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: API and CLI for everything (#5838)
Oleg Isonen1ddf6b02c967
diff --git a/apps/builder/app/builder/features/breakpoints/breakpoints-container.tsx b/apps/builder/app/builder/features/breakpoints/breakpoints-container.tsxindex df4dfedd14..2008804dba 100644--- a/apps/builder/app/builder/features/breakpoints/breakpoints-container.tsx+++ b/apps/builder/app/builder/features/breakpoints/breakpoints-container.tsx@@ -11,7 +11,8 @@ import { BreakpointsSelector } from "./breakpoints-selector";import { BreakpointsMenu } from "./breakpoints-menu";import { BreakpointsEditor } from "./breakpoints-editor";import { ConfirmationDialog } from "./confirmation-dialog";-import { $breakpointsMenuView, isBaseBreakpoint } from "~/shared/breakpoints";+import { $breakpointsMenuView } from "~/shared/breakpoints";+import { isBaseBreakpoint } from "@webstudio-is/project-build/runtime/breakpoints";import { setCanvasWidth } from "../../shared/calc-canvas-width";import { serverSyncStore } from "~/shared/sync/sync-stores";import type { Breakpoint } from "@webstudio-is/sdk";diff --git a/apps/builder/app/builder/features/breakpoints/breakpoints-editor.tsx b/apps/builder/app/builder/features/breakpoints/breakpoints-editor.tsxindex 9cea7c8848..1d670b1906 100644--- a/apps/builder/app/builder/features/breakpoints/breakpoints-editor.tsx+++ b/apps/builder/app/builder/features/breakpoints/breakpoints-editor.tsx@@ -26,7 +26,7 @@ import {groupBreakpoints,hasReachedBreakpointLimit,isBaseBreakpoint,-} from "~/shared/breakpoints";+} from "@webstudio-is/project-build/runtime/breakpoints";import { serverSyncStore } from "~/shared/sync/sync-stores";import { ConditionInput } from "./condition-input";import { CssValueInput } from "~/builder/features/style-panel/shared/css-value-input";diff --git a/apps/builder/app/builder/features/breakpoints/breakpoints-menu.tsx b/apps/builder/app/builder/features/breakpoints/breakpoints-menu.tsxindex b5cfa13344..2c88a24bfb 100644--- a/apps/builder/app/builder/features/breakpoints/breakpoints-menu.tsx+++ b/apps/builder/app/builder/features/breakpoints/breakpoints-menu.tsx@@ -12,7 +12,7 @@ import {Button,} from "@webstudio-is/design-system";import { EllipsesIcon } from "@webstudio-is/icons";-import { groupBreakpoints } from "~/shared/breakpoints";+import { groupBreakpoints } from "@webstudio-is/project-build/runtime/breakpoints";import { $selectedBreakpointId } from "~/shared/nano-states";import { setCanvasWidth } from "../../shared/calc-canvas-width";diff --git a/apps/builder/app/builder/features/breakpoints/breakpoints-selector.tsx b/apps/builder/app/builder/features/breakpoints/breakpoints-selector.tsxindex 88404365db..4a05906f66 100644--- a/apps/builder/app/builder/features/breakpoints/breakpoints-selector.tsx+++ b/apps/builder/app/builder/features/breakpoints/breakpoints-selector.tsx@@ -17,7 +17,10 @@ import {$selectedBreakpointId,} from "~/shared/nano-states";import { $breakpoints } from "~/shared/sync/data-stores";-import { groupBreakpoints, isBaseBreakpoint } from "~/shared/breakpoints";+import {+ groupBreakpoints,+ isBaseBreakpoint,+} from "@webstudio-is/project-build/runtime/breakpoints";import { setCanvasWidth } from "../../shared/calc-canvas-width";import { $canvasWidth } from "~/builder/shared/nano-states";import { useDebouncedCallback } from "use-debounce";diff --git a/apps/builder/app/builder/features/breakpoints/canvas-settings-popover.tsx b/apps/builder/app/builder/features/breakpoints/canvas-settings-popover.tsxindex 9df56d00a6..bd15470aff 100644--- a/apps/builder/app/builder/features/breakpoints/canvas-settings-popover.tsx+++ b/apps/builder/app/builder/features/breakpoints/canvas-settings-popover.tsx@@ -11,7 +11,7 @@ import {Text,} from "@webstudio-is/design-system";import { WidthInput } from "./width-input";-import { minCanvasWidth } from "~/shared/breakpoints";+import { minCanvasWidth } from "~/shared/breakpoints-utils";import { $canvasWidth, $scale } from "~/builder/shared/nano-states";import { $selectedBreakpoint } from "~/shared/nano-states";import { ChevronDownIcon } from "@webstudio-is/icons";diff --git a/apps/builder/app/builder/features/breakpoints/cascade-indicator.tsx b/apps/builder/app/builder/features/breakpoints/cascade-indicator.tsxindex f020b988aa..f44d0a6dc2 100644--- a/apps/builder/app/builder/features/breakpoints/cascade-indicator.tsx+++ b/apps/builder/app/builder/features/breakpoints/cascade-indicator.tsx@@ -3,7 +3,7 @@ import { useStore } from "@nanostores/react";import { css, theme } from "@webstudio-is/design-system";import type { Breakpoint, Breakpoints } from "@webstudio-is/sdk";import { $breakpoints } from "~/shared/sync/data-stores";-import { isBaseBreakpoint } from "~/shared/breakpoints";+import { isBaseBreakpoint } from "@webstudio-is/project-build/runtime/breakpoints";const cascadeIndicatorStyle = css({position: "absolute",diff --git a/apps/builder/app/builder/features/command-panel/groups/data-variables-group.tsx b/apps/builder/app/builder/features/command-panel/groups/data-variables-group.tsxindex cf2908c02b..0da6b6af77 100644--- a/apps/builder/app/builder/features/command-panel/groups/data-variables-group.tsx+++ b/apps/builder/app/builder/features/command-panel/groups/data-variables-group.tsx@@ -24,7 +24,7 @@ import {focusCommandPanel,} from "../command-state";import { InstanceList, showInstance } from "../shared/instance-list";-import { deleteVariableMutable } from "~/shared/data-variables";+import { deleteVariableMutable } from "@webstudio-is/project-build/runtime/data";import { updateWebstudioData } from "~/shared/instance-utils/data";import {DeleteDataVariableDialog,@@ -33,7 +33,7 @@ import {import type { BaseOption } from "../shared/types";import { formatUsageCount, getUsageSearchTerms } from "../shared/usage-utils";import { getInstanceLabel } from "~/builder/shared/instance-label";-import { findVariableUsagesByInstance } from "~/shared/data-variables";+import { findVariableUsagesByInstance } from "@webstudio-is/project-build/runtime/data";export type DataVariableOption = BaseOption & {type: "dataVariable";diff --git a/apps/builder/app/builder/features/command-panel/groups/duplicate-tokens-group.tsx b/apps/builder/app/builder/features/command-panel/groups/duplicate-tokens-group.tsxindex 21c8755a89..4e3692b87d 100644--- a/apps/builder/app/builder/features/command-panel/groups/duplicate-tokens-group.tsx+++ b/apps/builder/app/builder/features/command-panel/groups/duplicate-tokens-group.tsx@@ -20,7 +20,7 @@ import type { Instance, StyleSource } from "@webstudio-is/sdk";import { $styleSources } from "~/shared/sync/data-stores";import { $selectedStyleSources } from "~/shared/nano-states";import { $styles, $breakpoints } from "~/shared/sync/data-stores";-import { findDuplicateTokens } from "~/shared/style-source-utils";+import { findDuplicateTokens } from "@webstudio-is/project-build/runtime/styles";import { $styleSourceUsages } from "~/builder/shared/style-source-actions";import { InstanceList, showInstance } from "../shared/instance-list";import {diff --git a/apps/builder/app/builder/features/command-panel/groups/instances-group.test.tsx b/apps/builder/app/builder/features/command-panel/groups/instances-group.test.tsxnew file mode 100644index 0000000000..bc20cdf7b4--- /dev/null+++ b/apps/builder/app/builder/features/command-panel/groups/instances-group.test.tsx@@ -0,0 +1,49 @@+import { beforeEach, describe, expect, test } from "vitest";+import { coreMetas, elementComponent } from "@webstudio-is/sdk";+import type { Instances } from "@webstudio-is/sdk";+import { createDefaultPages } from "@webstudio-is/project-build";+import { $registeredComponentMetas } from "~/shared/nano-states";+import { $instances, $pages, $props } from "~/shared/sync/data-stores";+import {+ $commandSearch,+ closeCommandPanel,+ openCommandPanel,+} from "../command-state";+import { $instanceOptions } from "./instances-group";++beforeEach(() => {+ closeCommandPanel();+ $commandSearch.set("");+ $instances.set(new Map());+ $props.set(new Map());+ $pages.set(undefined);+ $registeredComponentMetas.set(new Map(Object.entries(coreMetas)));+});++describe("$instanceOptions", () => {+ test("does not build instance options until command search has text", () => {+ const instances: Instances = new Map([+ [+ "box",+ {+ type: "instance",+ id: "box",+ component: elementComponent,+ tag: "div",+ children: [],+ },+ ],+ ]);+ $instances.set(instances);+ $pages.set(createDefaultPages({ rootInstanceId: "box" }));++ openCommandPanel();++ expect($instanceOptions.get()).toEqual([]);++ $commandSearch.set("box");++ expect($instanceOptions.get()).toHaveLength(1);+ expect($instanceOptions.get()[0]?.instance.id).toBe("box");+ });+});diff --git a/apps/builder/app/builder/features/command-panel/groups/command-panel-options.test.tsx b/apps/builder/app/builder/features/command-panel/groups/tags-group.test.tsxsimilarity index 70%rename from apps/builder/app/builder/features/command-panel/groups/command-panel-options.test.tsxrename to apps/builder/app/builder/features/command-panel/groups/tags-group.test.tsxindex 7a981b371b..dae6899491 100644--- a/apps/builder/app/builder/features/command-panel/groups/command-panel-options.test.tsx+++ b/apps/builder/app/builder/features/command-panel/groups/tags-group.test.tsx@@ -13,7 +13,6 @@ import {closeCommandPanel,openCommandPanel,} from "../command-state";-import { $instanceOptions } from "./instances-group";import { $tagOptions } from "./tags-group";beforeEach(() => {@@ -26,34 +25,6 @@ beforeEach(() => {$registeredComponentMetas.set(new Map(Object.entries(coreMetas)));});-describe("$instanceOptions", () => {- test("does not build instance options until command search has text", () => {- const instances: Instances = new Map([- [- "box",- {- type: "instance",- id: "box",- component: elementComponent,- tag: "div",- children: [],- },- ],- ]);- $instances.set(instances);- $pages.set(createDefaultPages({ rootInstanceId: "box" }));-- openCommandPanel();-- expect($instanceOptions.get()).toEqual([]);-- $commandSearch.set("box");-- expect($instanceOptions.get()).toHaveLength(1);- expect($instanceOptions.get()[0]?.instance.id).toBe("box");- });-});-describe("$tagOptions", () => {test("uses indexed html tags from props when validating content model", () => {const instances: Instances = new Map([diff --git a/apps/builder/app/builder/features/marketplace/templates.tsx b/apps/builder/app/builder/features/marketplace/templates.tsxindex ac336436f9..6769593f96 100644--- a/apps/builder/app/builder/features/marketplace/templates.tsx+++ b/apps/builder/app/builder/features/marketplace/templates.tsx@@ -3,7 +3,8 @@ import { insertWebstudioFragmentAt } from "~/shared/instance-utils/insert";import {detectFragmentTokenConflicts,detectPageTokenConflicts,-} from "~/shared/instance-utils/fragment";+ extractWebstudioFragment,+} from "@webstudio-is/project-build/runtime/fragment";import { updateWebstudioData } from "~/shared/instance-utils/data";import { useMemo } from "react";import {@@ -31,9 +32,10 @@ import type { MarketplaceProduct } from "@webstudio-is/project-build";import { mapGroupBy } from "~/shared/shim";import { CollapsibleSection } from "~/builder/shared/collapsible-section";import { builderUrl } from "~/shared/router-utils";-import { extractWebstudioFragment } from "~/shared/instance-utils/fragment";+import { getWebstudioData } from "~/shared/instance-utils/data";import { builderApi } from "~/shared/builder-api";-import { insertPageCopyMutable } from "~/shared/page-utils";+import { insertPageCopyMutable } from "@webstudio-is/project-build/runtime/page-copy";+import { $project } from "~/shared/sync/data-stores";import { Card } from "./card";import type { MarketplaceOverviewItem } from "~/shared/marketplace/types";import { selectPage } from "~/shared/nano-states";@@ -70,7 +72,10 @@ const insertSection = async ({if (insertable.position === "end") {insertable.position = "after";}- const conflicts = detectFragmentTokenConflicts({ fragment });+ const conflicts = detectFragmentTokenConflicts({+ fragment,+ targetData: getWebstudioData(),+ });const conflictResolution =conflicts.length > 0? await builderApi.showTokenConflictDialog(conflicts)@@ -86,16 +91,25 @@ const insertPage = async ({data: WebstudioData;pageId: Page["id"];}) => {- const conflicts = detectPageTokenConflicts({ sourceData, pageId });+ const conflicts = detectPageTokenConflicts({+ sourceData,+ targetData: getWebstudioData(),+ pageId,+ });const conflictResolution =conflicts.length > 0? await builderApi.showTokenConflictDialog(conflicts): "theirs";let newPageId: undefined | Page["id"];+ const projectId = $project.get()?.id;+ if (projectId === undefined) {+ return;+ }updateWebstudioData((targetData) => {newPageId = insertPageCopyMutable({source: { data: sourceData, pageId },target: { data: targetData, folderId: ROOT_FOLDER_ID },+ projectId,conflictResolution,});});diff --git a/apps/builder/app/builder/features/pages/custom-metadata.tsx b/apps/builder/app/builder/features/pages/custom-metadata.tsxindex 035e2b416b..fe01529b7c 100644--- a/apps/builder/app/builder/features/pages/custom-metadata.tsx+++ b/apps/builder/app/builder/features/pages/custom-metadata.tsx@@ -12,7 +12,7 @@ import {} from "@webstudio-is/design-system";import { TrashIcon, PlusIcon } from "@webstudio-is/icons";import { isLiteralExpression } from "@webstudio-is/sdk";-import { computeExpression } from "~/shared/data-variables";+import { computeExpression } from "@webstudio-is/project-build/runtime/data";import {BindingControl,BindingPopover,diff --git a/apps/builder/app/builder/features/pages/folder-settings.tsx b/apps/builder/app/builder/features/pages/folder-settings.tsxindex eaefd988f0..8303f4bc4e 100644--- a/apps/builder/app/builder/features/pages/folder-settings.tsx+++ b/apps/builder/app/builder/features/pages/folder-settings.tsx@@ -24,6 +24,10 @@ import {findParentFolderByChildId,getFolderById,} from "@webstudio-is/sdk";+import {+ createFolderValue,+ isSlugAvailable,+} from "@webstudio-is/project-build/runtime/pages";import { nanoid } from "nanoid";import { useState, type FocusEventHandler } from "react";import slugify from "slugify";@@ -33,7 +37,10 @@ import { $pages } from "~/shared/sync/data-stores";import { $isDesignMode } from "~/shared/nano-states";import { serverSyncStore } from "~/shared/sync/sync-stores";import { Form } from "./form";-import { isSlugAvailable, registerFolderChildMutable } from "./page-utils";+import {+ insertFolderMutable,+ updateFolderFieldsMutable,+} from "~/shared/page-utils/tree";import { useDraftValue } from "~/builder/shared/use-draft-value";import { copyFolder } from "~/shared/copy-paste/copy-paste";import { PageItemActionsDropdown } from "./page-item-actions";@@ -295,16 +302,15 @@ const createFolder = (folderId: Folder["id"], values: Values) => {if (pages === undefined) {return;}- pages.folders.set(folderId, {- id: folderId,- name: values.name,- slug: values.slug,- children: [],- } satisfies Folder);- const parentFolder =- getFolderById(pages, values.parentFolderId) ??- getFolderById(pages, pages.rootFolderId);- parentFolder?.children.push(folderId);+ insertFolderMutable({+ pages,+ folder: createFolderValue({+ folderId,+ name: values.name,+ slug: values.slug,+ }),+ parentFolderId: values.parentFolderId,+ });});};@@ -317,15 +323,7 @@ const updateFolder = (folderId: Folder["id"], values: Partial<Values>) => {if (folder === undefined || folderId === pages.rootFolderId) {return;}- if (values.name !== undefined) {- folder.name = values.name;- }- if (values.slug !== undefined) {- folder.slug = values.slug;- }- if (values.parentFolderId !== undefined) {- registerFolderChildMutable(pages, folderId, values.parentFolderId);- }+ updateFolderFieldsMutable({ folder, folderId, pages, values });});};diff --git a/apps/builder/app/builder/features/pages/page-settings/page-settings.test.ts b/apps/builder/app/builder/features/pages/page-settings/page-settings.test.tsindex 811aa4b2a7..d5a0579129 100644--- a/apps/builder/app/builder/features/pages/page-settings/page-settings.test.ts+++ b/apps/builder/app/builder/features/pages/page-settings/page-settings.test.ts@@ -1,26 +1,8 @@-import { describe, expect, test, vi } from "vitest";+import { describe, expect, test } from "vitest";import type { Folder, Page, Pages } from "@webstudio-is/sdk";import { ROOT_FOLDER_ID } from "@webstudio-is/sdk";import type { Values } from "./shared";--const mocks = vi.hoisted(() => ({- isPathAvailable: vi.fn(() => true),-}));--vi.mock("../page-utils", () => ({- registerFolderChildMutable: () => undefined,- cleanupChildRefsMutable: () => undefined,- duplicatePage: () => undefined,- nameToPath: (_pages: unknown, name: string) =>- name === "" ? "" : `/${name.toLowerCase()}`,- isPathAvailable: mocks.isPathAvailable,- $pageRootScope: {- get: () => ({ variableValues: new Map(), scope: {}, aliases: new Map() }),- subscribe: () => () => undefined,- },-}));--const { __testing__ } = await import("./page-settings");+import { __testing__ } from "./page-settings";const {addContentModePathError,@@ -206,11 +188,12 @@ describe("addContentModePathError", () => {describe("validateValues", () => {test("accumulates duplicate path errors from the general section", () => {- mocks.isPathAvailable.mockReturnValueOnce(false);+ const currentPage = createPage({ id: "page-id", path: "/current" });+ const existingPage = createPage({ id: "existing", path: "/taken" });const errors = validateValues(- createPages(),- "page-id",+ createPages({ pages: [homePage, currentPage, existingPage] }),+ currentPage.id,createValues({path: "/taken",}),diff --git a/apps/builder/app/builder/features/pages/page-settings/page-settings.tsx b/apps/builder/app/builder/features/pages/page-settings/page-settings.tsxindex 7d2ec939ba..66f9ac520b 100644--- a/apps/builder/app/builder/features/pages/page-settings/page-settings.tsx+++ b/apps/builder/app/builder/features/pages/page-settings/page-settings.tsx@@ -10,7 +10,6 @@ import {findParentFolderByChildId,getPagePath,getHomePage,- elementComponent,isLiteralExpression,} from "@webstudio-is/sdk";import { validateBasicAuth } from "@webstudio-is/wsauth";@@ -39,17 +38,20 @@ import { $openProjectSettings } from "~/shared/nano-states/project-settings";import { $instances, $pages } from "~/shared/sync/data-stores";import { serverSyncStore } from "~/shared/sync/sync-stores";import { selectInstance } from "~/shared/nano-states";+import { $pageRootScope, duplicatePage, nameToPath } from "../page-utils";import {- registerFolderChildMutable,cleanupChildRefsMutable,- $pageRootScope,- duplicatePage,- nameToPath,-} from "../page-utils";+ registerFolderChildMutable,+} from "~/shared/page-utils/tree";import { CollapsibleSection } from "~/builder/shared/collapsible-section";import { Form } from "../form";import { findMatchingRedirect } from "~/shared/project-settings/utils";import { isContentModePagePath } from "@webstudio-is/project/content-mode-permissions";+import {+ createPageRootInstance,+ createPageValue,+} from "@webstudio-is/project-build/runtime/pages";+import { updatePageFieldsMutable } from "~/shared/page-utils/meta";import { AuthSection, validateAuthSection } from "./section-auth";import {CustomMetadataSection,@@ -545,21 +547,18 @@ const createPage = (pageId: Page["id"], values: Values) => {return;}const rootInstanceId = nanoid();- pages.pages.set(pageId, {- id: pageId,- name: values.name,- path: values.path,- title: values.title,- rootInstanceId,- meta: getInitialPageMeta(values),- });- instances.set(rootInstanceId, {- type: "instance",- id: rootInstanceId,- component: elementComponent,- tag: "body",- children: [],- });+ pages.pages.set(+ pageId,+ createPageValue({+ pageId,+ name: values.name,+ path: values.path,+ title: values.title,+ rootInstanceId,+ meta: getInitialPageMeta(values),+ })+ );+ instances.set(rootInstanceId, createPageRootInstance(rootInstanceId));registerFolderChildMutable(pages, pageId, values.parentFolderId);selectInstance(undefined);}@@ -572,60 +571,7 @@ export const updatePage = (pageId: Page["id"], values: Partial<Values>) => {values: Partial<Values>,pages: Pages) => {- if (values.name !== undefined) {- page.name = values.name;- }- if (values.path !== undefined) {- page.path = page.id === pages.homePageId ? "" : values.path;- }- if (values.title !== undefined) {- page.title = values.title;- }-- if (values.description !== undefined) {- page.meta.description = values.description;- }-- if (values.excludePageFromSearch !== undefined) {- page.meta.excludePageFromSearch = values.excludePageFromSearch;- }-- if (values.language !== undefined) {- page.meta.language =- values.language.length > 0 ? values.language : undefined;- }-- if ("status" in values) {- page.meta.status = values.status;- }-- if (values.redirect !== undefined) {- page.meta.redirect =- values.redirect.length > 0 ? values.redirect : undefined;- }-- if (values.socialImageAssetId !== undefined) {- page.meta.socialImageAssetId =- values.socialImageAssetId.length > 0- ? values.socialImageAssetId- : undefined;- }- if (values.socialImageUrl !== undefined) {- page.meta.socialImageUrl =- values.socialImageUrl.length > 0 ? values.socialImageUrl : undefined;- }-- if (values.customMetas !== undefined) {- page.meta.custom = values.customMetas;- }-- if (values.documentType !== undefined) {- page.meta.documentType = values.documentType;- }-- if (values.content !== undefined) {- page.meta.content = values.content;- }+ updatePageFieldsMutable({ page, pages, values });if (values.auth !== undefined) {page.meta.auth = getAuthFromValues({@@ -634,10 +580,6 @@ export const updatePage = (pageId: Page["id"], values: Partial<Values>) => {});}- if (values.parentFolderId !== undefined) {- registerFolderChildMutable(pages, page.id, values.parentFolderId);- }-if (values.marketplace !== undefined) {page.marketplace ??= {};page.marketplace.include = values.marketplace.include;diff --git a/apps/builder/app/builder/features/pages/page-settings/section-custom-metadata.tsx b/apps/builder/app/builder/features/pages/page-settings/section-custom-metadata.tsxindex 6853bed173..609a435140 100644--- a/apps/builder/app/builder/features/pages/page-settings/section-custom-metadata.tsx+++ b/apps/builder/app/builder/features/pages/page-settings/section-custom-metadata.tsx@@ -1,7 +1,7 @@import { z } from "zod";import { InputErrorsTooltip } from "@webstudio-is/design-system";import { CustomMetadata } from "../custom-metadata";-import { computeExpression } from "~/shared/data-variables";+import { computeExpression } from "@webstudio-is/project-build/runtime/data";import type { Errors, OnChange, Values } from "./shared";const customMetadataValues = z.object({diff --git a/apps/builder/app/builder/features/pages/page-settings/section-general.tsx b/apps/builder/app/builder/features/pages/page-settings/section-general.tsxindex 9642568cf3..bc8cfbc0a4 100644--- a/apps/builder/app/builder/features/pages/page-settings/section-general.tsx+++ b/apps/builder/app/builder/features/pages/page-settings/section-general.tsx@@ -33,9 +33,10 @@ import {BindingControl,BindingPopover,} from "~/builder/shared/binding-popover";-import { computeExpression } from "~/shared/data-variables";+import { computeExpression } from "@webstudio-is/project-build/runtime/data";import { $permissions } from "~/shared/nano-states";-import { $pageRootScope, isPathAvailable } from "../page-utils";+import { $pageRootScope } from "../page-utils";+import { isPathAvailable } from "@webstudio-is/project-build/runtime/pages";import { validatePathnamePattern } from "~/builder/shared/url-pattern";import {LOOP_ERROR,diff --git a/apps/builder/app/builder/features/pages/page-settings/section-marketplace.tsx b/apps/builder/app/builder/features/pages/page-settings/section-marketplace.tsxindex d80d1c4e31..21781a882c 100644--- a/apps/builder/app/builder/features/pages/page-settings/section-marketplace.tsx+++ b/apps/builder/app/builder/features/pages/page-settings/section-marketplace.tsx@@ -9,7 +9,7 @@ import {Switch,theme,} from "@webstudio-is/design-system";-import { computeExpression } from "~/shared/data-variables";+import { computeExpression } from "@webstudio-is/project-build/runtime/data";import { ImageControl } from "~/shared/project-settings";import { $assets } from "~/shared/sync/data-stores";import { Card } from "../../marketplace/card";diff --git a/apps/builder/app/builder/features/pages/page-settings/section-search.tsx b/apps/builder/app/builder/features/pages/page-settings/section-search.tsxindex 05c46f368f..22f4d36e6f 100644--- a/apps/builder/app/builder/features/pages/page-settings/section-search.tsx+++ b/apps/builder/app/builder/features/pages/page-settings/section-search.tsx@@ -17,7 +17,7 @@ import {BindingControl,BindingPopover,} from "~/builder/shared/binding-popover";-import { computeExpression } from "~/shared/data-variables";+import { computeExpression } from "@webstudio-is/project-build/runtime/data";import { useStore } from "@nanostores/react";import { $assets, $pages } from "~/shared/sync/data-stores";import { $pageRootScope } from "../page-utils";diff --git a/apps/builder/app/builder/features/pages/page-settings/section-social-image.tsx b/apps/builder/app/builder/features/pages/page-settings/section-social-image.tsxindex e1d9b4a52e..4cda7f5591 100644--- a/apps/builder/app/builder/features/pages/page-settings/section-social-image.tsx+++ b/apps/builder/app/builder/features/pages/page-settings/section-social-image.tsx@@ -12,7 +12,7 @@ import {BindingControl,BindingPopover,} from "~/builder/shared/binding-popover";-import { computeExpression } from "~/shared/data-variables";+import { computeExpression } from "@webstudio-is/project-build/runtime/data";import { ImageControl } from "~/shared/project-settings";import { $assets } from "~/shared/sync/data-stores";import { isLiteralExpression } from "@webstudio-is/sdk";diff --git a/apps/builder/app/builder/features/pages/page-settings/section-text-content.tsx b/apps/builder/app/builder/features/pages/page-settings/section-text-content.tsxindex 32391c90e7..f7b3c1fa6a 100644--- a/apps/builder/app/builder/features/pages/page-settings/section-text-content.tsx+++ b/apps/builder/app/builder/features/pages/page-settings/section-text-content.tsx@@ -7,7 +7,7 @@ import {BindingControl,BindingPopover,} from "~/builder/shared/binding-popover";-import { computeExpression } from "~/shared/data-variables";+import { computeExpression } from "@webstudio-is/project-build/runtime/data";import { $pageRootScope } from "../page-utils";import type { Errors, OnChange, Values } from "./shared";diff --git a/apps/builder/app/builder/features/pages/page-utils.test.ts b/apps/builder/app/builder/features/pages/page-utils.test.tsindex 7dbdc3ef9a..04c353d71c 100644--- a/apps/builder/app/builder/features/pages/page-utils.test.ts+++ b/apps/builder/app/builder/features/pages/page-utils.test.ts@@ -17,18 +17,16 @@ import {type WebstudioData,} from "@webstudio-is/sdk";import {- cleanupChildRefsMutable,deleteFolderWithChildrenMutable,- getAllChildrenAndSelf,- isSlugAvailable,- registerFolderChildMutable,- reparentOrphansMutable,$pageRootScope,- isPathAvailable,- reparentPageOrFolderMutable,+ canDrop,deletePageMutable,deleteTemplateMutable,+ duplicateFolder,+ duplicateTemplate,+ getStoredDropTarget,instantiateTemplate,+ isFolder,} from "./page-utils";import { $dataSourceVariables } from "~/shared/nano-states";import {@@ -144,382 +142,6 @@ const createWebstudioData = ({assets: new Map(),}) as unknown as WebstudioData;-describe("reparentOrphansMutable", () => {- // We must deal with the fact there can be an orphaned folder or page in a collaborative mode,- // because user A can add a page to a folder while user B deletes the folder without receiving the create page yet.- test("reparent orphans to the root", () => {- const { pages } = createPages();- pages.pages.set("pageId", {- id: "pageId",- meta: {},- name: "Page",- path: "/page",- rootInstanceId: "rootInstanceId",- title: `"Page"`,- });- pages.folders.set("folderId", {- id: "folderId",- name: "Folder",- slug: "folder",- children: [],- });- reparentOrphansMutable(pages);- const rootFolder = Array.from(pages.folders.values()).find(isRootFolder);- expect(rootFolder).toEqual({- id: ROOT_FOLDER_ID,- name: "Root",- slug: "",- children: ["homePageId", "folderId", "pageId"],- });- });-- test("recreates missing root folder with rootFolderId", () => {- const { pages } = createPages();- pages.rootFolderId = "customRoot";- pages.folders = new Map();- pages.pages.set("pageId", {- id: "pageId",- meta: {},- name: "Page",- path: "/page",- rootInstanceId: "rootInstanceId",- title: `"Page"`,- });-- reparentOrphansMutable(pages);-- expect(pages.folders.get("customRoot")).toEqual({- id: "customRoot",- name: "Root",- slug: "",- children: ["homePageId", "pageId"],- });- });-- test("keeps home page first in root folder", () => {- const { pages } = createPages();- pages.folders.set("folderId", {- id: "folderId",- name: "Folder",- slug: "folder",- children: ["homePageId"],- });- pages.folders.get(pages.rootFolderId)!.children = ["folderId"];-- reparentOrphansMutable(pages);-- expect(pages.folders.get(pages.rootFolderId)?.children).toEqual([- "homePageId",- "folderId",- ]);- expect(pages.folders.get("folderId")?.children).toEqual([]);- });-});--describe("cleanupChildRefsMutable", () => {- test("cleanup refs", () => {- const {- pages: { folders },- } = createPages();- folders.set("folderId", {- id: "folderId",- name: "Folder",- slug: "folder",- children: [],- });- const rootFolder = Array.from(folders.values()).find(isRootFolder);- rootFolder?.children.push("folderId");- cleanupChildRefsMutable("folderId", folders);- expect(rootFolder).toEqual({- id: ROOT_FOLDER_ID,- name: "Root",- slug: "",- children: ["homePageId"],- });- });-- test("removes duplicate refs from every folder", () => {- const {- pages: { folders },- } = createPages();- folders.get(ROOT_FOLDER_ID)?.children.push("folderId", "folderId");- folders.set("folderId", {- id: "folderId",- name: "Folder",- slug: "folder",- children: ["folderId"],- });-- cleanupChildRefsMutable("folderId", folders);-- expect(folders.get(ROOT_FOLDER_ID)?.children).toEqual(["homePageId"]);- expect(folders.get("folderId")?.children).toEqual([]);- });-});--describe("isSlugAvailable", () => {- const {- pages: { folders },- register,- f,- } = createPages();-- register([- f("folder1", [f("folder1-1")]),- f("folder2-1", ""),- f("folder2-2", ""),- ]);-- const rootFolder = Array.from(folders.values()).find(isRootFolder)!;-- test("available in the root", () => {- expect(isSlugAvailable("folder", folders, rootFolder.id)).toBe(true);- });-- test("not available in the root", () => {- expect(isSlugAvailable("folder1", folders, rootFolder.id)).toBe(false);- });-- test("available in folder1", () => {- expect(isSlugAvailable("folder", folders, "folder1")).toBe(true);- });-- test("not available in folder1", () => {- expect(isSlugAvailable("folder1-1", folders, "folder1")).toBe(false);- });-- test("existing folder can have a matching slug when its the same id/folder", () => {- expect(isSlugAvailable("folder1-1", folders, "folder1", "folder1-1")).toBe(- true- );- });-- test("empty folder slug can be defined multiple times", () => {- expect(isSlugAvailable("", folders, "rootInstanceId")).toBe(true);- });-});--describe("isPathAvailable", () => {- const { f, p, register, pages } = createPages();-- register([- f("folder1", [p("page1", "/page")]),- f("folder2", [p("page2", "/page")]),- f("/", [p("page3", "/page")]),- ]);-- test("/folder2/page existing page", () => {- expect(- isPathAvailable({- pages,- path: "/page",- parentFolderId: "folder2",- pageId: "page2",- })- ).toBe(true);- });-- test("/folder2/page new page", () => {- expect(- isPathAvailable({ pages, path: "/page", parentFolderId: "folder2" })- ).toBe(false);- });-- test("/folder2/page1 new page", () => {- expect(- isPathAvailable({ pages, path: "/page1", parentFolderId: "folder2" })- ).toBe(true);- });-- test("/page new page", () => {- expect(isPathAvailable({ pages, path: "/page", parentFolderId: "/" })).toBe(- false- );- });-});--describe("registerFolderChildMutable", () => {- test("register a folder child in the root via fallback", () => {- const { pages } = createPages();- const { folders } = pages;- registerFolderChildMutable(pages, "folderId");- const rootFolder = Array.from(folders.values()).find(isRootFolder);- expect(rootFolder?.children).toEqual(["homePageId", "folderId"]);- });-- test("register a folder child in a provided folder", () => {- const { pages } = createPages();- const { folders } = pages;- const folder = {- id: "folderId",- name: "Folder",- slug: "folder",- children: [],- };- folders.set(folder.id, folder);- registerFolderChildMutable(pages, "folderId2", "folderId");- expect(folder.children).toEqual(["folderId2"]);- });-- test("register in a provided folder & cleanup old refs", () => {- const { pages } = createPages();- const { folders } = pages;- const folder = {- id: "folderId",- name: "Folder",- slug: "folder",- children: [],- };- folders.set(folder.id, folder);- const rootFolder = Array.from(folders.values()).find(isRootFolder);- registerFolderChildMutable(pages, "folderId", ROOT_FOLDER_ID);- registerFolderChildMutable(pages, "folderId2", ROOT_FOLDER_ID);-- expect(rootFolder?.children).toEqual([- "homePageId",- "folderId",- "folderId2",- ]);-- // Moving folderId from root to folderId- registerFolderChildMutable(pages, "folderId2", "folderId");-- expect(rootFolder?.children).toEqual(["homePageId", "folderId"]);- expect(folder.children).toEqual(["folderId2"]);- });-- test("uses rootFolderId for fallback instead of hardcoded root id", () => {- const { pages } = createPages();- pages.rootFolderId = "customRoot";- pages.folders = new Map([- [- "customRoot",- {- id: "customRoot",- name: "Root",- slug: "",- children: [],- },- ],- ]);-- registerFolderChildMutable(pages, "folderId");-- expect(pages.folders.get("customRoot")?.children).toEqual(["folderId"]);- });-});--describe("reparent pages and folders", () => {- test("move page up within single parent", () => {- const { f, p, register, pages } = createPages();- register([- f("folder", [- p("page1", "/page1"),- p("page2", "/page2"),- p("page3", "/page3"),- ]),- ]);- reparentPageOrFolderMutable(pages.folders, "page3", "folder", 1);- const folder = pages.folders.get("folder");- expect(folder?.children).toEqual(["page1", "page3", "page2"]);- });-- test("move page down within single parent", () => {- const { f, p, register, pages } = createPages();- register([- f("folder", [- p("page1", "/page1"),- p("page2", "/page2"),- p("page3", "/page3"),- ]),- ]);- reparentPageOrFolderMutable(pages.folders, "page1", "folder", 2);- const folder = pages.folders.get("folder");- expect(folder?.children).toEqual(["page2", "page1", "page3"]);- });-- test("move page into another folder", () => {- const { f, p, register, pages } = createPages();- register([- f("folder1", [p("page1", "/page1"), p("page2", "/page2")]),- f("folder2", [p("page3", "/page3")]),- ]);- reparentPageOrFolderMutable(pages.folders, "page1", "folder2", 1);- const folder1 = pages.folders.get("folder1");- const folder2 = pages.folders.get("folder2");- expect(folder1?.children).toEqual(["page2"]);- expect(folder2?.children).toEqual(["page3", "page1"]);- });-- test("move folder into another folder", () => {- const { f, register, pages } = createPages();- register([f("folder1", []), f("folder2", [])]);- reparentPageOrFolderMutable(pages.folders, "folder1", "folder2", 1);- expect(Array.from(pages.folders.values())).toEqual([- expect.objectContaining({- id: "root",- children: ["homePageId", "folder2"],- }),- expect.objectContaining({ id: "folder1", children: [] }),- expect.objectContaining({ id: "folder2", children: ["folder1"] }),- ]);- });-- test("prevent reparanting folder into itself", () => {- const { f, register, pages } = createPages();- register([f("folder1", [])]);- reparentPageOrFolderMutable(pages.folders, "folder1", "folder1", 1);- expect(Array.from(pages.folders.values())).toEqual([- expect.objectContaining({- id: "root",- children: ["homePageId", "folder1"],- }),- expect.objectContaining({ id: "folder1", children: [] }),- ]);- });-- test("prevent reparanting folder own children", () => {- const { f, register, pages } = createPages();- register([f("folder1", [f("folder2", [])])]);- reparentPageOrFolderMutable(pages.folders, "folder1", "folder2", 1);- expect(Array.from(pages.folders.values())).toEqual([- expect.objectContaining({- id: "root",- children: ["homePageId", "folder1"],- }),- expect.objectContaining({ id: "folder2", children: [] }),- expect.objectContaining({ id: "folder1", children: ["folder2"] }),- ]);- });-- test("does not remove unrelated child when item is missing from previous parent", () => {- const { f, p, register, pages } = createPages();- register([f("folder", [p("page1", "/page1"), p("page2", "/page2")])]);-- reparentPageOrFolderMutable(pages.folders, "page3", "folder", 1);-- expect(pages.folders.get("folder")?.children).toEqual(["page1", "page2"]);- });-});--describe("getAllChildrenAndSelf", () => {- const folders = toMap<Folder>([- { id: "1", name: "1", slug: "1", children: ["2"] },- { id: "2", name: "2", slug: "2", children: ["3", "page1"] },- { id: "3", name: "3", slug: "3", children: ["page2"] },- ]);-- test("get nested folders", () => {- const result = getAllChildrenAndSelf("1", folders, "folder");- expect(result).toEqual(["1", "2", "3"]);- });-- test("get nested pages", () => {- const result = getAllChildrenAndSelf("1", folders, "page");- expect(result).toEqual(["page2", "page1"]);- });-});-describe("deleteFolderWithChildrenMutable", () => {const pages = (): Pages => ({homePageId: "homePageId",@@ -961,23 +583,17 @@ describe("isFolder", () => {test("should return true for existing folder id", async () => {const { pages: pagesData, register, f } = createPages();register([f("folder1", [])]);-- const { isFolder } = await import("./page-utils");expect(isFolder("folder1", pagesData.folders)).toBe(true);});test("should return false for non-existing folder id", async () => {const { pages: pagesData } = createPages();-- const { isFolder } = await import("./page-utils");expect(isFolder("nonexistent", pagesData.folders)).toBe(false);});test("should return false for page id", async () => {const { pages: pagesData, register, p } = createPages();register([p("page1", "/page1")]);-- const { isFolder } = await import("./page-utils");expect(isFolder("page1", pagesData.folders)).toBe(false);});});@@ -987,8 +603,6 @@ describe("getStoredDropTarget", () => {const { pages: pagesData, register, f, p } = createPages();register([f("folder1", [p("page1", "/page1")])]);$pages.set(pagesData);-- const { getStoredDropTarget } = await import("./page-utils");// selector order is [item, parent, grandparent, ...]const selector = ["page1", "folder1", ROOT_FOLDER_ID];const dropTarget = { parentLevel: 1, beforeLevel: 1 };@@ -1007,8 +621,6 @@ describe("getStoredDropTarget", () => {const { pages: pagesData, register, f, p } = createPages();register([f("folder1", [p("page1", "/page1"), p("page2", "/page2")])]);$pages.set(pagesData);-- const { getStoredDropTarget } = await import("./page-utils");const selector = ["page2", "folder1", ROOT_FOLDER_ID];const dropTarget = { parentLevel: 1, beforeLevel: 0 };@@ -1023,8 +635,6 @@ describe("getStoredDropTarget", () => {const { pages: pagesData, register, f, p } = createPages();register([f("folder1", [p("page1", "/page1"), p("page2", "/page2")])]);$pages.set(pagesData);-- const { getStoredDropTarget } = await import("./page-utils");const selector = ["page1", "folder1", ROOT_FOLDER_ID];const dropTarget = { parentLevel: 1, afterLevel: 0 };@@ -1038,8 +648,6 @@ describe("getStoredDropTarget", () => {test("should return undefined when parent id is undefined", async () => {const { pages: pagesData } = createPages();$pages.set(pagesData);-- const { getStoredDropTarget } = await import("./page-utils");const selector = ["page1"];const dropTarget = { parentLevel: 5 };@@ -1053,8 +661,6 @@ describe("canDrop", () => {test("should allow dropping inside a folder", async () => {const { pages: pagesData, register, f } = createPages();register([f("folder1", [])]);-- const { canDrop } = await import("./page-utils");const dropTarget = {parentId: "folder1",indexWithinChildren: 1,@@ -1066,8 +672,6 @@ describe("canDrop", () => {test("should forbid dropping on non-folder", async () => {const { pages: pagesData, register, p } = createPages();register([p("page1", "/page1")]);-- const { canDrop } = await import("./page-utils");const dropTarget = {parentId: "page1",indexWithinChildren: 0,@@ -1078,8 +682,6 @@ describe("canDrop", () => {test("should forbid dropping at index 0 of root folder", async () => {const { pages: pagesData } = createPages();-- const { canDrop } = await import("./page-utils");const dropTarget = {parentId: ROOT_FOLDER_ID,indexWithinChildren: 0,@@ -1090,8 +692,6 @@ describe("canDrop", () => {test("should allow dropping at index > 0 of root folder", async () => {const { pages: pagesData } = createPages();-- const { canDrop } = await import("./page-utils");const dropTarget = {parentId: ROOT_FOLDER_ID,indexWithinChildren: 1,@@ -1109,8 +709,6 @@ describe("canDrop", () => {slug: "",children: [],});-- const { canDrop } = await import("./page-utils");const dropTarget = {parentId: "customRoot",indexWithinChildren: 0,@@ -1129,8 +727,6 @@ describe("duplicateFolder", () => {$pages.set(pagesData);updateCurrentSystem(initialSystem);-- const { duplicateFolder } = await import("./page-utils");const newFolderId = duplicateFolder("folder1");expect(newFolderId).toBeDefined();@@ -1150,8 +746,6 @@ describe("duplicateFolder", () => {$pages.set(pagesData);updateCurrentSystem(initialSystem);-- const { duplicateFolder } = await import("./page-utils");const newFolderId = duplicateFolder("folder1");expect(newFolderId).toBeDefined();@@ -1161,7 +755,7 @@ describe("duplicateFolder", () => {? undefined: updatedPages.folders.get(newFolderId);expect(newFolder).toBeDefined();- // Note: Page duplication is handled by insertPageCopyMutable from ~/shared/page-utils+ // Note: Page duplication is handled by runtime insertPageCopyMutable// which requires full WebstudioData setup. Here we just verify the folder structure.expect(newFolder?.children.length).toBeGreaterThan(0);});@@ -1177,8 +771,6 @@ describe("duplicateFolder", () => {$pages.set(pagesData);updateCurrentSystem(initialSystem);-- const { duplicateFolder } = await import("./page-utils");const newFolderId = duplicateFolder("folder1");expect(newFolderId).toBeDefined();@@ -1209,8 +801,6 @@ describe("duplicateFolder", () => {$pages.set(pagesData);updateCurrentSystem(initialSystem);-- const { duplicateFolder } = await import("./page-utils");const newFolderId = duplicateFolder("folder1");expect(newFolderId).toBeDefined();@@ -1229,8 +819,6 @@ describe("duplicateFolder", () => {$pages.set(pagesData);updateCurrentSystem(initialSystem);-- const { duplicateFolder } = await import("./page-utils");const newFolderId = duplicateFolder("folder1");expect(newFolderId).toBeDefined();@@ -1249,8 +837,6 @@ describe("duplicateFolder", () => {$pages.set(pagesData);updateCurrentSystem(initialSystem);-- const { duplicateFolder } = await import("./page-utils");const newFolderId = duplicateFolder("folder1");const updatedPages = $pages.get()!;@@ -1338,8 +924,6 @@ describe("duplicateTemplate", () => {$styleSources.set(new Map());$styles.set(new Map());$assets.set(new Map());-- const { duplicateTemplate } = await import("./page-utils");const newTemplateId = duplicateTemplate("templateId");expect(newTemplateId).toBeDefined();diff --git a/apps/builder/app/builder/features/pages/page-utils.ts b/apps/builder/app/builder/features/pages/page-utils.tsindex 274d26bf45..72060d3520 100644--- a/apps/builder/app/builder/features/pages/page-utils.ts+++ b/apps/builder/app/builder/features/pages/page-utils.ts@@ -1,4 +1,8 @@-import { updateWebstudioData } from "~/shared/instance-utils/data";+import {+ applyBuilderPatchPayloadMutable,+ updateWebstudioData,+} from "~/shared/instance-utils/data";+import { isFragmentContentModeCopyableProp } from "~/shared/content-mode-copy-policy";import { computed } from "nanostores";import slugify from "slugify";import {@@ -8,19 +12,20 @@ import {type WebstudioData,type Pages,findPageByIdOrPath,- getPagePath,findParentFolderByChildId,- getAllFolders,- getAllPages,getFolderById,encodeDataSourceVariable,ROOT_INSTANCE_ID,systemParameter,SYSTEM_VARIABLE_ID,} from "@webstudio-is/sdk";-import { deleteInstanceMutable } from "~/shared/instance-utils/mutation";import { $variableValuesByInstanceSelector } from "~/shared/nano-states";-import { $dataSources, $pages } from "~/shared/sync/data-stores";+import { $dataSources, $pages, $project } from "~/shared/sync/data-stores";+import { getFolderDeletionTargets } from "@webstudio-is/project-build/runtime/pages";+import {+ collectExclusiveInstanceIds,+ createInstanceCleanupPayload,+} from "@webstudio-is/project-build/runtime/instances";import {createFolderCopyData,createTemplateCopyData,@@ -28,11 +33,12 @@ import {insertPageCopyMutable,insertPageFromTemplateMutable,insertTemplateCopyFromFragmentsMutable,-} from "~/shared/page-utils";+} from "@webstudio-is/project-build/runtime/page-copy";+import { cleanupChildRefsMutable } from "~/shared/page-utils/tree";import {$selectedPage,+ $registeredComponentMetas,getInstanceKey,- getInstancePath,} from "~/shared/nano-states";import { selectPage } from "~/shared/nano-states";@@ -55,205 +61,23 @@ export const nameToPath = (pages: Pages | undefined, name: string) => {return `${path}${suffix}`;};-/**- * When page or folder needs to be deleted or moved to a different parent,- * we want to cleanup any existing reference to it in current folder.- * We could do this in just one folder, but I think its more robust to check all,- * just in case we got double referencing.- */-export const cleanupChildRefsMutable = (- id: Folder["id"] | Page["id"],- folders: Pages["folders"]-) => {- for (const folder of Array.from(folders.values())) {- folder.children = folder.children.filter((childId) => childId !== id);- }-};--/**- * When page or folder is found and its not referenced in any other folder children,- * we consider it orphaned due to collaborative changes and we put it into the root folder.- */-export const reparentOrphansMutable = (pages: Pages) => {- const children = [pages.rootFolderId];- for (const folder of getAllFolders(pages)) {- children.push(...folder.children);- }-- let rootFolder = getFolderById(pages, pages.rootFolderId);- // Should never happen, but just in case.- if (rootFolder === undefined) {- rootFolder = {- id: pages.rootFolderId,- name: "Root",- slug: "",- children: [],- };- pages.folders.set(rootFolder.id, rootFolder);- }-- if (pages.pages.has(pages.homePageId)) {- let homePageRefCount = 0;- for (const folder of getAllFolders(pages)) {- for (const childId of folder.children) {- if (childId === pages.homePageId) {- homePageRefCount += 1;- }- }- }- if (rootFolder.children[0] !== pages.homePageId || homePageRefCount !== 1) {- cleanupChildRefsMutable(pages.homePageId, pages.folders);- rootFolder.children.unshift(pages.homePageId);- children.push(pages.homePageId);- }- }-- for (const folder of getAllFolders(pages)) {- // It's an orphan- if (children.includes(folder.id) === false) {- rootFolder.children.push(folder.id);- }- }-- for (const page of getAllPages(pages)) {- // It's an orphan- if (children.includes(page.id) === false) {- rootFolder.children.push(page.id);- }- }-};--/**- * Returns true if folder's slug is unique within it's future parent folder.- * Needed to verify if the folder can be nested under the parent folder without modifying slug.- */-export const isSlugAvailable = (- slug: string,- folders: Pages["folders"],- parentFolderId: Folder["id"],- // undefined folder id means new folder- folderId?: Folder["id"]+const deleteRootInstanceMutable = (+ data: WebstudioData,+ rootInstanceId: string) => {- // Empty slug can appear any amount of times.- if (slug === "") {- return true;- }- const parentFolder = folders.get(parentFolderId);- // Should be impossible because at least root folder is always found.- if (parentFolder === undefined) {- return false;- }-- return (- parentFolder.children.some(- (id) => folders.get(id)?.slug === slug && id !== folderId- ) === false- );-};--export const isPathAvailable = ({- pages,- path,- parentFolderId,- pageId,-}: {- pages: Pages;- path: Page["path"];- parentFolderId: Folder["id"];- // undefined page id means new page- pageId?: Page["id"];-}) => {- const map = new Map<Page["path"], Page>();- const allPages = getAllPages(pages);- for (const page of allPages) {- map.set(getPagePath(page.id, pages), page);- }- const folderPath = getPagePath(parentFolderId, pages);- // When slug is empty, folderPath is "/".- const pagePath = folderPath === "/" ? path : `${folderPath}${path}`;- const existingPage = map.get(pagePath);- // We found another page that has the same path and the current page.- if (pageId && existingPage?.id === pageId) {- return true;- }- return existingPage === undefined;-};--/**- * - Register a folder or a page inside children of a given parent folder.- * - Fallback to a root folder.- * - Cleanup any potential references in other folders.- */-export const registerFolderChildMutable = (- pages: Pick<Pages, "folders" | "rootFolderId">,- id: Page["id"] | Folder["id"],- // In case we couldn't find the current folder during update for any reason,- // we will always fall back to the root folder.- parentFolderId?: Folder["id"]-) => {- const { folders } = pages;- const parentFolder =- (parentFolderId === undefined ? undefined : folders.get(parentFolderId)) ??- folders.get(pages.rootFolderId);- cleanupChildRefsMutable(id, folders);- parentFolder?.children.push(id);-};--export const reparentPageOrFolderMutable = (- folders: Pages["folders"],- pageOrFolderId: string,- newFolderId: string,- newPosition: number-) => {- const childrenAndSelf = getAllChildrenAndSelf(- pageOrFolderId,- folders,- "folder"+ applyBuilderPatchPayloadMutable(+ data,+ createInstanceCleanupPayload({+ instanceIds: collectExclusiveInstanceIds(data.instances, [+ rootInstanceId,+ ]),+ props: data.props?.values() ?? [],+ dataSources: data.dataSources?.values() ?? [],+ styleSources: data.styleSources?.values() ?? [],+ styleSourceSelections: data.styleSourceSelections?.values() ?? [],+ styles: data.styles?.values() ?? [],+ }));- // make sure target folder is not self or descendants- if (childrenAndSelf.includes(newFolderId)) {- return;- }- const prevParent = findParentFolderByChildId(pageOrFolderId, folders);- const nextParent = folders.get(newFolderId);- if (prevParent === undefined || nextParent === undefined) {- return;- }- // if parent is the same, we need to adjust the position- // to account for the removal of the instance.- const prevPosition = prevParent.children.indexOf(pageOrFolderId);- if (prevPosition === -1) {- return;- }- if (prevParent.id === nextParent.id && prevPosition < newPosition) {- newPosition -= 1;- }- prevParent.children.splice(prevPosition, 1);- nextParent.children.splice(newPosition, 0, pageOrFolderId);-};--/**- * Get all child folder ids of the current folder including itself.- */-export const getAllChildrenAndSelf = (- id: Folder["id"] | Page["id"],- folders: Pages["folders"],- filter: "folder" | "page"-) => {- const child = folders.get(id);- const children: Array<Folder["id"]> = [];- const type = child === undefined ? "page" : "folder";-- if (type === filter) {- children.push(id);- }-- if (child) {- for (const childId of child.children) {- children.push(...getAllChildrenAndSelf(childId, folders, filter));- }- }- return children;};/**@@ -270,10 +94,7 @@ export const deletePageMutable = (pageId: Page["id"], data: WebstudioData) => {}const rootInstanceId = findPageByIdOrPath(pageId, data.pages)?.rootInstanceId;if (rootInstanceId !== undefined) {- deleteInstanceMutable(- data,- getInstancePath([rootInstanceId], data.instances)- );+ deleteRootInstanceMutable(data, rootInstanceId);}pages.pages.delete(pageId);cleanupChildRefsMutable(pageId, data.pages.folders);@@ -288,21 +109,7 @@ export const deleteFolderWithChildrenMutable = (pages: Pages) => {const { folders } = pages;- const folder = folders.get(folderId);- if (folder === undefined || folderId === pages.rootFolderId) {- return {- folderIds: [],- pageIds: [],- };- }- const folderIds = getAllChildrenAndSelf(folderId, folders, "folder");- const pageIds = getAllChildrenAndSelf(folderId, folders, "page");- if (pageIds.includes(pages.homePageId)) {- return {- folderIds: [],- pageIds: [],- };- }+ const { folderIds, pageIds } = getFolderDeletionTargets(folderId, pages);for (const folderId of folderIds) {cleanupChildRefsMutable(folderId, folders);folders.delete(folderId);@@ -344,12 +151,13 @@ export const $pageRootScope = computed();export const duplicatePage = (pageId: Page["id"]) => {+ const projectId = $project.get()?.id;const pages = $pages.get();const currentFolder =pages === undefined? undefined: findParentFolderByChildId(pageId, pages.folders);- if (currentFolder === undefined) {+ if (currentFolder === undefined || projectId === undefined) {return;}let newPageId: undefined | string;@@ -357,18 +165,20 @@ export const duplicatePage = (pageId: Page["id"]) => {newPageId = insertPageCopyMutable({source: { data, pageId },target: { data, folderId: currentFolder.id },+ projectId,});});return newPageId;};export const duplicateFolder = (folderId: Folder["id"]) => {+ const projectId = $project.get()?.id;const pages = $pages.get();const currentFolder =pages === undefined? undefined: findParentFolderByChildId(folderId, pages.folders);- if (currentFolder === undefined) {+ if (currentFolder === undefined || projectId === undefined) {return;}let newFolderId: undefined | string;@@ -378,6 +188,7 @@ export const duplicateFolder = (folderId: Folder["id"]) => {newFolderId = insertFolderCopyFromDataMutable({source: copyData,target: { data, parentFolderId: currentFolder.id },+ projectId,forceFolderCopySuffix: true,});}@@ -458,17 +269,15 @@ export const deleteTemplateMutable = (if (template === undefined) {return;}- deleteInstanceMutable(- data,- getInstancePath([template.rootInstanceId], data.instances)- );+ deleteRootInstanceMutable(data, template.rootInstanceId);data.pages.pageTemplates?.delete(templateId);};export const duplicateTemplate = (templateId: PageTemplate["id"]) => {+ const projectId = $project.get()?.id;const pages = $pages.get();const template = pages?.pageTemplates?.get(templateId);- if (template === undefined) {+ if (template === undefined || projectId === undefined) {return;}let newTemplateId: undefined | string;@@ -484,6 +293,7 @@ export const duplicateTemplate = (templateId: PageTemplate["id"]) => {bodyFragment: copyData.bodyFragment,},target: { data },+ projectId,});});return newTemplateId;@@ -500,6 +310,10 @@ export const instantiateTemplate = ({folderId: Folder["id"];contentMode?: boolean;}) => {+ const projectId = $project.get()?.id;+ if (projectId === undefined) {+ return;+ }let newPageId: undefined | string;updateWebstudioData((data) => {newPageId = insertPageFromTemplateMutable({@@ -507,6 +321,9 @@ export const instantiateTemplate = ({source: { data },target: { data, folderId },overrides,+ projectId,+ metas: $registeredComponentMetas.get(),+ contentModeCopyableProp: isFragmentContentModeCopyableProp,contentMode,});});diff --git a/apps/builder/app/builder/features/pages/pages.tsx b/apps/builder/app/builder/features/pages/pages.tsxindex 6b78586cd0..309999f2bf 100644--- a/apps/builder/app/builder/features/pages/pages.tsx+++ b/apps/builder/app/builder/features/pages/pages.tsx@@ -55,10 +55,12 @@ import {$templateIdToDelete,} from "~/shared/nano-states";import { $pages } from "~/shared/sync/data-stores";+import { getAllChildrenAndSelf } from "@webstudio-is/project-build/runtime/pages";import {- getAllChildrenAndSelf,reparentOrphansMutable,reparentPageOrFolderMutable,+} from "~/shared/page-utils/tree";+import {deletePageMutable,deleteFolderWithChildrenMutable,duplicateFolder,diff --git a/apps/builder/app/builder/features/settings-panel/controls/resource-control.tsx b/apps/builder/app/builder/features/settings-panel/controls/resource-control.tsxindex 7056c27dc1..84fcb3a4b7 100644--- a/apps/builder/app/builder/features/settings-panel/controls/resource-control.tsx+++ b/apps/builder/app/builder/features/settings-panel/controls/resource-control.tsx@@ -33,8 +33,12 @@ import {import { $variableValuesByInstanceSelector } from "~/shared/nano-states";import { $dataSources } from "~/shared/sync/data-stores";import { $props, $resources } from "~/shared/sync/data-stores";-import { computeExpression } from "~/shared/data-variables";-import { updateWebstudioData } from "~/shared/instance-utils/data";+import { computeExpression } from "@webstudio-is/project-build/runtime/data";+import {+ applyBuilderPatchPayloadMutable,+ updateWebstudioData,+} from "~/shared/instance-utils/data";+import { createPropUpsertPayload } from "@webstudio-is/project-build/runtime/props";import {$selectedInstance,$selectedInstanceKeyWithRoot,@@ -280,7 +284,13 @@ export const ResourceControl = ({type: "resource",value: newResource.id,};- data.props.set(newProp.id, newProp);+ applyBuilderPatchPayloadMutable(+ data,+ createPropUpsertPayload({+ props: data.props.values(),+ nextProps: [newProp],+ }).payload+ );data.resources.set(newResource.id, newResource);}});diff --git a/apps/builder/app/builder/features/settings-panel/controls/tag-control.tsx b/apps/builder/app/builder/features/settings-panel/controls/tag-control.tsxindex c3796dfe29..07afaf5edd 100644--- a/apps/builder/app/builder/features/settings-panel/controls/tag-control.tsx+++ b/apps/builder/app/builder/features/settings-panel/controls/tag-control.tsx@@ -5,7 +5,11 @@ import { Box, Combobox, Select, theme } from "@webstudio-is/design-system";import { elementsByTag } from "@webstudio-is/html-data";import { tags } from "@webstudio-is/sdk";import { $selectedInstance, $selectedInstancePath } from "~/shared/nano-states";-import { updateWebstudioData } from "~/shared/instance-utils/data";+import {+ applyBuilderPatchPayloadMutable,+ updateWebstudioData,+} from "~/shared/instance-utils/data";+import { createPropDeletePayload } from "@webstudio-is/project-build/runtime/props";import { isTreeSatisfyingContentModel } from "~/shared/content-model";import { $registeredComponentMetas } from "~/shared/nano-states";import { $instances } from "~/shared/sync/data-stores";@@ -59,7 +63,14 @@ export const TagControl = ({ meta, prop }: ControlProps<"tag">) => {updateWebstudioData((data) => {// clean legacy <Box tag> and <Text tag>if (prop) {- data.props.delete(prop.id);+ applyBuilderPatchPayloadMutable(+ data,+ createPropDeletePayload({+ deletions: [{ instanceId, name: prop.name }],+ instances: data.instances,+ props: data.props.values(),+ }).payload+ );}const instance = data.instances.get(instanceId);if (instance) {diff --git a/apps/builder/app/builder/features/settings-panel/controls/text-content.tsx b/apps/builder/app/builder/features/settings-panel/controls/text-content.tsxindex 0b41719636..be4b3f0f20 100644--- a/apps/builder/app/builder/features/settings-panel/controls/text-content.tsx+++ b/apps/builder/app/builder/features/settings-panel/controls/text-content.tsx@@ -19,7 +19,15 @@ import {validatePrimitiveValue,} from "~/builder/shared/binding-popover";import { useDraftValue } from "~/builder/shared/use-draft-value";-import { updateWebstudioData } from "~/shared/instance-utils/data";+import {+ applyBuilderPatchPayloadMutable,+ updateWebstudioData,+} from "~/shared/instance-utils/data";+import {+ createTextContentChild,+ createTextContentResetPayload,+ createTextContentUpdatePayload,+} from "@webstudio-is/project-build/runtime/instances";import { CodeEditor } from "~/shared/code-editor";import {type ControlProps,@@ -45,7 +53,14 @@ const updateChildren = (updateWebstudioData((data) => {const instance = data.instances.get(instanceId);if (instance) {- instance.children = [{ type, value }];+ applyBuilderPatchPayloadMutable(+ data,+ createTextContentUpdatePayload({+ instanceId,+ childIndex: 0,+ child: createTextContentChild({ type, value }),+ })+ );}});};@@ -110,7 +125,10 @@ export const TextContent = ({updateWebstudioData((data) => {const instance = data.instances.get(instanceId);if (instance) {- instance.children = [];+ applyBuilderPatchPayloadMutable(+ data,+ createTextContentResetPayload({ instanceId })+ );}});}}diff --git a/apps/builder/app/builder/features/settings-panel/property-label.tsx b/apps/builder/app/builder/features/settings-panel/property-label.tsxindex 80755b277d..abc028ac97 100644--- a/apps/builder/app/builder/features/settings-panel/property-label.tsx+++ b/apps/builder/app/builder/features/settings-panel/property-label.tsx@@ -15,12 +15,19 @@ import {import { AlertIcon } from "@webstudio-is/icons";import type { Prop } from "@webstudio-is/sdk";import { showAttribute } from "@webstudio-is/react-sdk";-import { updateWebstudioData } from "~/shared/instance-utils/data";+import {+ applyBuilderPatchPayloadMutable,+ updateWebstudioData,+} from "~/shared/instance-utils/data";import {$authPermit,$isContentMode,$selectedInstance,} from "~/shared/nano-states";+import {+ createPropDeletePayload,+ getPropIdsToDelete,+} from "@webstudio-is/project-build/runtime/props";import { $props } from "~/shared/sync/data-stores";import {$selectedInstanceInitialPropNames,@@ -65,52 +72,22 @@ const useProp = (name: string) => {return useStore(store);};-const getPropIdsToDelete = ({- instanceComponent,- instanceProps,- propName,-}: {- instanceComponent: string | undefined;- instanceProps: Map<Prop["name"], Prop>;- propName: Prop["name"];-}) => {- const propIds = new Set<Prop["id"]>();- const prop = instanceProps.get(propName);- if (prop) {- propIds.add(prop.id);- }- if (instanceComponent === "Image" && propName === "src") {- const widthProp = instanceProps.get("width");- if (widthProp) {- propIds.add(widthProp.id);- }- const heightProp = instanceProps.get("height");- if (heightProp) {- propIds.add(heightProp.id);- }- }- return propIds;-};-export const __testing__ = {getPropIdsToDelete,};const deleteProp = (name: string) => {const instance = $selectedInstance.get();- const instanceProps = $selectedInstanceProps.get();updateWebstudioData((data) => {- const prop = instanceProps.get(name);- for (const propId of getPropIdsToDelete({- instanceComponent: instance?.component,- instanceProps,- propName: name,- })) {- data.props.delete(propId);- }- if (prop?.type === "resource") {- data.resources.delete(prop.value);+ if (instance === undefined) {+ return;}+ const { payload } = createPropDeletePayload({+ deletions: [{ instanceId: instance.id, name }],+ instances: data.instances,+ props: data.props.values(),+ });+ applyBuilderPatchPayloadMutable(data, payload);});};diff --git a/apps/builder/app/builder/features/settings-panel/props-section/animation/set-css-property.ts b/apps/builder/app/builder/features/settings-panel/props-section/animation/set-css-property.tsindex a5906a1d90..d1876a0682 100644--- a/apps/builder/app/builder/features/settings-panel/props-section/animation/set-css-property.ts+++ b/apps/builder/app/builder/features/settings-panel/props-section/animation/set-css-property.ts@@ -1,17 +1,17 @@-import { nanoid } from "nanoid";import type { CssProperty, StyleValue } from "@webstudio-is/css-engine";import {- getStyleDeclKey,- type StyleDecl,type Breakpoints,type Instance,type Styles,type StyleSources,type StyleSourceSelections,} from "@webstudio-is/sdk";+import { nanoid } from "nanoid";-import { isBaseBreakpoint } from "~/shared/breakpoints-utils";+import { isBaseBreakpoint } from "@webstudio-is/project-build/runtime/breakpoints";import { camelCaseProperty } from "@webstudio-is/css-data";+import { createStyleDeclarationUpdatePayload } from "@webstudio-is/project-build/runtime/styles";+import { applyBuilderPatchPayloadMutable } from "~/shared/instance-utils/data";export const setListedCssProperty =(@@ -22,26 +22,6 @@ export const setListedCssProperty =styles: Styles) =>(instanceId: Instance["id"], property: CssProperty, value: StyleValue) => {- if (!styleSourceSelections.has(instanceId)) {- const styleSourceId = nanoid();- styleSources.set(styleSourceId, { type: "local", id: styleSourceId });-- styleSourceSelections.set(instanceId, {- instanceId,- values: [styleSourceId],- });- }-- const styleSourceSelection = styleSourceSelections.get(instanceId)!;-- const localStyleSorceId = styleSourceSelection.values.find(- (styleSourceId) => styleSources.get(styleSourceId)?.type === "local"- );-- if (localStyleSorceId === undefined) {- throw new Error("Local style source not found");- }-const baseBreakpoint = Array.from(breakpoints.values()).find(isBaseBreakpoint);@@ -50,12 +30,23 @@ export const setListedCssProperty =throw new Error("Base breakpoint not found");}- const styleDecl: StyleDecl = {- breakpointId: baseBreakpoint.id,- property: camelCaseProperty(property),- styleSourceId: localStyleSorceId,- value,- listed: true,- };- styles.set(getStyleDeclKey(styleDecl), styleDecl);+ applyBuilderPatchPayloadMutable(+ { styleSourceSelections, styleSources, styles },+ createStyleDeclarationUpdatePayload({+ updates: [+ {+ instanceId,+ breakpoint: baseBreakpoint.id,+ property: camelCaseProperty(property),+ value,+ listed: true,+ createLocalIfMissing: true,+ },+ ],+ styleSources,+ styleSourceSelections: styleSourceSelections.values(),+ styles: styles.values(),+ createId: nanoid,+ }).payload+ );};diff --git a/apps/builder/app/builder/features/settings-panel/props-section/props-section.tsx b/apps/builder/app/builder/features/settings-panel/props-section/props-section.tsxindex 6d771d4067..080e3d763c 100644--- a/apps/builder/app/builder/features/settings-panel/props-section/props-section.tsx+++ b/apps/builder/app/builder/features/settings-panel/props-section/props-section.tsx@@ -48,6 +48,8 @@ import {$selectedInstanceInitialPropNames,$selectedInstancePropsMetas,} from "../shared";+import { applyBuilderPatchPayloadMutable } from "~/shared/instance-utils/data";+import { createPropUpsertPayload } from "@webstudio-is/project-build/runtime/props";type Item = {name: string;@@ -404,18 +406,14 @@ export const PropsSectionContainer = ({props: propsByInstanceId.get(instance.id) ?? [],updateProp: (update) => {- const { propsByInstanceId } = $propsIndex.get();- const instanceProps = propsByInstanceId.get(instance.id) ?? [];- // Fixing a bug that caused some props to be duplicated on unmount by removing duplicates.- // see for details https://github.com/webstudio-is/webstudio/pull/2170- const duplicateProps = instanceProps- .filter((prop) => prop.id !== update.id)- .filter((prop) => prop.name === update.name);serverSyncStore.createTransaction([$props], (props) => {- for (const prop of duplicateProps) {- props.delete(prop.id);- }- props.set(update.id, update);+ applyBuilderPatchPayloadMutable(+ { props },+ createPropUpsertPayload({+ props: props.values(),+ nextProps: [update],+ }).payload+ );});},});diff --git a/apps/builder/app/builder/features/settings-panel/props-section/use-props-logic.ts b/apps/builder/app/builder/features/settings-panel/props-section/use-props-logic.tsindex 9f3327e64c..3eaa1f8e1c 100644--- a/apps/builder/app/builder/features/settings-panel/props-section/use-props-logic.ts+++ b/apps/builder/app/builder/features/settings-panel/props-section/use-props-logic.ts@@ -28,6 +28,7 @@ import {showAttributeMeta,type PropValue,} from "../shared";+import { createPropValue } from "@webstudio-is/project-build/runtime/props";type PropOrName = { prop?: Prop; propName: string };@@ -424,9 +425,13 @@ export const usePropsLogic = ({const handleChange = ({ prop, propName }: PropOrName, value: PropValue) => {updateProp(- prop === undefined- ? { id: nanoid(), instanceId: instance.id, name: propName, ...value }- : { ...prop, ...value }+ createPropValue({+ id: prop?.id ?? nanoid(),+ instanceId: instance.id,+ name: propName,+ required: prop?.required,+ ...value,+ }));};@@ -434,9 +439,13 @@ export const usePropsLogic = ({const prop = props.find((prop) => prop.name === propName);updateProp(- prop === undefined- ? { id: nanoid(), instanceId: instance.id, name: propName, ...value }- : { ...prop, ...value }+ createPropValue({+ id: prop?.id ?? nanoid(),+ instanceId: instance.id,+ name: propName,+ required: prop?.required,+ ...value,+ }));};diff --git a/apps/builder/app/builder/features/settings-panel/resource-panel.tsx b/apps/builder/app/builder/features/settings-panel/resource-panel.tsxindex c7c64b570a..a328bf148b 100644--- a/apps/builder/app/builder/features/settings-panel/resource-panel.tsx+++ b/apps/builder/app/builder/features/settings-panel/resource-panel.tsx@@ -14,7 +14,6 @@ import { useStore } from "@nanostores/react";import {type DataSources,type Resource,- resource,type DataSource,type Page,type PageTemplate,@@ -71,7 +70,10 @@ import {type InstancePath,} from "~/shared/nano-states";import { updateWebstudioData } from "~/shared/instance-utils/data";-import { rebindTreeVariablesMutable } from "~/shared/data-variables";+import {+ createResourceValue,+ upsertResourceMutable,+} from "@webstudio-is/project-build/runtime/data";import { parseCurl, type CurlRequest } from "./curl";export const parseResource = ({@@ -89,7 +91,7 @@ export const parseResource = ({const searchParamValues = formData.getAll("search-param-value") as string[];const headerNames = formData.getAll("header-name") as string[];const headerValues = formData.getAll("header-value") as string[];- return resource.parse({+ return createResourceValue({id,control,name: name ?? formData.get("name"),@@ -101,7 +103,6 @@ export const parseResource = ({headers: headerNames.map((name, index) => ({ name, value: headerValues[index] })).filter((item) => item.name.trim()),- // use undefined instead of empty stringbody: formData.get("body") || undefined,});};@@ -878,11 +879,12 @@ export const ResourceForm = forwardRef<resourceId: newResource.id,};updateWebstudioData((data) => {- data.dataSources.set(newVariable.id, newVariable);- data.resources.set(newResource.id, newResource);- rebindTreeVariablesMutable({- startingInstanceId: scopeInstanceId,- ...data,+ upsertResourceMutable({+ data,+ resource: newResource,+ dataSourceId: newVariable.id,+ scopeInstanceId,+ dataSourceName: newVariable.name,});});},@@ -1037,11 +1039,12 @@ export const SystemResourceForm = forwardRef<resourceId: newResource.id,};updateWebstudioData((data) => {- data.dataSources.set(newVariable.id, newVariable);- data.resources.set(newResource.id, newResource);- rebindTreeVariablesMutable({- startingInstanceId: scopeInstanceId,- ...data,+ upsertResourceMutable({+ data,+ resource: newResource,+ dataSourceId: newVariable.id,+ scopeInstanceId,+ dataSourceName: newVariable.name,});});},@@ -1145,11 +1148,12 @@ export const GraphqlResourceForm = forwardRef<resourceId: newResource.id,};updateWebstudioData((data) => {- data.dataSources.set(newVariable.id, newVariable);- data.resources.set(newResource.id, newResource);- rebindTreeVariablesMutable({- startingInstanceId: scopeInstanceId,- ...data,+ upsertResourceMutable({+ data,+ resource: newResource,+ dataSourceId: newVariable.id,+ scopeInstanceId,+ dataSourceName: newVariable.name,});});},diff --git a/apps/builder/app/builder/features/settings-panel/variable-popover.tsx b/apps/builder/app/builder/features/settings-panel/variable-popover.tsxindex b424499a5e..498d2481c3 100644--- a/apps/builder/app/builder/features/settings-panel/variable-popover.tsx+++ b/apps/builder/app/builder/features/settings-panel/variable-popover.tsx@@ -45,10 +45,10 @@ import {import {type DataSource,transpileExpression,- lintExpression,SYSTEM_VARIABLE_ID,resourceRequest,} from "@webstudio-is/sdk";+import { hasExpressionDiagnostics } from "~/shared/expression-validation";import {ExpressionEditor,formatValue,@@ -74,7 +74,7 @@ import { updateWebstudioData } from "~/shared/instance-utils/data";import {findUnsetVariableNames,rebindTreeVariablesMutable,-} from "~/shared/data-variables";+} from "@webstudio-is/project-build/runtime/data";import { validateDataVariableName } from "~/builder/shared/data-variable-utils";import {GraphqlResourceForm,@@ -495,9 +495,8 @@ const BooleanForm = forwardRef<BooleanForm.displayName = "BooleanForm";const validateJsonValue = (expression: string) => {- const diagnostics = lintExpression({ expression });// prevent saving with any message including unset variable- return diagnostics.length > 0 ? "error" : "";+ return hasExpressionDiagnostics({ expression }) ? "error" : "";};const parseJsonValue = (expression: string) => {diff --git a/apps/builder/app/builder/features/settings-panel/variables-section.tsx b/apps/builder/app/builder/features/settings-panel/variables-section.tsxindex b66316f173..030551ee4e 100644--- a/apps/builder/app/builder/features/settings-panel/variables-section.tsx+++ b/apps/builder/app/builder/features/settings-panel/variables-section.tsx@@ -46,7 +46,7 @@ import {deleteVariableMutable,findAvailableVariables,findUsedVariables,-} from "~/shared/data-variables";+} from "@webstudio-is/project-build/runtime/data";import { DeleteDataVariableDialog } from "~/builder/shared/data-variable-utils";/**diff --git a/apps/builder/app/builder/features/style-panel/sections/layout/shared/grid-areas.utils.test.ts b/apps/builder/app/builder/features/style-panel/sections/layout/shared/grid-areas.utils.test.tsdeleted file mode 100644index 89c806f33e..0000000000--- a/apps/builder/app/builder/features/style-panel/sections/layout/shared/grid-areas.utils.test.ts+++ /dev/null@@ -1,641 +0,0 @@-import { describe, test, expect } from "vitest";-import {- parseGridAreas,- getGridDimensions,- __testing__,- type AreaInfo,-} from "./grid-areas";--const {- generateGridTemplate,- checkOverlap,- generateUniqueAreaName,- findNonOverlappingPosition,- isAreaWithinBounds,- filterAreasWithinBounds,-} = __testing__;--describe("parseGridAreas", () => {- test("parses empty or none value", () => {- expect(parseGridAreas("")).toEqual([]);- expect(parseGridAreas("none")).toEqual([]);- });-- test("parses single area", () => {- const result = parseGridAreas('"header"');- expect(result).toEqual([- {- name: "header",- columnStart: 1,- columnEnd: 2,- rowStart: 1,- rowEnd: 2,- },- ]);- });-- test("parses area spanning multiple columns", () => {- const result = parseGridAreas('"header header header"');- expect(result).toEqual([- {- name: "header",- columnStart: 1,- columnEnd: 4,- rowStart: 1,- rowEnd: 2,- },- ]);- });-- test("parses multiple areas in one row", () => {- const result = parseGridAreas('"sidebar main"');- expect(result).toHaveLength(2);- expect(result).toContainEqual({- name: "sidebar",- columnStart: 1,- columnEnd: 2,- rowStart: 1,- rowEnd: 2,- });- expect(result).toContainEqual({- name: "main",- columnStart: 2,- columnEnd: 3,- rowStart: 1,- rowEnd: 2,- });- });-- test("parses area spanning multiple rows", () => {- const result = parseGridAreas('"sidebar main" "sidebar footer"');- expect(result).toHaveLength(3);- expect(result).toContainEqual({- name: "sidebar",- columnStart: 1,- columnEnd: 2,- rowStart: 1,- rowEnd: 3,- });- });-- test("parses complex layout with multiple rows and columns", () => {- const result = parseGridAreas(- '"header header" "sidebar main" "footer footer"'- );- expect(result).toHaveLength(4);- expect(result).toContainEqual({- name: "header",- columnStart: 1,- columnEnd: 3,- rowStart: 1,- rowEnd: 2,- });- expect(result).toContainEqual({- name: "sidebar",- columnStart: 1,- columnEnd: 2,- rowStart: 2,- rowEnd: 3,- });- expect(result).toContainEqual({- name: "main",- columnStart: 2,- columnEnd: 3,- rowStart: 2,- rowEnd: 3,- });- expect(result).toContainEqual({- name: "footer",- columnStart: 1,- columnEnd: 3,- rowStart: 3,- rowEnd: 4,- });- });-- test("ignores dots (empty cells)", () => {- const result = parseGridAreas('"header ." ". main"');- expect(result).toHaveLength(2);- expect(result).toContainEqual({- name: "header",- columnStart: 1,- columnEnd: 2,- rowStart: 1,- rowEnd: 2,- });- expect(result).toContainEqual({- name: "main",- columnStart: 2,- columnEnd: 3,- rowStart: 2,- rowEnd: 3,- });- });-});--describe("generateGridTemplate", () => {- test("generates template for single area", () => {- const areas: AreaInfo[] = [- { name: "header", columnStart: 1, columnEnd: 2, rowStart: 1, rowEnd: 2 },- ];- expect(generateGridTemplate(areas, 2, 2)).toBe('"header ." ". ."');- });-- test("generates template for area spanning columns", () => {- const areas: AreaInfo[] = [- { name: "header", columnStart: 1, columnEnd: 3, rowStart: 1, rowEnd: 2 },- ];- expect(generateGridTemplate(areas, 2, 2)).toBe('"header header" ". ."');- });-- test("generates template for complex layout", () => {- const areas: AreaInfo[] = [- { name: "header", columnStart: 1, columnEnd: 3, rowStart: 1, rowEnd: 2 },- { name: "sidebar", columnStart: 1, columnEnd: 2, rowStart: 2, rowEnd: 3 },- { name: "main", columnStart: 2, columnEnd: 3, rowStart: 2, rowEnd: 3 },- ];- expect(generateGridTemplate(areas, 2, 2)).toBe(- '"header header" "sidebar main"'- );- });-- test("fills empty cells with dots", () => {- const areas: AreaInfo[] = [- { name: "header", columnStart: 1, columnEnd: 2, rowStart: 1, rowEnd: 2 },- { name: "footer", columnStart: 2, columnEnd: 3, rowStart: 2, rowEnd: 3 },- ];- expect(generateGridTemplate(areas, 2, 2)).toBe('"header ." ". footer"');- });-- test("handles area out of bounds gracefully", () => {- const areas: AreaInfo[] = [- {- name: "header",- columnStart: 1,- columnEnd: 10,- rowStart: 1,- rowEnd: 10,- },- ];- // Should only fill within the grid bounds- expect(generateGridTemplate(areas, 2, 2)).toBe(- '"header header" "header header"'- );- });-});--describe("getGridDimensions", () => {- test("parses column and row counts", () => {- expect(getGridDimensions("1fr 2fr", "100px 200px")).toEqual({- columns: 2,- rows: 2,- });- });-- test("handles complex track definitions", () => {- expect(- getGridDimensions("repeat(3, 1fr)", "minmax(100px, 1fr) auto 200px")- ).toEqual({- columns: 3, // repeat(3, 1fr) expands to 3 tracks- rows: 3, // minmax(100px, 1fr), auto, 200px = 3 tracks- });- });-- test("defaults to 2 when none", () => {- expect(getGridDimensions("none", "none")).toEqual({- columns: 2,- rows: 2,- });- });-- test("defaults to 2 when empty", () => {- expect(getGridDimensions("", "")).toEqual({- columns: 2,- rows: 2,- });- });-});--describe("checkOverlap", () => {- test("detects overlapping areas", () => {- const area1: AreaInfo = {- name: "a",- columnStart: 1,- columnEnd: 3,- rowStart: 1,- rowEnd: 3,- };- const area2: AreaInfo = {- name: "b",- columnStart: 2,- columnEnd: 4,- rowStart: 2,- rowEnd: 4,- };- expect(checkOverlap(area1, area2)).toBe(true);- });-- test("detects non-overlapping areas horizontally", () => {- const area1: AreaInfo = {- name: "a",- columnStart: 1,- columnEnd: 2,- rowStart: 1,- rowEnd: 2,- };- const area2: AreaInfo = {- name: "b",- columnStart: 2,- columnEnd: 3,- rowStart: 1,- rowEnd: 2,- };- expect(checkOverlap(area1, area2)).toBe(false);- });-- test("detects non-overlapping areas vertically", () => {- const area1: AreaInfo = {- name: "a",- columnStart: 1,- columnEnd: 2,- rowStart: 1,- rowEnd: 2,- };- const area2: AreaInfo = {- name: "b",- columnStart: 1,- columnEnd: 2,- rowStart: 2,- rowEnd: 3,- };- expect(checkOverlap(area1, area2)).toBe(false);- });-- test("detects complete containment as overlap", () => {- const area1: AreaInfo = {- name: "a",- columnStart: 1,- columnEnd: 5,- rowStart: 1,- rowEnd: 5,- };- const area2: AreaInfo = {- name: "b",- columnStart: 2,- columnEnd: 4,- rowStart: 2,- rowEnd: 4,- };- expect(checkOverlap(area1, area2)).toBe(true);- });-- test("detects edge adjacency as non-overlapping", () => {- const area1: AreaInfo = {- name: "a",- columnStart: 1,- columnEnd: 2,- rowStart: 1,- rowEnd: 2,- };- const area2: AreaInfo = {- name: "b",- columnStart: 2,- columnEnd: 3,- rowStart: 2,- rowEnd: 3,- };- expect(checkOverlap(area1, area2)).toBe(false);- });-});--describe("generateUniqueAreaName", () => {- test("returns 'Area' when no existing names", () => {- expect(generateUniqueAreaName([])).toBe("Area");- });-- test("returns 'Area' when it doesn't exist", () => {- expect(generateUniqueAreaName(["Header", "Footer"])).toBe("Area");- });-- test("returns 'Area-1' when 'Area' exists", () => {- expect(generateUniqueAreaName(["Area"])).toBe("Area-1");- });-- test("returns next available number", () => {- expect(generateUniqueAreaName(["Area", "Area-1", "Area-2"])).toBe("Area-3");- });-- test("handles gaps in numbering", () => {- expect(generateUniqueAreaName(["Area", "Area-2", "Area-5"])).toBe("Area-1");- });-});--describe("findNonOverlappingPosition", () => {- test("finds first cell when grid is empty", () => {- const result = findNonOverlappingPosition([], 2, 2);- expect(result.needsNewRow).toBe(false);- expect(result.area).toMatchObject({- name: "Area",- columnStart: 1,- columnEnd: 2,- rowStart: 1,- rowEnd: 2,- });- });-- test("finds next available cell", () => {- const existingAreas: AreaInfo[] = [- { name: "Area", columnStart: 1, columnEnd: 2, rowStart: 1, rowEnd: 2 },- ];- const result = findNonOverlappingPosition(existingAreas, 2, 2);- expect(result.needsNewRow).toBe(false);- expect(result.area).toMatchObject({- columnStart: 2,- columnEnd: 3,- rowStart: 1,- rowEnd: 2,- });- });-- test("generates unique name for new area", () => {- const existingAreas: AreaInfo[] = [- { name: "Area", columnStart: 1, columnEnd: 2, rowStart: 1, rowEnd: 2 },- ];- const result = findNonOverlappingPosition(existingAreas, 2, 2);- expect(result.area.name).toBe("Area-1");- });-- test("adds new row when grid is full", () => {- const existingAreas: AreaInfo[] = [- { name: "Area", columnStart: 1, columnEnd: 2, rowStart: 1, rowEnd: 2 },- { name: "Area-1", columnStart: 2, columnEnd: 3, rowStart: 1, rowEnd: 2 },- { name: "Area-2", columnStart: 1, columnEnd: 2, rowStart: 2, rowEnd: 3 },- { name: "Area-3", columnStart: 2, columnEnd: 3, rowStart: 2, rowEnd: 3 },- ];- const result = findNonOverlappingPosition(existingAreas, 2, 2);- expect(result.needsNewRow).toBe(true);- expect(result.area).toMatchObject({- columnStart: 1,- columnEnd: 3,- rowStart: 3,- rowEnd: 4,- });- });-- test("finds cell when area spans multiple cells", () => {- const existingAreas: AreaInfo[] = [- { name: "header", columnStart: 1, columnEnd: 3, rowStart: 1, rowEnd: 2 },- ];- const result = findNonOverlappingPosition(existingAreas, 2, 2);- expect(result.needsNewRow).toBe(false);- expect(result.area).toMatchObject({- columnStart: 1,- columnEnd: 2,- rowStart: 2,- rowEnd: 3,- });- });-});--describe("isAreaWithinBounds", () => {- test("validates area within bounds", () => {- const area: AreaInfo = {- name: "test",- columnStart: 1,- columnEnd: 2,- rowStart: 1,- rowEnd: 2,- };- expect(isAreaWithinBounds(area, 2, 2)).toBe(true);- });-- test("rejects area with invalid column start", () => {- const area: AreaInfo = {- name: "test",- columnStart: 0,- columnEnd: 2,- rowStart: 1,- rowEnd: 2,- };- expect(isAreaWithinBounds(area, 2, 2)).toBe(false);- });-- test("rejects area with column start >= column end", () => {- const area: AreaInfo = {- name: "test",- columnStart: 2,- columnEnd: 2,- rowStart: 1,- rowEnd: 2,- };- expect(isAreaWithinBounds(area, 2, 2)).toBe(false);- });-- test("rejects area with column end beyond grid", () => {- const area: AreaInfo = {- name: "test",- columnStart: 1,- columnEnd: 4,- rowStart: 1,- rowEnd: 2,- };- expect(isAreaWithinBounds(area, 2, 2)).toBe(false);- });-- test("rejects area with invalid row start", () => {- const area: AreaInfo = {- name: "test",- columnStart: 1,- columnEnd: 2,- rowStart: 0,- rowEnd: 2,- };- expect(isAreaWithinBounds(area, 2, 2)).toBe(false);- });-- test("rejects area with row start >= row end", () => {- const area: AreaInfo = {- name: "test",- columnStart: 1,- columnEnd: 2,- rowStart: 2,- rowEnd: 2,- };- expect(isAreaWithinBounds(area, 2, 2)).toBe(false);- });-- test("rejects area with row end beyond grid", () => {- const area: AreaInfo = {- name: "test",- columnStart: 1,- columnEnd: 2,- rowStart: 1,- rowEnd: 4,- };- expect(isAreaWithinBounds(area, 2, 2)).toBe(false);- });-- test("allows area at grid boundary", () => {- const area: AreaInfo = {- name: "test",- columnStart: 2,- columnEnd: 3,- rowStart: 2,- rowEnd: 3,- };- expect(isAreaWithinBounds(area, 2, 2)).toBe(true);- });-});--describe("filterAreasWithinBounds", () => {- test("returns all areas when all are valid", () => {- const areas: AreaInfo[] = [- {- name: "area1",- columnStart: 1,- columnEnd: 2,- rowStart: 1,- rowEnd: 2,- },- {- name: "area2",- columnStart: 2,- columnEnd: 3,- rowStart: 1,- rowEnd: 2,- },- ];- const result = filterAreasWithinBounds(areas, 3, 2);- expect(result).toEqual(areas);- expect(result).toHaveLength(2);- });-- test("filters out single area that exceeds column bounds", () => {- const areas: AreaInfo[] = [- {- name: "valid",- columnStart: 1,- columnEnd: 2,- rowStart: 1,- rowEnd: 2,- },- {- name: "invalid",- columnStart: 1,- columnEnd: 4,- rowStart: 1,- rowEnd: 2,- },- ];- const result = filterAreasWithinBounds(areas, 2, 2);- expect(result).toHaveLength(1);- expect(result[0].name).toBe("valid");- });-- test("filters out single area that exceeds row bounds", () => {- const areas: AreaInfo[] = [- {- name: "valid",- columnStart: 1,- columnEnd: 2,- rowStart: 1,- rowEnd: 2,- },- {- name: "invalid",- columnStart: 1,- columnEnd: 2,- rowStart: 1,- rowEnd: 4,- },- ];- const result = filterAreasWithinBounds(areas, 2, 2);- expect(result).toHaveLength(1);- expect(result[0].name).toBe("valid");- });-- test("filters out multiple invalid areas", () => {- const areas: AreaInfo[] = [- {- name: "valid",- columnStart: 1,- columnEnd: 2,- rowStart: 1,- rowEnd: 2,- },- {- name: "invalid1",- columnStart: 1,- columnEnd: 5,- rowStart: 1,- rowEnd: 2,- },- {- name: "invalid2",- columnStart: 1,- columnEnd: 2,- rowStart: 1,- rowEnd: 5,- },- ];- const result = filterAreasWithinBounds(areas, 2, 2);- expect(result).toHaveLength(1);- expect(result[0].name).toBe("valid");- });-- test("returns empty array when all areas are invalid", () => {- const areas: AreaInfo[] = [- {- name: "invalid1",- columnStart: 1,- columnEnd: 5,- rowStart: 1,- rowEnd: 2,- },- {- name: "invalid2",- columnStart: 1,- columnEnd: 2,- rowStart: 1,- rowEnd: 5,- },- ];- const result = filterAreasWithinBounds(areas, 2, 2);- expect(result).toEqual([]);- });-- test("returns empty array for empty input", () => {- const result = filterAreasWithinBounds([], 3, 3);- expect(result).toEqual([]);- });-- test("preserves order of valid areas", () => {- const areas: AreaInfo[] = [- {- name: "first",- columnStart: 1,- columnEnd: 2,- rowStart: 1,- rowEnd: 2,- },- {- name: "invalid",- columnStart: 1,- columnEnd: 5,- rowStart: 1,- rowEnd: 2,- },- {- name: "second",- columnStart: 2,- columnEnd: 3,- rowStart: 1,- rowEnd: 2,- },- ];- const result = filterAreasWithinBounds(areas, 3, 2);- expect(result).toHaveLength(2);- expect(result[0].name).toBe("first");- expect(result[1].name).toBe("second");- });-});diff --git a/apps/builder/app/builder/features/style-panel/sections/layout/shared/grid-generator.tsx b/apps/builder/app/builder/features/style-panel/sections/layout/shared/grid-generator.tsxindex 54942e36cf..57750d93ad 100644--- a/apps/builder/app/builder/features/style-panel/sections/layout/shared/grid-generator.tsx+++ b/apps/builder/app/builder/features/style-panel/sections/layout/shared/grid-generator.tsx@@ -14,7 +14,7 @@ import {Separator,} from "@webstudio-is/design-system";import { toValue } from "@webstudio-is/css-engine";-import { getStyleDeclKey, type StyleDecl } from "@webstudio-is/sdk";+import { createSelectedStyleDeclarationUpdatePayload } from "@webstudio-is/project-build/runtime/styles";import {parseGridTemplateTrackList,parseGridAreas,@@ -30,7 +30,10 @@ import { $gridCellData } from "~/shared/nano-states";import { $selectedInstanceSelector } from "~/shared/nano-states";import { $breakpoints } from "~/shared/sync/data-stores";import { $instances } from "~/shared/sync/data-stores";-import { updateWebstudioData } from "~/shared/instance-utils/data";+import {+ applyBuilderPatchPayloadMutable,+ updateWebstudioData,+} from "~/shared/instance-utils/data";import { DEFAULT_GRID_TRACK_COUNT } from "./constants";/**@@ -326,28 +329,36 @@ const applyFillGridItems = (component: "Box",children: [],});- data.styleSources.set(styleSourceId, {+ const styleSource = {type: "local",id: styleSourceId,- });- data.styleSourceSelections.set(instanceId, {- instanceId,- values: [styleSourceId],- });- const displayStyleDecl: StyleDecl = {- breakpointId,- styleSourceId,- property: "display",- value: { type: "keyword", value: "flex" },- };- data.styles.set(getStyleDeclKey(displayStyleDecl), displayStyleDecl);- const directionStyleDecl: StyleDecl = {- breakpointId,- styleSourceId,- property: "flexDirection",- value: { type: "keyword", value: "column" },- };- data.styles.set(getStyleDeclKey(directionStyleDecl), directionStyleDecl);+ } as const;+ applyBuilderPatchPayloadMutable(+ data,+ createSelectedStyleDeclarationUpdatePayload({+ updates: [+ {+ instanceId,+ styleSource,+ styleSourceId,+ breakpoint: breakpointId,+ property: "display",+ value: { type: "keyword", value: "flex" },+ },+ {+ instanceId,+ styleSource,+ styleSourceId,+ breakpoint: breakpointId,+ property: "flexDirection",+ value: { type: "keyword", value: "column" },+ },+ ],+ styleSources: data.styleSources,+ styleSourceSelections: data.styleSourceSelections.values(),+ styles: data.styles.values(),+ }).payload+ );parentInstance.children.push({ type: "id", value: instanceId });}};diff --git a/apps/builder/app/builder/features/style-panel/shared/use-style-data.ts b/apps/builder/app/builder/features/style-panel/shared/use-style-data.tsindex c79f4eb058..0c899111f5 100644--- a/apps/builder/app/builder/features/style-panel/shared/use-style-data.ts+++ b/apps/builder/app/builder/features/style-panel/shared/use-style-data.ts@@ -1,4 +1,3 @@-import { getStyleDeclKey, type StyleDecl } from "@webstudio-is/sdk";import type { CssProperty, StyleValue } from "@webstudio-is/css-engine";import { camelCaseProperty } from "@webstudio-is/css-data";import {@@ -14,7 +13,12 @@ import {import { serverSyncStore } from "~/shared/sync/sync-stores";import { $ephemeralStyles } from "~/canvas/stores";import { $selectedInstance } from "~/shared/nano-states";-import { isStyleSourceLocked } from "~/shared/style-source-utils";+import {+ createSelectedStyleDeclarationDeletePayload,+ createSelectedStyleDeclarationUpdatePayload,+ isStyleSourceLocked,+} from "@webstudio-is/project-build/runtime/styles";+import { applyBuilderPatchPayloadMutable } from "~/shared/instance-utils/data";type StyleUpdate =| {@@ -101,41 +105,45 @@ const publishUpdates = ((styleSourceSelections, styleSources, styles) => {const instanceId = selectedInstance.id;const breakpointId = selectedBreakpoint.id;- // set only selected style source and update selection with it- // generated local style source will not be written if not selected- styleSources.set(selectedStyleSource.id, selectedStyleSource);- const selectionValues =- styleSourceSelections.get(instanceId)?.values ?? [];- if (- selectionValues.includes(styleSourceSelector.styleSourceId) === false- ) {- styleSourceSelections.set(instanceId, {- instanceId,- values: [...selectionValues, styleSourceSelector.styleSourceId],- });- }-for (const update of updates) {if (update.operation === "set") {- const styleDecl: StyleDecl = {- breakpointId,- styleSourceId: styleSourceSelector.styleSourceId,- state: styleSourceSelector.state,- property: camelCaseProperty(update.property),- value: update.value,- listed: options.listed,- };- styles.set(getStyleDeclKey(styleDecl), styleDecl);+ applyBuilderPatchPayloadMutable(+ { styleSourceSelections, styleSources, styles },+ createSelectedStyleDeclarationUpdatePayload({+ updates: [+ {+ instanceId,+ styleSource: selectedStyleSource,+ styleSourceId: styleSourceSelector.styleSourceId,+ breakpoint: breakpointId,+ state: styleSourceSelector.state,+ property: camelCaseProperty(update.property),+ value: update.value,+ listed: options.listed,+ },+ ],+ styleSources,+ styleSourceSelections: styleSourceSelections.values(),+ styles: styles.values(),+ }).payload+ );}if (update.operation === "delete") {- const styleDeclKey = getStyleDeclKey({- breakpointId,- styleSourceId: styleSourceSelector.styleSourceId,- state: styleSourceSelector.state,- property: camelCaseProperty(update.property),- });- styles.delete(styleDeclKey);+ applyBuilderPatchPayloadMutable(+ { styles },+ createSelectedStyleDeclarationDeletePayload({+ deletions: [+ {+ styleSourceId: styleSourceSelector.styleSourceId,+ breakpoint: breakpointId,+ state: styleSourceSelector.state,+ property: camelCaseProperty(update.property),+ },+ ],+ styles: styles.values(),+ }).payload+ );}}}diff --git a/apps/builder/app/builder/features/style-panel/style-panel.tsx b/apps/builder/app/builder/features/style-panel/style-panel.tsxindex ceda8ddd2a..033d60902b 100644--- a/apps/builder/app/builder/features/style-panel/style-panel.tsx+++ b/apps/builder/app/builder/features/style-panel/style-panel.tsx@@ -27,7 +27,7 @@ import {$selectedInstanceRenderState,$selectedStyleSource,} from "~/shared/nano-states";-import { isStyleSourceLocked } from "~/shared/style-source-utils";+import { isStyleSourceLocked } from "@webstudio-is/project-build/runtime/styles";import { ReadonlyProvider } from "./shared/readonly";import { $selectedInstance } from "~/shared/nano-states";import { CollapsibleProvider } from "~/builder/shared/collapsible-section";diff --git a/apps/builder/app/builder/features/style-panel/style-source-section.tsx b/apps/builder/app/builder/features/style-panel/style-source-section.tsxindex 7b72b41946..af02c16e55 100644--- a/apps/builder/app/builder/features/style-panel/style-source-section.tsx+++ b/apps/builder/app/builder/features/style-panel/style-source-section.tsx@@ -5,21 +5,26 @@ import { computed } from "nanostores";import { pseudoClassesByTag } from "@webstudio-is/html-data";import { isPseudoElement } from "@webstudio-is/css-data";import {- type Instance,type StyleSource,type StyleSourceToken,- type StyleSourceSelections,type StyleDecl,- type StyleSources,getStyleDeclKey,} from "@webstudio-is/sdk";+import { cloneStyles } from "@webstudio-is/project-build/runtime/style-utils";+import { createTokenStyleSource } from "@webstudio-is/project-build/runtime/styles";+import { type RenameStyleSourceError } from "@webstudio-is/project-build/runtime/styles";import { type ItemSource, StyleSourceInput } from "./style-source";-import { type RenameStyleSourceError } from "~/shared/style-source-utils";+import {+ addStyleSourceToInstanceMutable,+ getOrCreateStyleSourceSelectionMutable,+ removeStyleSourceFromInstanceMutable,+} from "@webstudio-is/project-build/runtime/styles";import {renameStyleSource,deleteStyleSource,DeleteStyleSourceDialog,setStyleSourceLocked,+ deselectMatchingStyleSource,} from "~/builder/shared/style-source-actions";import {$registeredComponentMetas,@@ -34,8 +39,6 @@ import {$styleSources,$styles,} from "~/shared/sync/data-stores";-import { removeByMutable } from "~/shared/array-utils";-import { cloneStyles } from "~/shared/instance-utils/tree";import { serverSyncStore } from "~/shared/sync/sync-stores";import { subscribe } from "~/shared/pubsub";import { $selectedInstance } from "~/shared/nano-states";@@ -62,79 +65,25 @@ const selectStyleSource = ($selectedStyleState.set(state);};-const deselectMatchingStyleSource = (styleSourceId: StyleSource["id"]) => {- const instanceId = $selectedInstance.get()?.id;- if (instanceId === undefined) {- return;- }- const selectedStyleSources = new Map($selectedStyleSources.get());- if (selectedStyleSources.get(instanceId) === styleSourceId) {- selectedStyleSources.delete(instanceId);- $selectedStyleSources.set(selectedStyleSources);- $selectedStyleState.set(undefined);- }-};--const getOrCreateStyleSourceSelectionMutable = (- styleSourceSelections: StyleSourceSelections,- selectedInstanceId: Instance["id"]-) => {- let styleSourceSelection = styleSourceSelections.get(selectedInstanceId);- if (styleSourceSelection === undefined) {- styleSourceSelection = {- instanceId: selectedInstanceId,- values: [],- };- styleSourceSelections.set(selectedInstanceId, styleSourceSelection);- }- return styleSourceSelection;-};--const addStyleSourceToInstanceMutable = (- styleSourceSelections: StyleSourceSelections,- styleSources: StyleSources,- instanceId: Instance["id"],- newStyleSourceId: StyleSource["id"]-) => {- const styleSourceSelection = getOrCreateStyleSourceSelectionMutable(- styleSourceSelections,- instanceId- );- if (styleSourceSelection.values.includes(newStyleSourceId) === false) {- const lastStyleSourceId = styleSourceSelection.values.at(-1);- const lastStyleSource =- lastStyleSourceId === undefined- ? undefined- : styleSources.get(lastStyleSourceId);- // when local style source exists insert before it- if (lastStyleSource?.type === "local") {- styleSourceSelection.values.splice(-1, 0, newStyleSourceId);- } else {- styleSourceSelection.values.push(newStyleSourceId);- }- }-};-const createStyleSource = (id: StyleSource["id"], name: string) => {const instanceId = $selectedInstance.get()?.id;if (instanceId === undefined) {return;}- const newStyleSource: StyleSource = {- type: "token",+ const newStyleSource = createTokenStyleSource({id,name,- };+ });serverSyncStore.createTransaction([$styleSources, $styleSourceSelections],(styleSources, styleSourceSelections) => {styleSources.set(newStyleSource.id, newStyleSource);- addStyleSourceToInstanceMutable(+ addStyleSourceToInstanceMutable({styleSourceSelections,styleSources,instanceId,- newStyleSource.id- );+ styleSourceId: newStyleSource.id,+ });});selectStyleSource(newStyleSource.id);@@ -150,12 +99,12 @@ export const addStyleSourceToInstance = (serverSyncStore.createTransaction([$styleSourceSelections, $styleSources],(styleSourceSelections, styleSources) => {- addStyleSourceToInstanceMutable(+ addStyleSourceToInstanceMutable({styleSourceSelections,styleSources,instanceId,- newStyleSourceId- );+ styleSourceId: newStyleSourceId,+ });});selectStyleSource(newStyleSourceId);@@ -169,14 +118,11 @@ const removeStyleSourceFromInstance = (styleSourceId: StyleSource["id"]) => {serverSyncStore.createTransaction([$styleSourceSelections],(styleSourceSelections) => {- const styleSourceSelection = styleSourceSelections.get(instanceId);- if (styleSourceSelection === undefined) {- return;- }- removeByMutable(- styleSourceSelection.values,- (item) => item === styleSourceId- );+ removeStyleSourceFromInstanceMutable({+ styleSourceSelections,+ instanceId,+ styleSourceId,+ });});// reset selected style source if necessary@@ -196,12 +142,11 @@ const duplicateStyleSource = (styleSourceId: StyleSource["id"]) => {return;}- const newStyleSource: StyleSource = {- type: "token",+ const newStyleSource = createTokenStyleSource({id: nanoid(),name: `${styleSource.name} (copy)`,- };- const clonedStyleSourceIds = new Map();+ });+ const clonedStyleSourceIds = new Map<StyleSource["id"], StyleSource["id"]>();clonedStyleSourceIds.set(styleSourceId, newStyleSource.id);const clonedStyles = cloneStyles($styles.get(), clonedStyleSourceIds);@@ -232,11 +177,10 @@ const convertLocalStyleSourceToToken = (styleSourceId: StyleSource["id"]) => {if (instanceId === undefined) {return;}- const newStyleSource: StyleSource = {- type: "token",+ const newStyleSource = createTokenStyleSource({id: styleSourceId,name: "Local (Copy)",- };+ });serverSyncStore.createTransaction([$styleSources, $styleSourceSelections],(styleSources, styleSourceSelections) => {diff --git a/apps/builder/app/builder/features/workspace/canvas-tools/outline/block-utils.test.ts b/apps/builder/app/builder/features/workspace/canvas-tools/outline/block-utils.test.tsindex 07e5956b04..92475c08b5 100644--- a/apps/builder/app/builder/features/workspace/canvas-tools/outline/block-utils.test.ts+++ b/apps/builder/app/builder/features/workspace/canvas-tools/outline/block-utils.test.ts@@ -16,13 +16,21 @@ const fragment: WebstudioFragment = {styleSources: [],styles: [],};+const targetData = {} as Parameters<+ typeof getTemplateTokenConflicts+>[0]["targetData"];describe("getTemplateTokenConflicts", () => {test("does not scan template token conflicts in content mode", () => {const detect = vi.fn(() => []);expect(- getTemplateTokenConflicts({ fragment, contentMode: true, detect })+ getTemplateTokenConflicts({+ fragment,+ targetData,+ contentMode: true,+ detect,+ })).toEqual([]);expect(detect).not.toHaveBeenCalled();});@@ -32,8 +40,13 @@ describe("getTemplateTokenConflicts", () => {const detect = vi.fn(() => conflicts);expect(- getTemplateTokenConflicts({ fragment, contentMode: false, detect })+ getTemplateTokenConflicts({+ fragment,+ targetData,+ contentMode: false,+ detect,+ })).toBe(conflicts);- expect(detect).toHaveBeenCalledWith({ fragment });+ expect(detect).toHaveBeenCalledWith({ fragment, targetData });});});diff --git a/apps/builder/app/builder/features/workspace/canvas-tools/outline/block-utils.ts b/apps/builder/app/builder/features/workspace/canvas-tools/outline/block-utils.tsindex 41d2718d83..91d90aca22 100644--- a/apps/builder/app/builder/features/workspace/canvas-tools/outline/block-utils.ts+++ b/apps/builder/app/builder/features/workspace/canvas-tools/outline/block-utils.ts@@ -6,15 +6,16 @@ import {} from "~/shared/instance-utils/data";import { insertInstanceChildrenMutable } from "~/shared/instance-utils/insert";import {- insertWebstudioFragmentCopy,detectFragmentTokenConflicts,-} from "~/shared/instance-utils/fragment";+ extractWebstudioFragment,+ insertWebstudioFragmentCopy,+} from "@webstudio-is/project-build/runtime/fragment";import { blockTemplateComponent } from "@webstudio-is/sdk";import { shallowEqual } from "shallow-equal";import { selectInstance } from "~/shared/nano-states";import { builderApi } from "~/shared/builder-api";-import { findAvailableVariables } from "~/shared/data-variables";-import { extractWebstudioFragment } from "~/shared/instance-utils/fragment";+import { findAvailableVariables } from "@webstudio-is/project-build/runtime/data";+import { isFragmentContentModeCopyableProp } from "~/shared/content-mode-copy-policy";import {$registeredComponentMetas,$isContentMode,@@ -79,17 +80,19 @@ const getInsertionIndex = (const getTemplateTokenConflicts = ({fragment,+ targetData,contentMode,detect = detectFragmentTokenConflicts,}: {fragment: WebstudioFragment;+ targetData: ReturnType<typeof getWebstudioData>;contentMode: boolean;detect?: typeof detectFragmentTokenConflicts;}) => {if (contentMode) {return [];}- return detect({ fragment });+ return detect({ fragment, targetData });};export const __testing__ = {@@ -132,9 +135,11 @@ export const insertListItemAt = (listItemSelector: InstanceSelector) => {listItemSelector[0]);- fragment.instances = structuredClone(fragment.instances);- fragment.instances.splice(1);- fragment.instances[0].children = [];+ const [listItemInstance] = fragment.instances;+ if (listItemInstance === undefined) {+ return;+ }+ fragment.instances = [{ ...listItemInstance, children: [] }];updateWebstudioData((data) => {const { newInstanceIds } = insertWebstudioFragmentCopy({@@ -205,7 +210,11 @@ export const insertTemplateAt = async (try {const contentMode = $isContentMode.get();- const conflicts = getTemplateTokenConflicts({ fragment, contentMode });+ const conflicts = getTemplateTokenConflicts({+ fragment,+ targetData: getWebstudioData(),+ contentMode,+ });const conflictResolution =conflicts.length > 0? await builderApi.showTokenConflictDialog(conflicts)@@ -221,6 +230,8 @@ export const insertTemplateAt = async (}),projectId: project.id,conflictResolution,+ metas: $registeredComponentMetas.get(),+ contentModeCopyableProp: isFragmentContentModeCopyableProp,contentMode,});const newRootInstanceId = newInstanceIds.get(fragment.instances[0].id);diff --git a/apps/builder/app/builder/features/workspace/canvas-tools/resize-handles.tsx b/apps/builder/app/builder/features/workspace/canvas-tools/resize-handles.tsxindex 53af889177..8f2c7529f0 100644--- a/apps/builder/app/builder/features/workspace/canvas-tools/resize-handles.tsx+++ b/apps/builder/app/builder/features/workspace/canvas-tools/resize-handles.tsx@@ -8,7 +8,7 @@ import {} from "@webstudio-is/design-system";import { useEffect, useRef } from "react";import { $canvasWidth } from "~/builder/shared/nano-states";-import { minCanvasWidth } from "~/shared/breakpoints";+import { minCanvasWidth } from "~/shared/breakpoints-utils";import { $isResizingCanvas, $selectedBreakpointId } from "~/shared/nano-states";import { $breakpoints } from "~/shared/sync/data-stores";diff --git a/apps/builder/app/builder/shared/asset-manager/asset-info.test.ts b/apps/builder/app/builder/shared/asset-manager/asset-info.test.tsdeleted file mode 100644index 451f0a889e..0000000000--- a/apps/builder/app/builder/shared/asset-manager/asset-info.test.ts+++ /dev/null@@ -1,554 +0,0 @@-import { describe, test, expect } from "vitest";-import type { Pages, Props, Styles, Asset, Page } from "@webstudio-is/sdk";-import type {- ImageValue,- FontFamilyValue,- StyleValue,-} from "@webstudio-is/css-engine";-import { __testing__ } from "./asset-info";--const { traverseStyleValue, calculateUsagesByAssetId } = __testing__;--const createPages = ({- meta = {},- homeMeta = {},- pages = new Map(),-}: {- meta?: Pages["meta"];- homeMeta?: Page["meta"];- pages?: Map<Page["id"], Page>;-} = {}): Pages => ({- meta,- homePageId: "home",- rootFolderId: "root",- pages: new Map([- [- "home",- {- id: "home",- name: "Home",- path: "",- title: "Home",- meta: homeMeta,- rootInstanceId: "root",- },- ],- ...pages,- ]),- folders: new Map([- [- "root",- {- id: "root",- name: "Root",- slug: "",- children: ["home", ...pages.keys()],- },- ],- ]),-});--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 | FontFamilyValue)[] = [];- 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 | FontFamilyValue)[] = [];- 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 | FontFamilyValue)[] = [];- 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 | FontFamilyValue)[] = [];- 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 | FontFamilyValue)[] = [];- traverseStyleValue(layersValue, (value) => results.push(value));- expect(results).toEqual([imageValue]);- });-- test("calls callback for fontFamily values", () => {- const fontFamilyValue: FontFamilyValue = {- type: "fontFamily",- value: ["CustomFont", "Arial", "sans-serif"],- };- const results: (ImageValue | FontFamilyValue)[] = [];- traverseStyleValue(fontFamilyValue, (value) => results.push(value));- expect(results).toEqual([fontFamilyValue]);- });- });-- describe("calculateUsagesByAssetId", () => {- test("tracks favicon asset usage", () => {- const pages = createPages({- meta: { faviconAssetId: "favicon-asset" },- });- const props: Props = new Map();- const styles: Styles = new Map();- const assets = new Map<Asset["id"], Asset>();-- const usages = calculateUsagesByAssetId({ pages, props, styles, assets });-- expect(usages.get("favicon-asset")).toEqual([{ type: "favicon" }]);- });-- test("tracks social image asset usage", () => {- const pages = createPages({- homeMeta: { socialImageAssetId: "social-asset" },- });- const props: Props = new Map();- const styles: Styles = new Map();- const assets = new Map<Asset["id"], Asset>();-- const usages = calculateUsagesByAssetId({ pages, props, styles, assets });-- expect(usages.get("social-asset")).toEqual([- { type: "socialImage", pageId: "home" },- ]);- });-- test("tracks marketplace thumbnail asset usage", () => {- const pages = createPages({- pages: new Map([- [- "page-1",- {- id: "page-1",- name: "Page 1",- path: "/page-1",- title: "Page 1",- meta: {},- rootInstanceId: "root-1",- marketplace: { thumbnailAssetId: "thumbnail-asset" },- },- ],- ]),- });- const props: Props = new Map();- const styles: Styles = new Map();- const assets = new Map<Asset["id"], Asset>();-- const usages = calculateUsagesByAssetId({ pages, props, styles, assets });-- expect(usages.get("thumbnail-asset")).toEqual([- { type: "marketplaceThumbnail", pageId: "page-1" },- ]);- });-- test("tracks prop asset usage", () => {- const pages = createPages();- 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 assets = new Map<Asset["id"], Asset>();-- const usages = calculateUsagesByAssetId({ pages, props, styles, assets });-- expect(usages.get("asset-1")).toEqual([- { type: "prop", propId: "prop-1" },- ]);- });-- test("ignores width and height props", () => {- const pages = createPages();- 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 assets = new Map<Asset["id"], Asset>();-- const usages = calculateUsagesByAssetId({ pages, props, styles, assets });-- expect(usages.get("asset-1")).toBeUndefined();- });-- test("tracks image asset usage in styles", () => {- const pages = createPages();- 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 assets = new Map<Asset["id"], Asset>();-- const usages = calculateUsagesByAssetId({ pages, props, styles, assets });-- expect(usages.get("asset-1")).toEqual([- { type: "style", styleDeclKey: "style-1:breakpoint-1:property" },- ]);- });-- test("returns empty map when no usages", () => {- const pages = createPages();- const props: Props = new Map();- const styles: Styles = new Map();- const assets = new Map<Asset["id"], Asset>();-- const usages = calculateUsagesByAssetId({ pages, props, styles, assets });-- expect(usages.size).toBe(0);- });-- test("aggregates multiple usages for same asset", () => {- const pages = createPages({- meta: { faviconAssetId: "asset-1" },- homeMeta: { socialImageAssetId: "asset-1" },- });- 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 assets = new Map<Asset["id"], Asset>();-- const usages = calculateUsagesByAssetId({ pages, props, styles, assets });-- 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 assets = new Map<Asset["id"], Asset>();-- const usages = calculateUsagesByAssetId({ pages, props, styles, assets });-- expect(usages.size).toBe(0);- });-- test("tracks multiple assets in tuple style value", () => {- const pages = createPages();- 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 assets = new Map<Asset["id"], Asset>();-- const usages = calculateUsagesByAssetId({ pages, props, styles, assets });-- 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" },- ]);- });-- test("tracks font asset usage in fontFamily styles", () => {- const pages = createPages();- const props: Props = new Map();- const styles: Styles = new Map([- [- "style-1:breakpoint-1:fontFamily",- {- breakpointId: "breakpoint-1",- styleSourceId: "style-1",- property: "fontFamily",- value: {- type: "fontFamily",- value: ["CustomFont", "Arial", "sans-serif"],- },- },- ],- ]);- const assets = new Map<Asset["id"], Asset>([- [- "font-asset-1",- {- id: "font-asset-1",- type: "font",- name: "CustomFont",- format: "woff2",- size: 5000,- meta: { family: "CustomFont", style: "normal", weight: 400 },- createdAt: "2024-01-01",- projectId: "project-id",- },- ],- ]);-- const usages = calculateUsagesByAssetId({ pages, props, styles, assets });-- expect(usages.get("font-asset-1")).toEqual([- { type: "style", styleDeclKey: "style-1:breakpoint-1:fontFamily" },- ]);- });-- test("tracks multiple font assets in same fontFamily style", () => {- const pages = createPages();- const props: Props = new Map();- const styles: Styles = new Map([- [- "style-1:breakpoint-1:fontFamily",- {- breakpointId: "breakpoint-1",- styleSourceId: "style-1",- property: "fontFamily",- value: {- type: "fontFamily",- value: ["CustomFont", "AnotherFont"],- },- },- ],- ]);- const assets = new Map<Asset["id"], Asset>([- [- "font-asset-1",- {- id: "font-asset-1",- type: "font",- name: "CustomFont",- format: "woff2",- size: 5000,- meta: { family: "CustomFont", style: "normal", weight: 400 },- createdAt: "2024-01-01",- projectId: "project-id",- },- ],- [- "font-asset-2",- {- id: "font-asset-2",- type: "font",- name: "AnotherFont",- format: "woff2",- size: 6000,- meta: { family: "AnotherFont", style: "normal", weight: 400 },- createdAt: "2024-01-01",- projectId: "project-id",- },- ],- ]);-- const usages = calculateUsagesByAssetId({ pages, props, styles, assets });-- expect(usages.get("font-asset-1")).toEqual([- { type: "style", styleDeclKey: "style-1:breakpoint-1:fontFamily" },- ]);- expect(usages.get("font-asset-2")).toEqual([- { type: "style", styleDeclKey: "style-1:breakpoint-1:fontFamily" },- ]);- });-- test("ignores font families without matching assets", () => {- const pages = createPages();- const props: Props = new Map();- const styles: Styles = new Map([- [- "style-1:breakpoint-1:fontFamily",- {- breakpointId: "breakpoint-1",- styleSourceId: "style-1",- property: "fontFamily",- value: {- type: "fontFamily",- value: ["Arial", "sans-serif"],- },- },- ],- ]);- const assets = new Map<Asset["id"], Asset>();-- const usages = calculateUsagesByAssetId({ pages, props, styles, assets });-- expect(usages.size).toBe(0);- });-- test("tracks same font used in multiple styles", () => {- const pages = createPages();- const props: Props = new Map();- const styles: Styles = new Map([- [- "style-1:breakpoint-1:fontFamily",- {- breakpointId: "breakpoint-1",- styleSourceId: "style-1",- property: "fontFamily",- value: {- type: "fontFamily",- value: ["CustomFont"],- },- },- ],- [- "style-2:breakpoint-1:fontFamily",- {- breakpointId: "breakpoint-1",- styleSourceId: "style-2",- property: "fontFamily",- value: {- type: "fontFamily",- value: ["CustomFont"],- },- },- ],- ]);- const assets = new Map<Asset["id"], Asset>([- [- "font-asset-1",- {- id: "font-asset-1",- type: "font",- name: "CustomFont",- format: "woff2",- size: 5000,- meta: { family: "CustomFont", style: "normal", weight: 400 },- createdAt: "2024-01-01",- projectId: "project-id",- },- ],- ]);-- const usages = calculateUsagesByAssetId({ pages, props, styles, assets });-- expect(usages.get("font-asset-1")).toEqual([- { type: "style", styleDeclKey: "style-1:breakpoint-1:fontFamily" },- { type: "style", styleDeclKey: "style-2:breakpoint-1:fontFamily" },- ]);- });- });-});diff --git a/apps/builder/app/builder/shared/asset-manager/asset-info.tsx b/apps/builder/app/builder/shared/asset-manager/asset-info.tsxindex 87f9cf6725..6d143ef784 100644--- a/apps/builder/app/builder/shared/asset-manager/asset-info.tsx+++ b/apps/builder/app/builder/shared/asset-manager/asset-info.tsx@@ -4,18 +4,8 @@ import { useDebouncedCallback } from "use-debounce";import prettyBytes from "pretty-bytes";import { computed } from "nanostores";import { useStore } from "@nanostores/react";-import {- getAllPages,- getMimeTypeByExtension,- IMAGE_MIME_TYPES,-} from "@webstudio-is/sdk";-import type { Asset, Pages, Props, Styles, Instance } from "@webstudio-is/sdk";-import type {- ImageValue,- FontFamilyValue,- StyleValue,-} from "@webstudio-is/css-engine";-import { mapGetOrInsert } from "~/shared/shim";+import { getMimeTypeByExtension, IMAGE_MIME_TYPES } from "@webstudio-is/sdk";+import type { Asset, Instance } from "@webstudio-is/sdk";import {Box,Button,@@ -82,112 +72,10 @@ import {} from "~/builder/shared/assets/asset-utils";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 | FontFamilyValue) => void-) => {- if (styleValue.type === "image") {- callback(styleValue);- }- if (styleValue.type === "fontFamily") {- 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 calculateUsagesByAssetId = ({- pages,- props,- styles,- assets,-}: {- pages: Pages | undefined;- props: Props;- styles: Styles;- assets: Map<Asset["id"], Asset>;-}): Map<Asset["id"], AssetUsage[]> => {- const usagesByAsset = new Map<Asset["id"], AssetUsage[]>();-- // Build font family to asset ID map once for O(1) lookups- const fontFamilyToAssetId = new Map<string, Asset["id"]>();- for (const asset of assets.values()) {- if (asset.type === "font") {- fontFamilyToAssetId.set(asset.meta.family, asset.id);- }- }-- if (pages?.meta?.faviconAssetId) {- const usages = mapGetOrInsert(usagesByAsset, pages.meta.faviconAssetId, []);- usages.push({ type: "favicon" });- }- if (pages) {- for (const page of getAllPages(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, (value) => {- if (value.type === "image" && value.value.type === "asset") {- const usages = mapGetOrInsert(usagesByAsset, value.value.value, []);- usages.push({ type: "style", styleDeclKey });- }- if (value.type === "fontFamily") {- // Match each font family name to its asset ID- for (const fontFamily of value.value) {- const assetId = fontFamilyToAssetId.get(fontFamily);- if (assetId !== undefined) {- const usages = mapGetOrInsert(usagesByAsset, assetId, []);- usages.push({ type: "style", styleDeclKey });- }- }- }- });- }- return usagesByAsset;-};+import {+ calculateUsagesByAssetId,+ type AssetUsage,+} from "@webstudio-is/project-build/runtime/assets";const $usagesByAssetId = computed([$pages, $props, $styles, $assets],@@ -719,8 +607,3 @@ export const AssetInfo = ({ asset }: { asset: Asset }) => {</>);};--export const __testing__ = {- traverseStyleValue,- calculateUsagesByAssetId,-};diff --git a/apps/builder/app/builder/shared/asset-manager/delete-unused-assets.tsx b/apps/builder/app/builder/shared/asset-manager/delete-unused-assets.tsxindex d7eeaf390b..3a5f8eb6e0 100644--- a/apps/builder/app/builder/shared/asset-manager/delete-unused-assets.tsx+++ b/apps/builder/app/builder/shared/asset-manager/delete-unused-assets.tsx@@ -18,7 +18,7 @@ import type { Asset } from "@webstudio-is/sdk";import { $assets, $pages, $props, $styles } from "~/shared/sync/data-stores";import { deleteAssets } from "~/builder/shared/assets";import { formatAssetName } from "~/builder/shared/assets/asset-utils";-import { calculateUsagesByAssetId } from "./asset-info";+import { calculateUsagesByAssetId } from "@webstudio-is/project-build/runtime/assets";const $isDeleteUnusedAssetsDialogOpen = atom(false);diff --git a/apps/builder/app/builder/shared/assets/replace-asset.test.ts b/apps/builder/app/builder/shared/assets/replace-asset.test.tsdeleted file mode 100644index 662904d568..0000000000--- a/apps/builder/app/builder/shared/assets/replace-asset.test.ts+++ /dev/null@@ -1,85 +0,0 @@-import { describe, test, expect } from "vitest";-import type { StyleValue } from "@webstudio-is/css-engine";-import { __testing__ } from "./replace-asset";--const { replaceAssetInStyleValue } = __testing__;--describe("replaceAssetInStyleValue", () => {- test("replaces asset id in a direct image value", () => {- const value: StyleValue = {- type: "image",- value: { type: "asset", value: "old-id" },- };- replaceAssetInStyleValue(value, "old-id", "new-id");- expect(value).toEqual({- type: "image",- value: { type: "asset", value: "new-id" },- });- });-- test("does not mutate image value with a different asset id", () => {- const value: StyleValue = {- type: "image",- value: { type: "asset", value: "other-id" },- };- replaceAssetInStyleValue(value, "old-id", "new-id");- expect(value).toEqual({- type: "image",- value: { type: "asset", value: "other-id" },- });- });-- test("does not mutate image value with url type", () => {- const value: StyleValue = {- type: "image",- value: { type: "url", url: "https://example.com/img.png" },- };- replaceAssetInStyleValue(value, "old-id", "new-id");- expect(value).toEqual({- type: "image",- value: { type: "url", url: "https://example.com/img.png" },- });- });-- test("replaces asset id inside a tuple value", () => {- const value: StyleValue = {- type: "tuple",- value: [- { type: "image", value: { type: "asset", value: "old-id" } },- { type: "image", value: { type: "asset", value: "other-id" } },- ],- };- replaceAssetInStyleValue(value, "old-id", "new-id");- expect(value).toEqual({- type: "tuple",- value: [- { type: "image", value: { type: "asset", value: "new-id" } },- { type: "image", value: { type: "asset", value: "other-id" } },- ],- });- });-- test("replaces asset id inside a layers value", () => {- const value: StyleValue = {- type: "layers",- value: [- { type: "image", value: { type: "asset", value: "old-id" } },- { type: "image", value: { type: "asset", value: "old-id" } },- ],- };- replaceAssetInStyleValue(value, "old-id", "new-id");- expect(value).toEqual({- type: "layers",- value: [- { type: "image", value: { type: "asset", value: "new-id" } },- { type: "image", value: { type: "asset", value: "new-id" } },- ],- });- });-- test("does not mutate non-image value types", () => {- const value: StyleValue = { type: "keyword", value: "auto" };- replaceAssetInStyleValue(value, "old-id", "new-id");- expect(value).toEqual({ type: "keyword", value: "auto" });- });-});diff --git a/apps/builder/app/builder/shared/assets/replace-asset.ts b/apps/builder/app/builder/shared/assets/replace-asset.tsindex 8837195d0b..a341d01af6 100644--- a/apps/builder/app/builder/shared/assets/replace-asset.ts+++ b/apps/builder/app/builder/shared/assets/replace-asset.ts@@ -1,11 +1,11 @@-import { getAllPages, type Asset } from "@webstudio-is/sdk";+import type { Asset } from "@webstudio-is/sdk";import { toast } from "@webstudio-is/design-system";import { $assets, $pages, $props, $styles } from "~/shared/sync/data-stores";import { serverSyncStore } from "~/shared/sync/sync-stores";import { onNextTransactionComplete } from "~/shared/sync/project-queue";import { invalidateAssets } from "~/shared/resources";+import { replaceAssetMutable } from "@webstudio-is/project-build/runtime/assets";import { uploadAssets } from "./upload-assets";-import type { StyleValue } from "@webstudio-is/css-engine";/*** Replace an image asset with a new file.@@ -44,29 +44,15 @@ export const replaceAsset = async (updatedNewAsset.description = oldAsset.description;}- for (const prop of props.values()) {- if (prop.type === "asset" && prop.value === oldAssetId) {- prop.value = newAssetId;- }- }-- for (const styleDecl of styles.values()) {- replaceAssetInStyleValue(styleDecl.value, oldAssetId, newAssetId);- }-- if (pages) {- if (pages.meta?.faviconAssetId === oldAssetId) {- pages.meta.faviconAssetId = newAssetId;- }- for (const page of getAllPages(pages)) {- if (page.meta.socialImageAssetId === oldAssetId) {- page.meta.socialImageAssetId = newAssetId;- }- if (page.marketplace?.thumbnailAssetId === oldAssetId) {- page.marketplace.thumbnailAssetId = newAssetId;- }- }- }+ replaceAssetMutable({+ pages,+ props: props.values(),+ styles: styles.values(),+ replacement: {+ fromAssetId: oldAssetId,+ toAssetId: newAssetId,+ },+ });assets.delete(oldAssetId);}@@ -79,30 +65,6 @@ export const replaceAsset = async (toast.success("Asset replaced successfully");};-const replaceAssetInStyleValue = (- styleValue: StyleValue,- oldAssetId: string,- newAssetId: string-): void => {- if (- styleValue.type === "image" &&- styleValue.value.type === "asset" &&- styleValue.value.value === oldAssetId- ) {- styleValue.value.value = newAssetId;- }- if (styleValue.type === "tuple") {- for (const item of styleValue.value) {- replaceAssetInStyleValue(item, oldAssetId, newAssetId);- }- }- if (styleValue.type === "layers") {- for (const item of styleValue.value) {- replaceAssetInStyleValue(item, oldAssetId, newAssetId);- }- }-};-const waitForAsset = (assetId: string): Promise<Asset> => {// Check if asset already exists (avoids TDZ with synchronous subscribe callback)const existingAsset = $assets.get().get(assetId);@@ -121,5 +83,3 @@ const waitForAsset = (assetId: string): Promise<Asset> => {});});};--export const __testing__ = { replaceAssetInStyleValue };diff --git a/apps/builder/app/builder/shared/binding-popover.tsx b/apps/builder/app/builder/shared/binding-popover.tsxindex 714f06a777..a434d0294b 100644--- a/apps/builder/app/builder/shared/binding-popover.tsx+++ b/apps/builder/app/builder/shared/binding-popover.tsx@@ -35,13 +35,13 @@ import {import {decodeDataSourceVariable,getExpressionIdentifiers,- lintExpression,} from "@webstudio-is/sdk";+import { getExpressionErrorMessages } from "~/shared/expression-validation";import { $dataSourceVariables, $isDesignMode } from "~/shared/nano-states";import {computeExpression,encodeDataVariableName,-} from "~/shared/data-variables";+} from "@webstudio-is/project-build/runtime/data";import {ExpressionEditor,formatValuePreview,@@ -122,12 +122,10 @@ const BindingPanel = ({const scopeEntries = Object.entries(scope);const validate = (expression: string) => {- const diagnostics = lintExpression({+ const errors = getExpressionErrorMessages({expression,availableVariables: new Set(aliases.keys()),});- // prevent saving expression only with syntax error- const errors = diagnostics.filter((item) => item.severity === "error");setErrorsCount(errors.length);};diff --git a/apps/builder/app/builder/shared/calc-canvas-width.ts b/apps/builder/app/builder/shared/calc-canvas-width.tsindex 8b96b5aae8..bd49cf132d 100644--- a/apps/builder/app/builder/shared/calc-canvas-width.ts+++ b/apps/builder/app/builder/shared/calc-canvas-width.ts@@ -4,8 +4,8 @@ import type { Breakpoint } from "@webstudio-is/sdk";import {groupBreakpoints,isBaseBreakpoint,- minCanvasWidth,-} from "~/shared/breakpoints-utils";+} from "@webstudio-is/project-build/runtime/breakpoints";+import { minCanvasWidth } from "~/shared/breakpoints-utils";import { $workspaceRect, $canvasWidth } from "~/builder/shared/nano-states";import { $isPreviewMode, $selectedBreakpoint } from "~/shared/nano-states";import { $breakpoints } from "~/shared/sync/data-stores";diff --git a/apps/builder/app/builder/shared/commands.ts b/apps/builder/app/builder/shared/commands.tsindex 85ae2a1061..baaebff09d 100644--- a/apps/builder/app/builder/shared/commands.ts+++ b/apps/builder/app/builder/shared/commands.ts@@ -9,13 +9,12 @@ import { toggleInstanceShow } from "~/shared/instance-utils/mutation";import {extractWebstudioFragment,insertWebstudioFragmentCopy,-} from "~/shared/instance-utils/fragment";+} from "@webstudio-is/project-build/runtime/fragment";import { insertWebstudioFragmentAt } from "~/shared/instance-utils/insert";import { toast } from "@webstudio-is/design-system";import {ROOT_INSTANCE_ID,isComponentDetachable,- type Instance,type WebstudioFragment,} from "@webstudio-is/sdk";import type { Project } from "@webstudio-is/project";@@ -82,7 +81,7 @@ import { showWrapComponentsList } from "../features/command-panel/groups/wrap-grimport { showConvertComponentsList } from "../features/command-panel/groups/convert-group";import { builderApi } from "~/shared/builder-api";import { getSetting, setSetting } from "./client-settings";-import { findAvailableVariables } from "~/shared/data-variables";+import { findAvailableVariables } from "@webstudio-is/project-build/runtime/data";import { generateFragmentFromHtml } from "~/shared/html";import { generateFragmentFromTailwind } from "~/shared/tailwind/tailwind";import { denormalizeSrcProps } from "~/shared/copy-paste/asset-upload";@@ -110,6 +109,7 @@ import {} from "~/shared/instance-utils/slot";import type { InstanceSelector } from "~/shared/instance-utils/tree";import { areInstanceSelectorsEqual } from "~/shared/instance-utils/tree";+import { findChildReferenceIndex } from "@webstudio-is/project-build/runtime/instances";const makeBreakpointCommand = <CommandName extends string>(name: CommandName,@@ -259,11 +259,6 @@ const requestSelectedPageItemDelete = () => {type InstanceMoveDirection = "up" | "down" | "intoPreviousSibling" | "out";-const getIdChildIndex = (children: Instance["children"], instanceId: string) =>- children.findIndex(- (child) => child.type === "id" && child.value === instanceId- );-type SelectedInstancePath = {index: number;instancePath: InstancePath;@@ -464,7 +459,7 @@ const duplicateSelectedInstances = (project: Project) => {if (parentInstance === undefined) {continue;}- const indexWithinChildren = getIdChildIndex(+ const indexWithinChildren = findChildReferenceIndex(parentInstance.children,selectedItem.instance.id);@@ -507,7 +502,7 @@ const getOutdentMoveTarget = (if (slotParentItem === undefined) {return;}- const slotPosition = getIdChildIndex(+ const slotPosition = findChildReferenceIndex(slotParentItem.instance.children,directSlotBoundary.slotId);@@ -522,7 +517,7 @@ const getOutdentMoveTarget = (}const parent = parentItem.instance;- const parentIndex = getIdChildIndex(+ const parentIndex = findChildReferenceIndex(grandparentItem.instance.children,parent.id);@@ -549,7 +544,7 @@ const getInstanceMoveTarget = (direction: InstanceMoveDirection) => {}const parent = parentItem.instance;- const selectedIndex = getIdChildIndex(+ const selectedIndex = findChildReferenceIndex(parent.children,selectedItem.instance.id);diff --git a/apps/builder/app/builder/shared/css-variable-utils.test.tsx b/apps/builder/app/builder/shared/css-variable-utils.test.tsxindex 676cb7ef7e..326c6d8d47 100644--- a/apps/builder/app/builder/shared/css-variable-utils.test.tsx+++ b/apps/builder/app/builder/shared/css-variable-utils.test.tsx@@ -4,8 +4,8 @@ import type { StyleDecl, Styles, Prop } from "@webstudio-is/sdk";import type { StyleProperty, StyleValue } from "@webstudio-is/css-engine";import { parseCssValue } from "@webstudio-is/css-data";import { $styles } from "~/shared/sync/data-stores";+import { findCssVariableUsagesByInstance } from "@webstudio-is/project-build/runtime/styles";import {- findCssVariableUsagesByInstance,validateCssVariableName,performCssVariableRename,updateVarReferencesInProps,diff --git a/apps/builder/app/builder/shared/css-variable-utils.tsx b/apps/builder/app/builder/shared/css-variable-utils.tsxindex 9ac1f57a3f..6c0d531385 100644--- a/apps/builder/app/builder/shared/css-variable-utils.tsx+++ b/apps/builder/app/builder/shared/css-variable-utils.tsx@@ -14,25 +14,26 @@ import {InputField,toast,} from "@webstudio-is/design-system";-import type {- Instance,- StyleDecl,- StyleSourceSelections,- Props,-} from "@webstudio-is/sdk";-import type {- StyleValue,- StyleProperty,- CustomProperty,-} from "@webstudio-is/css-engine";-import { toValue } from "@webstudio-is/css-engine";+import type { CustomProperty } from "@webstudio-is/css-engine";import {$styles,$styleSourceSelections,$props,} from "~/shared/sync/data-stores";import { serverSyncStore } from "~/shared/sync/sync-stores";-import { getStyleDeclKey } from "@webstudio-is/sdk";+import {+ findCssVariableUsagesByInstance,+ getCssVariableDefinitionsByVariable,+ getDefinedCssVariableNames,+ getReferencedCssVariables,+ performCssVariableRename,+ renameCssVariableMutable,+ updateVarReferencesInProps,+ validateCssVariableNameWithStyles,+} from "@webstudio-is/project-build/runtime/styles";+import { type CssVariableNameError } from "@webstudio-is/project-build/runtime/styles";++export { performCssVariableRename, updateVarReferencesInProps };const $isDeleteUnusedCssVariablesDialogOpen = atom(false);@@ -40,133 +41,13 @@ export const openDeleteUnusedCssVariablesDialog = () => {$isDeleteUnusedCssVariablesDialogOpen.set(true);};-// Utility: Escape regex special characters-const escapeRegex = (str: string): string => {- return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");-};--// Utility: Create regex to match variable name with word boundary-// This avoids matching --color inside --color-dark-// Uses negative lookahead (?![\\w-]) to ensure variable name doesn't continue-// with word characters or hyphens, preventing partial matches.-const createVarNameRegex = (varName: string): RegExp => {- return new RegExp(`${escapeRegex(varName)}(?![\\w-])`, "g");-};--const createVarNamesRegex = (definedVariables: Set<string>): RegExp => {- const alternatives = Array.from(definedVariables)- .sort((left, right) => right.length - left.length)- .map(escapeRegex)- .join("|");- return new RegExp(`(?:${alternatives})(?![\\w-])`, "g");-};--const collectVariableReferencesFromString = (value: string, regex: RegExp) => {- const varReferences = new Set<string>();- regex.lastIndex = 0;- for (const match of value.matchAll(regex)) {- varReferences.add(match[0]);- }- return varReferences;-};--const getDefinedVariables = (styles: Map<string, StyleDecl>) => {- const definedVariables = new Set<string>();- for (const styleDecl of styles.values()) {- if (styleDecl.property.startsWith("--")) {- definedVariables.add(styleDecl.property);- }- }- return definedVariables;-};--const getInstancesByStyleSource = (- styleSourceSelections: StyleSourceSelections-) => {- const instancesByStyleSource = new Map<string, Instance["id"]>();- for (const { instanceId, values } of styleSourceSelections.values()) {- for (const styleSourceId of values) {- instancesByStyleSource.set(styleSourceId, instanceId);- }- }- return instancesByStyleSource;-};--// Find CSS variable usage counts (how many times each variable is referenced via var())-export const findCssVariableUsagesByInstance = ({- styleSourceSelections,- styles,- props,-}: {- styleSourceSelections: StyleSourceSelections;- styles: Map<string, StyleDecl>;- props: Props;-}): {- counts: Map<string, number>;- instances: Map<string, Set<Instance["id"]>>;-} => {- const usageCounts = new Map<string, number>();- const usageInstances = new Map<string, Set<Instance["id"]>>();-- const definedVariables = getDefinedVariables(styles);- if (definedVariables.size === 0) {- return { counts: usageCounts, instances: usageInstances };- }- const definedVariablesRegex = createVarNamesRegex(definedVariables);-- const instancesByStyleSource = getInstancesByStyleSource(- styleSourceSelections- );-- const addVarReference = (varName: string, instanceId: Instance["id"]) => {- const count = usageCounts.get(varName) ?? 0;- usageCounts.set(varName, count + 1);-- let instances = usageInstances.get(varName);- if (instances === undefined) {- instances = new Set();- usageInstances.set(varName, instances);- }- instances.add(instanceId);- };-- // Track CSS variable references in StyleDecl values- for (const styleDecl of styles.values()) {- const instanceId = instancesByStyleSource.get(styleDecl.styleSourceId);- if (!instanceId) {- continue;- }-- for (const varName of collectVariableReferencesFromString(- toValue(styleDecl.value),- definedVariablesRegex- )) {- addVarReference(varName, instanceId);- }- }-- // Track CSS variable references in HTML Embed code props- for (const prop of props.values()) {- if (prop.type === "string" && prop.name === "code" && prop.value) {- for (const varName of collectVariableReferencesFromString(- prop.value,- definedVariablesRegex- )) {- addVarReference(varName, prop.instanceId);- }- }- }-- return { counts: usageCounts, instances: usageInstances };-};-const $cssVariableUsageData = computed([$styleSourceSelections, $styles, $props],(styleSourceSelections, styles, props) => {return findCssVariableUsagesByInstance({- styleSourceSelections,- styles,- props,+ styleSourceSelections: styleSourceSelections.values(),+ styles: styles.values(),+ props: props.values(),});});@@ -183,35 +64,17 @@ export const $cssVariableInstancesByVariable = computed(// Get all defined CSS variables (unique properties that start with --)export const $definedCssVariables = computed($styles, (styles) => {- return getDefinedVariables(styles) as Set<CustomProperty>;+ return getDefinedCssVariableNames(styles.values()) as Set<CustomProperty>;});// Map CSS variables to the instances where they are definedexport const $cssVariableDefinitionsByVariable = computed([$styleSourceSelections, $styles],(styleSourceSelections, styles) => {- const definitionsByVariable = new Map<string, Set<Instance["id"]>>();-- const instancesByStyleSource = getInstancesByStyleSource(- styleSourceSelections- );-- // Find all CSS variable definitions- for (const styleDecl of styles.values()) {- if (styleDecl.property.startsWith("--")) {- const instanceId = instancesByStyleSource.get(styleDecl.styleSourceId);- if (instanceId) {- let instances = definitionsByVariable.get(styleDecl.property);- if (instances === undefined) {- instances = new Set();- definitionsByVariable.set(styleDecl.property, instances);- }- instances.add(instanceId);- }- }- }-- return definitionsByVariable;+ return getCssVariableDefinitionsByVariable({+ styleSourceSelections: styleSourceSelections.values(),+ styles: styles.values(),+ });});@@ -219,34 +82,10 @@ export const $cssVariableDefinitionsByVariable = computed(export const $referencedCssVariables = computed([$styles, $props],(styles, props) => {- const referencedVariables = new Set<string>();-- const definedVariables = getDefinedVariables(styles);- if (definedVariables.size === 0) {- return referencedVariables;- }-- const definedVariablesRegex = createVarNamesRegex(definedVariables);- for (const styleDecl of styles.values()) {- for (const varName of collectVariableReferencesFromString(- toValue(styleDecl.value),- definedVariablesRegex- )) {- referencedVariables.add(varName);- }- }- for (const prop of props.values()) {- if (prop.type === "string" && prop.name === "code" && prop.value) {- for (const varName of collectVariableReferencesFromString(- prop.value,- definedVariablesRegex- )) {- referencedVariables.add(varName);- }- }- }-- return referencedVariables;+ return getReferencedCssVariables({+ styles: styles.values(),+ props: props.values(),+ });});@@ -264,178 +103,32 @@ export const $unusedCssVariables = computed(});-type CssVariableError =- | { type: "required"; message: string }- | { type: "invalid"; message: string }- | { type: "duplicate"; message: string };-export const validateCssVariableName = (name: string,currentProperty?: string-): CssVariableError | undefined => {- // Check if name is required- if (name.trim().length === 0) {- return {- type: "required",- message: "CSS variable name cannot be empty",- };- }-- // Ensure name starts with --- if (!name.startsWith("--")) {- return {- type: "invalid",- message: 'CSS variable name must start with "--"',- };- }-- // Check for duplicates within the same style source + breakpoint + state- const styles = $styles.get();- for (const styleDecl of styles.values()) {- if (- styleDecl.property === name &&- styleDecl.property !== currentProperty &&- styleDecl.property.startsWith("--")- ) {- return {- type: "duplicate",- message: `CSS variable "${name}" already exists`,- };- }- }-};--// Update all var() references in a StyleValue-const updateVarReferences = (- value: StyleValue,- oldProperty: string,- newProperty: string-): StyleValue => {- // For simple replacement, use JSON stringify/parse approach- // since toValue produces CSS string which is harder to parse back- let valueStr = JSON.stringify(value);-- // Handle two patterns:- // 1. In var type objects: "value":"variable-name" (without --)- // StyleValue stores var without -- prefix in "value" field- // 2. In literal strings: "--variable-name" (with --)- // Unparsed strings contain full --variable-name syntax- // Both patterns are needed because StyleValue can contain both structured- // var types and unparsed CSS strings with var() references-- // Strip -- prefix for var type replacement- const oldVarName = oldProperty.startsWith("--")- ? oldProperty.slice(2)- : oldProperty;- const newVarName = newProperty.startsWith("--")- ? newProperty.slice(2)- : newProperty;-- // Replace in var type value fields: "value":"old-name" -> "value":"new-name"- // Use word boundary to avoid replacing "color" in "color-dark"- const varTypeRegex = new RegExp(- `("value":")${escapeRegex(oldVarName)}(?![\\w-])`,- "g"- );- valueStr = valueStr.replace(varTypeRegex, `$1${newVarName}`);-- // Also replace literal --variable-name in unparsed strings- valueStr = valueStr.replace(createVarNameRegex(oldProperty), newProperty);-- return JSON.parse(valueStr) as StyleValue;-};--// Core rename logic without transaction wrapper (for testing)-export const performCssVariableRename = (- styles: Map<string, StyleDecl>,- oldProperty: string,- newProperty: string-): Map<string, StyleDecl> => {- const updatedStyles = new Map(styles);-- // Update all StyleDecl with the old property name- const styleDeclsToUpdate: Array<{ key: string; decl: StyleDecl }> = [];- for (const [key, styleDecl] of updatedStyles) {- if (styleDecl.property === oldProperty) {- styleDeclsToUpdate.push({ key, decl: styleDecl });- }- }-- for (const { key, decl } of styleDeclsToUpdate) {- updatedStyles.delete(key);- const newDecl = { ...decl, property: newProperty as StyleProperty };- updatedStyles.set(getStyleDeclKey(newDecl), newDecl);- }-- // Update all var() references in StyleValue- const styleDeclsToUpdateRefs: Array<{ key: string; decl: StyleDecl }> = [];- for (const [key, styleDecl] of updatedStyles) {- styleDeclsToUpdateRefs.push({ key, decl: styleDecl });- }-- for (const { key, decl } of styleDeclsToUpdateRefs) {- const newValue = updateVarReferences(decl.value, oldProperty, newProperty);- if (newValue !== decl.value) {- updatedStyles.set(key, { ...decl, value: newValue });- }- }-- return updatedStyles;-};--// Update var() references in HTML Embed code props (pure function for testing)-export const updateVarReferencesInProps = (- props: Props,- oldProperty: string,- newProperty: string-): Props => {- const updatedProps = new Map(props);- const regex = createVarNameRegex(oldProperty);-- for (const [key, prop] of updatedProps) {- if (prop.type === "string" && prop.name === "code" && prop.value) {- const updatedValue = prop.value.replace(regex, newProperty);- if (updatedValue !== prop.value) {- updatedProps.set(key, { ...prop, value: updatedValue });- }- }- }-- return updatedProps;-};+) =>+ validateCssVariableNameWithStyles({+ name,+ currentProperty,+ styles: $styles.get().values(),+ });export const renameCssVariable = (oldProperty: string,newProperty: string-): CssVariableError | undefined => {+): CssVariableNameError | undefined => {const validationError = validateCssVariableName(newProperty, oldProperty);if (validationError) {return validationError;}serverSyncStore.createTransaction([$styles, $props], (styles, props) => {- const updatedStyles = performCssVariableRename(+ renameCssVariableMutable({styles,- oldProperty,- newProperty- );-- // Clear and repopulate the styles map- styles.clear();- for (const [key, value] of updatedStyles) {- styles.set(key, value);- }-- // Update var() references in HTML Embed code props- const updatedProps = updateVarReferencesInProps(props,oldProperty,- newProperty- );- props.clear();- for (const [key, value] of updatedProps) {- props.set(key, value);- }+ newProperty,+ });});return;diff --git a/apps/builder/app/builder/shared/data-variable-utils.tsx b/apps/builder/app/builder/shared/data-variable-utils.tsxindex 5b0c5f0bb7..d072c044d8 100644--- a/apps/builder/app/builder/shared/data-variable-utils.tsx+++ b/apps/builder/app/builder/shared/data-variable-utils.tsx@@ -24,7 +24,11 @@ import {$resources,} from "~/shared/sync/data-stores";import { serverSyncStore } from "~/shared/sync/sync-stores";-import { findVariableUsagesByInstance } from "~/shared/data-variables";+import {+ findVariableUsagesByInstance,+ validateDataVariableNameWithSources,+} from "@webstudio-is/project-build/runtime/data";+import { type DataVariableNameError } from "@webstudio-is/project-build/runtime/data";const $isDeleteUnusedDataVariablesDialogOpen = atom(false);@@ -32,10 +36,7 @@ export const openDeleteUnusedDataVariablesDialog = () => {$isDeleteUnusedDataVariablesDialogOpen.set(true);};-export type DataVariableError = {- type: "required" | "duplicate";- message: string;-};+export type DataVariableError = DataVariableNameError;const getUsedVariablesInInstances = () => {return findVariableUsagesByInstance({@@ -121,19 +122,11 @@ export const deleteUnusedDataVariables = () => {return 0;}- serverSyncStore.createTransaction(- [$dataSources, $resources],- (dataSources, resources) => {- for (const variableId of unusedVariableIds) {- const dataSource = dataSources.get(variableId);- // Cleanup resource when variable is deleted- if (dataSource?.type === "resource") {- resources.delete(dataSource.resourceId);- }- dataSources.delete(variableId);- }+ serverSyncStore.createTransaction([$dataSources], (dataSources) => {+ for (const variableId of unusedVariableIds) {+ dataSources.delete(variableId);}- );+ });return unusedVariableIds.length;};@@ -143,13 +136,6 @@ export const validateDataVariableName = (variableId?: DataSource["id"],scopeInstanceId?: Instance["id"]): DataVariableError | undefined => {- if (name.trim().length === 0) {- return {- type: "required",- message: "Variable name is required",- };- }-const dataSources = $dataSources.get();const currentVariable = variableId ? dataSources.get(variableId) : undefined;const actualScopeInstanceId =@@ -157,20 +143,12 @@ export const validateDataVariableName = ((currentVariable?.type === "variable"? currentVariable.scopeInstanceId: undefined);-- for (const dataSource of dataSources.values()) {- if (- dataSource.type === "variable" &&- dataSource.scopeInstanceId === actualScopeInstanceId &&- dataSource.name === name &&- dataSource.id !== variableId- ) {- return {- type: "duplicate",- message: "Name is already used by another variable on this instance",- };- }- }+ return validateDataVariableNameWithSources({+ dataSources: dataSources.values(),+ name,+ variableId,+ scopeInstanceId: actualScopeInstanceId,+ });};export const renameDataVariable = (diff --git a/apps/builder/app/builder/shared/expression-editor.tsx b/apps/builder/app/builder/shared/expression-editor.tsxindex f605363355..741d9e83c3 100644--- a/apps/builder/app/builder/shared/expression-editor.tsx+++ b/apps/builder/app/builder/shared/expression-editor.tsx@@ -47,7 +47,7 @@ import {encodeDataVariableName,restoreExpressionVariables,unsetExpressionVariables,-} from "~/shared/data-variables";+} from "@webstudio-is/project-build/runtime/data";export type { EditorApi };diff --git a/apps/builder/app/builder/shared/style-source-actions.test.tsx b/apps/builder/app/builder/shared/style-source-actions.test.tsxnew file mode 100644index 0000000000..07fe3a77bc--- /dev/null+++ b/apps/builder/app/builder/shared/style-source-actions.test.tsx@@ -0,0 +1,46 @@+import { expect, test } from "vitest";+import {+ selectInstance,+ $selectedStyleSources,+ $selectedStyleState,+} from "~/shared/nano-states";+import { $instances } from "~/shared/sync/data-stores";+import { deselectMatchingStyleSource } from "./style-source-actions";++test("deselects matching style source for selected instance", () => {+ $instances.set(+ new Map([+ [+ "instance",+ { type: "instance", id: "instance", component: "Box", children: [] },+ ],+ ])+ );+ selectInstance(["instance"]);+ $selectedStyleSources.set(new Map([["instance", "style-source"]]));+ $selectedStyleState.set(":hover");++ deselectMatchingStyleSource("style-source");++ expect($selectedStyleSources.get().has("instance")).toBe(false);+ expect($selectedStyleState.get()).toBeUndefined();+});++test("keeps selection when selected style source does not match", () => {+ $instances.set(+ new Map([+ [+ "instance",+ { type: "instance", id: "instance", component: "Box", children: [] },+ ],+ ])+ );+ selectInstance(["instance"]);+ $selectedStyleSources.set(new Map([["instance", "style-source"]]));+ $selectedStyleState.set(":hover");++ deselectMatchingStyleSource("other-style-source");++ expect($selectedStyleSources.get().get("instance")).toBe("style-source");+ expect($selectedStyleState.get()).toBe(":hover");+});diff --git a/apps/builder/app/builder/shared/style-source-actions.tsx b/apps/builder/app/builder/shared/style-source-actions.tsxindex 77d054b35d..5ea736430b 100644--- a/apps/builder/app/builder/shared/style-source-actions.tsx+++ b/apps/builder/app/builder/shared/style-source-actions.tsx@@ -15,6 +15,7 @@ import {toast,} from "@webstudio-is/design-system";import type { Instance, StyleSource } from "@webstudio-is/sdk";+import type { RenameStyleSourceError } from "@webstudio-is/project-build/runtime/styles";import {$selectedStyleSources,$selectedStyleState,@@ -23,13 +24,12 @@ import { $styleSources } from "~/shared/sync/data-stores";import { $styleSourceSelections, $styles } from "~/shared/sync/data-stores";import {deleteStyleSourceMutable,- findUnusedTokens,deleteStyleSourcesMutable,- validateAndRenameStyleSource,+ findUnusedTokens,renameStyleSourceMutable,toggleStyleSourceLockMutable,- type RenameStyleSourceError,-} from "~/shared/style-source-utils";+ validateAndRenameStyleSource,+} from "@webstudio-is/project-build/runtime/styles";import { serverSyncStore } from "~/shared/sync/sync-stores";import { $selectedInstance } from "~/shared/nano-states";@@ -57,7 +57,9 @@ export const $styleSourceUsages = computed(});-const deselectMatchingStyleSource = (styleSourceId: StyleSource["id"]) => {+export const deselectMatchingStyleSource = (+ styleSourceId: StyleSource["id"]+) => {const instanceId = $selectedInstance.get()?.id;if (instanceId === undefined) {return;diff --git a/apps/builder/app/routes/_ui.(builder).tsx b/apps/builder/app/routes/_ui.(builder).tsxindex 01f0b6497b..2ceb885852 100644--- a/apps/builder/app/routes/_ui.(builder).tsx+++ b/apps/builder/app/routes/_ui.(builder).tsx@@ -28,7 +28,7 @@ import env from "~/env/env.server";import builderStyles from "~/builder/builder.css?url";import { ClientOnly } from "~/shared/client-only";-import { parseBuilderUrl } from "@webstudio-is/http-client";+import { parseBuilderUrl } from "@webstudio-is/protocol";import { preventCrossOriginCookie } from "~/services/no-cross-origin-cookie";import { redirect } from "~/services/no-store-redirect";import { builderSessionStorage } from "~/services/builder-session.server";diff --git a/apps/builder/app/routes/_ui.dashboard.tsx b/apps/builder/app/routes/_ui.dashboard.tsxindex 9729de6ca8..a62c4ed3f9 100644--- a/apps/builder/app/routes/_ui.dashboard.tsx+++ b/apps/builder/app/routes/_ui.dashboard.tsx@@ -17,7 +17,7 @@ import { db as authDb } from "@webstudio-is/authorization-token/index.server";import * as projectApi from "@webstudio-is/project/index.server";import { notification as notificationApi } from "@webstudio-is/project/index.server";import type { Role } from "@webstudio-is/project";-import { parseBuilderUrl } from "@webstudio-is/http-client";+import { parseBuilderUrl } from "@webstudio-is/protocol";import { dashboardProjectRouter } from "@webstudio-is/dashboard/index.server";import { builderUrl, isDashboard, loginPath } from "~/shared/router-utils";import { getSetting, setSetting } from "~/builder/shared/client-settings";diff --git a/apps/builder/app/routes/builder-logout.ts b/apps/builder/app/routes/builder-logout.tsindex 7bee51dbe1..9e9ea6b5f8 100644--- a/apps/builder/app/routes/builder-logout.ts+++ b/apps/builder/app/routes/builder-logout.ts@@ -1,144 +1,6 @@-import { json, type ActionFunctionArgs } from "@remix-run/server-runtime";-import { createDebug } from "~/shared/debug";import { builderAuthenticator } from "~/services/builder-auth.server";-import { getAuthorizationServerOrigin } from "~/shared/router-utils/origins";-import { isBuilder, loginPath } from "~/shared/router-utils";-import { isRedirectResponse } from "~/services/cookie.server";-import {- appendVaryHeader,- createPrivateNoStoreHeaders,-} from "~/services/cache-control.server";+import { createBuilderLogoutAction } from "~/services/builder-logout-action.server";-const debug = createDebug(import.meta.url);--const getCorsHeaders = (request: Request) => {- const origin = request.headers.get("Origin");- const allowedOrigin = getAuthorizationServerOrigin(request.url);-- if (origin !== allowedOrigin) {- return;- }-- return {- "Access-Control-Allow-Credentials": "true",- "Access-Control-Allow-Headers": "Content-Type",- "Access-Control-Allow-Methods": "POST, OPTIONS",- "Access-Control-Allow-Origin": origin,- };-};--const withCors = (request: Request, response: Response) => {- const corsHeaders = getCorsHeaders(request);- if (corsHeaders === undefined) {- return response;- }-- const headers = createPrivateNoStoreHeaders(response.headers);- for (const [name, value] of Object.entries(corsHeaders)) {- headers.set(name, value);- }- appendVaryHeader(headers, "Origin");-- return new Response(response.body, {- status: response.status,- statusText: response.statusText,- headers,- });-};--export const action = async ({ request }: ActionFunctionArgs) => {- // IMPORTANT: This route allows cross-origin cookies to enable dashboard logout from builders.- // Enforcing preflight by checking Content-Type to be application/json.- // Both the preflight and actual logout response must include CORS headers- // or browser fetch reports the project logout as failed.-- if (false === isBuilder(request)) {- throw new Response("Not found", {- status: 404,- });- }-- if (request.method === "OPTIONS") {- const corsHeaders = getCorsHeaders(request);- if (corsHeaders === undefined) {- return new Response("Origin not allowed", {- status: 403,- });- }-- const headers = createPrivateNoStoreHeaders(corsHeaders);- appendVaryHeader(headers, "Origin");-- return new Response(null, {- status: 204,- headers,- });- }-- if (request.method !== "POST") {- return withCors(- request,- json(- { message: "Method not allowed" },- {- status: 405,- }- )- );- }-- if (request.headers.get("sec-fetch-site") === "same-origin") {- // To prevent logout initiated from the builder iframe-- return withCors(- request,- new Response("Only cross-origin requests are allowed", {- status: 403,- })- );- }-- if (- false === request.headers.get("Content-Type")?.includes("application/json")- ) {- // Enforce preflight request, preflight is checked on allowed origin-- return withCors(- request,- new Response("Invalid content type, only application/json is allowed", {- status: 415,- })- );- }-- const redirectTo = `${getAuthorizationServerOrigin(request.url)}${loginPath({})}`;-- try {- debug("Logging out");-- await builderAuthenticator.logout(request, {- redirectTo,- });- } catch (error) {- if (error instanceof Response) {- if (isRedirectResponse(error)) {- return withCors(- request,- new Response(null, {- status: 204,- headers: error.headers,- })- );- }-- return withCors(request, error);- }-- console.error(error);- throw error;- }-- throw new Response("Should not reach this point", {- status: 500,- });-};+export const action = createBuilderLogoutAction((request, options) =>+ builderAuthenticator.logout(request, options)+);diff --git a/apps/builder/app/routes/rest.assets_.$name.tsx b/apps/builder/app/routes/rest.assets_.$name.tsxindex 34f546e002..8e7fbf0010 100644--- a/apps/builder/app/routes/rest.assets_.$name.tsx+++ b/apps/builder/app/routes/rest.assets_.$name.tsx@@ -1,17 +1,9 @@-import { z } from "zod";import { json, type ActionFunctionArgs } from "@remix-run/server-runtime";import {+ createUploadName,uploadFile,type UploadErrorCleanup,} from "@webstudio-is/asset-uploader/index.server";-import {- isAllowedMimeCategory,- RESIZABLE_IMAGE_MIME_TYPES,- ALLOWED_FILE_TYPES,- type Asset,- assetType,-} from "@webstudio-is/sdk";-import type { Database } from "@webstudio-is/postgrest/index.server";import { isAssetFileName } from "@webstudio-is/protocol";import type { AssetActionResponse } from "~/builder/shared/assets";import { createAssetClient } from "~/shared/asset-client";@@ -20,104 +12,14 @@ import { preventCrossOriginCookie } from "~/services/no-cross-origin-cookie";import { checkCsrf } from "~/services/csrf-session.server";import { parseError } from "~/shared/error/error-parse";import { privateNoStoreResponseHeaders } from "~/services/cache-control.server";-import { assertProjectBuildPermit } from "~/services/project-import.server";--const urlBody = z.object({- url: z.string(),-});--const parseAssetType = (value: string | null) => {- const result = assetType.safeParse(value);- return result.success ? result.data : undefined;-};--type AssetInfoFallback =- | { width: number; height: number; format: string }- | undefined;-type FileRow = Database["public"]["Tables"]["File"]["Row"];--const getAssetInfoFallback = ({- format,- searchParams,-}: {- format: string | undefined;- searchParams: URLSearchParams;-}) => {- const width = Number.parseInt(searchParams.get("width") ?? "", 10);- const height = Number.parseInt(searchParams.get("height") ?? "", 10);- if (- Number.isFinite(width) === false ||- Number.isFinite(height) === false ||- format === undefined- ) {- return;- }- return { width, height, format };-};--const reserveAssetUpload = async ({- context,- name,- projectId,- type,-}: {- context: Awaited<ReturnType<typeof createContext>>;- name: string;- projectId: string;- type: Asset["type"];-}): Promise<UploadErrorCleanup> => {- const existingFile = await context.postgrest.client- .from("File")- .select("*")- .eq("name", name)- .maybeSingle();- if (existingFile.error) {- throw existingFile.error;- }-- const fileRow = {- name,- status: "UPLOADING" as const,- format: type,- size: 0,- uploaderProjectId: projectId,- isDeleted: false,- createdAt: new Date().toISOString(),- };- const onUploadError = createUploadErrorCleanup(existingFile.data, name);-- const upsertFile = await context.postgrest.client- .from("File")- .upsert(fileRow, { onConflict: "name" });- if (upsertFile.error) {- throw upsertFile.error;- }-- return onUploadError;-};--const createUploadErrorCleanup =- (previousFile: FileRow | null, name: string): UploadErrorCleanup =>- async (_name, context) => {- if (previousFile) {- const restoreFile = await context.postgrest.client- .from("File")- .update(previousFile)- .eq("name", name);- if (restoreFile.error) {- throw restoreFile.error;- }- return;- }-- const deleteFile = await context.postgrest.client- .from("File")- .delete()- .eq("name", name);- if (deleteFile.error) {- throw deleteFile.error;- }- };+import { assertApiProjectPermit } from "~/services/api-permits.server";+import {+ getAssetInfoFallback,+ getBrowserAssetFormat,+ getBrowserUploadBody,+ parseAssetType,+ type AssetInfoFallback,+} from "~/services/asset-upload.server";const createAssetUploadResponse = async ({body,@@ -145,82 +47,25 @@ const createAssetUploadResponse = async ({});};-const getBrowserUploadBody = async (- request: Request,- contentType: string | null-) => {- let body = request.body;- if (body === null) {- throw new Error("Asset body is empty");- }-- // Check if this is a request to download from URL (has url field in JSON body)- // vs uploading a JSON file directly (JSON file content in body)- if (contentType?.includes("application/json")) {- const jsonBody = await request.json();- const urlParse = urlBody.safeParse(jsonBody);-- // Only fetch from URL if the body has a valid url field- if (urlParse.success) {- const { url } = urlParse.data;-- const imageRequest = await fetch(url, {- method: "GET",- headers: {- Accept: RESIZABLE_IMAGE_MIME_TYPES.join(","),- },- });-- if (false === imageRequest.ok) {- const error = await imageRequest.text();- const errors = `An error occurred while fetching the image at ${url}: ${error.slice(0, 500)}`;- throw new Error(errors);- }-- if (imageRequest.body === null) {- throw new Error(- `An error occurred while fetching the image at ${url}: Image body is null`- );- }-- body = imageRequest.body;- } else {- // This is a JSON file being uploaded, use the JSON content as body- body = new Blob([JSON.stringify(jsonBody)], {- type: "application/json",- }).stream();+const createApiUploadErrorCleanup =+ (assetId: string, projectId: string): UploadErrorCleanup =>+ async (name, context) => {+ const deleteAsset = await context.postgrest.client+ .from("Asset")+ .delete()+ .eq("id", assetId)+ .eq("projectId", projectId);+ if (deleteAsset.error) {+ throw deleteAsset.error;}- }-- return body;-};--const getBrowserAssetFormat = ({- contentType,- name,-}: {- contentType: string | null;- name: string;-}) => {- // Get file extension from filename- const fileExtension = name.split(".").pop()?.toLowerCase();-- // Use the file extension to determine the correct MIME type- // This handles cases where browsers send legacy MIME types (e.g., application/font-woff instead of font/woff)- const correctMimeType =- ALLOWED_FILE_TYPES[fileExtension as keyof typeof ALLOWED_FILE_TYPES] ??- contentType?.split(";")[0];-- const contentTypeArr = correctMimeType?.split("/") ?? [];-- // Validate MIME type against allowed categories- const mimeCategory = contentTypeArr[0];- if (mimeCategory && correctMimeType && !isAllowedMimeCategory(mimeCategory)) {- throw new Error(`MIME type "${mimeCategory}/*" is not allowed`);- }-- return contentTypeArr[0] === "video" ? contentTypeArr[1] : undefined;-};+ const deleteFile = await context.postgrest.client+ .from("File")+ .delete()+ .eq("name", name);+ if (deleteFile.error) {+ throw deleteFile.error;+ }+ };export const action = async (props: ActionFunctionArgs) => {preventCrossOriginCookie(props.request);@@ -257,6 +102,10 @@ export const action = async (props: ActionFunctionArgs) => {if (projectId === null) {throw new Error("Project id is required");}+ const assetId = url.searchParams.get("assetId");+ if (assetId === null) {+ throw new Error("Asset id is required");+ }if (assetType === undefined) {throw new Error("Asset type is invalid");}@@ -269,19 +118,22 @@ export const action = async (props: ActionFunctionArgs) => {});const context = await createContext(request);- await assertProjectBuildPermit({ ctx: context, projectId });- const onUploadError = await reserveAssetUpload({- context,- name: params.name,- projectId,- type: assetType,- });+ await assertApiProjectPermit(context, projectId, "build");+ const uploadName = await createUploadName(+ {+ assetId,+ projectId,+ type: assetType,+ filename: params.name,+ },+ context+ );return await createAssetUploadResponse({body: request.body,context,- name: params.name,+ name: uploadName,assetInfoFallback,- onUploadError,+ onUploadError: createApiUploadErrorCleanup(assetId, projectId),});}@@ -308,10 +160,3 @@ export const action = async (props: ActionFunctionArgs) => {);}};--export const __testing__ = {- getAssetInfoFallback,- getBrowserAssetFormat,- getBrowserUploadBody,- parseAssetType,-};diff --git a/apps/builder/app/services/api-build.server.test.ts b/apps/builder/app/services/api-build.server.test.tsnew file mode 100644index 0000000000..c91df632a0--- /dev/null+++ b/apps/builder/app/services/api-build.server.test.ts@@ -0,0 +1,405 @@+import { afterEach, describe, expect, test, vi } from "vitest";+import { createDefaultPages } from "@webstudio-is/project-build";+import type { CompactBuild } from "@webstudio-is/project-build";+import {+ createTestServer,+ db,+ json,+ testContext,+} from "@webstudio-is/postgrest/testing";+import { buildPatchTransaction } from "@webstudio-is/protocol";+import type { AppContext } from "@webstudio-is/trpc-interface/index.server";+import { authorizeProject } from "@webstudio-is/trpc-interface/index.server";+import { db as authDb } from "@webstudio-is/authorization-token/index.server";+import * as projectApi from "@webstudio-is/project/index.server";+import * as projectBuild from "@webstudio-is/project-build/index.server";+import type { z } from "zod";+import {+ commitBuildPatch,+ commitBuildTransactions,+ createBuildSnapshot,+ loadBuildByProjectVersion,+ loadReadableDevBuild,+ serializeProjectSummary,+} from "./api-build.server";++const server = createTestServer();++type ProjectSummaryInput = Parameters<typeof serializeProjectSummary>[0];+type SnapshotBuildInput = Parameters<typeof createBuildSnapshot>[0]["build"];++const createContext = (+ allowAdditionalPermissions: boolean,+ authorization: AppContext["authorization"] = {+ type: "token",+ authToken: "secret-token",+ ownerId: "user-1",+ }+) =>+ ({+ authorization,+ planFeatures: {+ allowAdditionalPermissions,+ },+ }) as AppContext;++const createToken = (+ overrides: Partial<Awaited<ReturnType<typeof authDb.getTokenInfo>>> = {}+) =>+ ({+ token: "token-1",+ projectId: "project-1",+ name: "Token",+ relation: "builders",+ createdAt: "2024-01-01T00:00:00.000Z",+ canClone: true,+ canCopy: true,+ canPublish: false,+ canUseApi: true,+ ...overrides,+ }) as Awaited<ReturnType<typeof authDb.getTokenInfo>>;++const createBuildRow = (overrides: Record<string, unknown> = {}) => ({+ id: "build-1",+ projectId: "project-1",+ version: 3,+ createdAt: "2024-01-01T00:00:00.000Z",+ updatedAt: "2024-01-01T00:00:00.000Z",+ pages: JSON.stringify({+ meta: {},+ homePage: {+ id: "page-1",+ name: "Home",+ path: "",+ title: "Home",+ meta: {},+ rootInstanceId: "root-1",+ },+ pages: [],+ }),+ breakpoints: JSON.stringify([]),+ styles: JSON.stringify([]),+ styleSources: JSON.stringify([]),+ styleSourceSelections: JSON.stringify([]),+ props: JSON.stringify([]),+ dataSources: JSON.stringify([]),+ resources: JSON.stringify([]),+ instances: JSON.stringify([+ { id: "root-1", type: "instance", component: "Body", children: [] },+ ]),+ deployment: null,+ marketplaceProduct: JSON.stringify({}),+ ...overrides,+});++afterEach(() => {+ vi.restoreAllMocks();+});++describe("api build loading", () => {+ test("loads a specific project build version", async () => {+ server.use(db.get("Build", () => json([createBuildRow()])));++ await expect(+ loadBuildByProjectVersion(testContext as AppContext, "project-1", 3)+ ).resolves.toMatchObject({+ id: "build-1",+ projectId: "project-1",+ version: 3,+ });+ });++ test("throws not found when project build version is missing", async () => {+ server.use(db.get("Build", () => json([])));++ await expect(+ loadBuildByProjectVersion(testContext as AppContext, "project-1", 99)+ ).rejects.toMatchObject({+ code: "NOT_FOUND",+ message: "Build version not found for project",+ });+ });++ test("checks view permission before loading readable dev build", async () => {+ const ctx = createContext(true);+ const build = { id: "build-1" } as Awaited<+ ReturnType<typeof projectBuild.loadDevBuildByProjectId>+ >;+ vi.spyOn(authDb, "getTokenInfo").mockResolvedValue(createToken());+ vi.spyOn(authorizeProject, "hasProjectPermit").mockResolvedValue(true);+ const loadDevBuild = vi+ .spyOn(projectBuild, "loadDevBuildByProjectId")+ .mockResolvedValue(build);++ await expect(loadReadableDevBuild(ctx, "project-1")).resolves.toBe(build);++ expect(loadDevBuild).toHaveBeenCalledWith(ctx, "project-1");+ });+});++describe("api build patch commits", () => {+ const build = {+ id: "build",+ projectId: "project",+ version: 1,+ } as CompactBuild;+ const transaction: z.infer<typeof buildPatchTransaction> = {+ id: "transaction",+ payload: [+ {+ namespace: "pages",+ patches: [{ op: "replace", path: ["meta", "siteName"], value: "Site" }],+ },+ ],+ };++ test("commits transactions and semantic payloads", async () => {+ const ctx = createContext(true);+ const patchBuild = vi+ .spyOn(projectApi, "patchBuild")+ .mockResolvedValue({ status: "ok", version: 2 });++ await expect(+ commitBuildTransactions({+ ctx,+ projectId: "project",+ buildId: "build",+ clientVersion: 1,+ transactions: [transaction],+ })+ ).resolves.toEqual({ version: 2 });+ await expect(+ commitBuildPatch({+ build,+ ctx,+ projectId: "project",+ payload: transaction.payload,+ })+ ).resolves.toEqual({ version: 2 });++ expect(patchBuild).toHaveBeenNthCalledWith(+ 1,+ {+ buildId: "build",+ projectId: "project",+ clientVersion: 1,+ transactions: [transaction],+ },+ ctx+ );+ expect(patchBuild).toHaveBeenNthCalledWith(+ 2,+ {+ buildId: "build",+ projectId: "project",+ clientVersion: 1,+ transactions: [+ {+ id: expect.any(String),+ payload: transaction.payload,+ },+ ],+ },+ ctx+ );+ });++ test("maps patch conflicts and errors to TRPC errors", async () => {+ const ctx = createContext(true);+ const patchBuild = vi.spyOn(projectApi, "patchBuild");++ patchBuild.mockResolvedValueOnce({+ status: "version_mismatched",+ errors: "Version changed",+ });+ await expect(+ commitBuildTransactions({+ ctx,+ projectId: "project",+ buildId: "build",+ clientVersion: 1,+ transactions: [transaction],+ })+ ).rejects.toMatchObject({+ code: "CONFLICT",+ message: "Version changed",+ });++ patchBuild.mockResolvedValueOnce({+ status: "error",+ errors: "Invalid patch",+ });+ await expect(+ commitBuildTransactions({+ ctx,+ projectId: "project",+ buildId: "build",+ clientVersion: 1,+ transactions: [transaction],+ })+ ).rejects.toMatchObject({+ code: "BAD_REQUEST",+ message: "Invalid patch",+ });+ });+});++describe("api build snapshot", () => {+ test("returns only requested build namespaces", () => {+ const tokenStyleSource = {+ type: "token" as const,+ id: "token-1",+ name: "Primary",+ };+ const localStyleSource = { type: "local" as const, id: "local-1" };+ const build = {+ id: "build-1",+ projectId: "project-1",+ version: 7,+ pages: createDefaultPages({ rootInstanceId: "root-1" }),+ instances: [{ type: "instance", id: "root-1", component: "Body" }],+ props: [],+ styles: [],+ styleSources: [tokenStyleSource, localStyleSource],+ styleSourceSelections: [],+ resources: [],+ dataSources: [],+ breakpoints: [],+ } as unknown as SnapshotBuildInput;++ expect(+ createBuildSnapshot({+ build,+ include: new Set(["designTokens", "instances"]),+ projectId: "project-1",+ })+ ).toEqual({+ projectId: "project-1",+ buildId: "build-1",+ version: 7,+ designTokens: [tokenStyleSource],+ instances: [{ type: "instance", id: "root-1", component: "Body" }],+ });+ });++ test("returns page folders and data namespaces when requested", () => {+ const pages = createDefaultPages({ rootInstanceId: "root-1" });+ pages.meta = { siteName: "Acme" };+ pages.compiler = { atomicStyles: true };+ pages.redirects = [{ old: "/old", new: "/new", status: "301" }];+ const build = {+ id: "build-1",+ projectId: "project-1",+ version: 7,+ pages,+ instances: [],+ props: [],+ styles: [],+ styleSources: [],+ styleSourceSelections: [],+ resources: [{ id: "resource-1" }],+ dataSources: [{ id: "variable-1" }],+ breakpoints: [{ id: "breakpoint-1" }],+ marketplaceProduct: { categories: ["template"] },+ } as unknown as SnapshotBuildInput;++ expect(+ createBuildSnapshot({+ build,+ include: new Set([+ "pages",+ "folders",+ "resources",+ "variables",+ "breakpoints",+ "marketplaceProduct",+ ]),+ projectId: "project-1",+ })+ ).toEqual(+ expect.objectContaining({+ projectId: "project-1",+ buildId: "build-1",+ version: 7,+ homePageId: build.pages.homePageId,+ rootFolderId: build.pages.rootFolderId,+ meta: { siteName: "Acme" },+ compiler: { atomicStyles: true },+ redirects: [{ old: "/old", new: "/new", status: "301" }],+ resources: [{ id: "resource-1" }],+ variables: [{ id: "variable-1" }],+ breakpoints: [{ id: "breakpoint-1" }],+ marketplaceProduct: { categories: ["template"] },+ })+ );+ });+});++describe("api project serialization", () => {+ test("uses latest virtual build time as project updated time", () => {+ const project = {+ id: "project-1",+ title: "Project",+ domain: "example.com",+ createdAt: "2024-01-01T00:00:00.000Z",+ latestBuildVirtual: {+ createdAt: "2024-01-03T00:00:00.000Z",+ },+ latestStaticBuild: {+ updatedAt: "2024-01-02T00:00:00.000Z",+ },+ } as unknown as ProjectSummaryInput;++ expect(serializeProjectSummary(project)).toEqual({+ id: "project-1",+ name: "Project",+ domain: "example.com",+ createdAt: "2024-01-01T00:00:00.000Z",+ updatedAt: "2024-01-03T00:00:00.000Z",+ });+ });++ test("falls back to latest static build and then project creation time", () => {+ expect(+ serializeProjectSummary({+ id: "project-1",+ title: "Project",+ domain: null,+ createdAt: "2024-01-01T00:00:00.000Z",+ latestBuildVirtual: null,+ latestStaticBuild: {+ updatedAt: "2024-01-02T00:00:00.000Z",+ },+ } as unknown as ProjectSummaryInput)+ ).toEqual({+ id: "project-1",+ name: "Project",+ domain: undefined,+ createdAt: "2024-01-01T00:00:00.000Z",+ updatedAt: "2024-01-02T00:00:00.000Z",+ });++ expect(+ serializeProjectSummary({+ id: "project-1",+ title: "Project",+ domain: null,+ createdAt: "2024-01-01T00:00:00.000Z",+ latestBuildVirtual: null,+ latestStaticBuild: null,+ } as unknown as ProjectSummaryInput)+ ).toEqual({+ id: "project-1",+ name: "Project",+ domain: undefined,+ createdAt: "2024-01-01T00:00:00.000Z",+ updatedAt: "2024-01-01T00:00:00.000Z",+ });+ });++ test("throws not found when project is missing", () => {+ expect(() =>+ serializeProjectSummary(null as unknown as ProjectSummaryInput)+ ).toThrow("Project not found");+ });+});diff --git a/apps/builder/app/services/api-build.server.ts b/apps/builder/app/services/api-build.server.tsnew file mode 100644index 0000000000..28384451a5--- /dev/null+++ b/apps/builder/app/services/api-build.server.ts@@ -0,0 +1,199 @@+import { nanoid } from "nanoid";+import { z } from "zod";+import { loadById, patchBuild } from "@webstudio-is/project/index.server";+import type { CompactBuild } from "@webstudio-is/project-build";+import {+ loadBuildById,+ loadDevBuildByProjectId,+} from "@webstudio-is/project-build/index.server";+import { buildPatchTransaction } from "@webstudio-is/protocol";+import type { AppContext } from "@webstudio-is/trpc-interface/index.server";+import { serializePages } from "@webstudio-is/project-migrations/pages";+import { assertApiProjectPermit } from "./api-permits.server";+import { throwApiError } from "./api-errors.server";++export const loadBuildByProjectVersion = async (+ ctx: AppContext,+ projectId: string,+ version: number+) => {+ const build = await ctx.postgrest.client+ .from("Build")+ .select("id")+ .eq("projectId", projectId)+ .eq("version", version)+ .is("deployment", null)+ .order("createdAt", { ascending: false })+ .limit(1);++ if (build.error) {+ throw build.error;+ }+ const buildId = build.data.at(0)?.id;+ if (buildId === undefined) {+ return throwApiError("NOT_FOUND", "Build version not found for project");+ }++ return await loadBuildById(ctx, buildId);+};++export const loadReadableDevBuild = async (+ ctx: AppContext,+ projectId: string+) => {+ await assertApiProjectPermit(ctx, projectId, "view");+ return await loadDevBuildByProjectId(ctx, projectId);+};++const buildInclude = z.enum([+ "pages",+ "folders",+ "instances",+ "props",+ "styles",+ "styleSources",+ "styleSourceSelections",+ "designTokens",+ "assets",+ "resources",+ "variables",+ "breakpoints",+ "marketplaceProduct",+]);++export type BuildInclude = z.infer<typeof buildInclude>;++export const buildGetInput = z.object({+ projectId: z.string(),+ include: z.array(buildInclude).optional(),+ version: z.number().int().optional(),+});++export const buildPatchInput = z.object({+ projectId: z.string(),+ baseVersion: z.number().int(),+ transactions: z.array(buildPatchTransaction).min(1),+});++export const createBuildSnapshot = ({+ build,+ include,+ projectId,+}: {+ build: Awaited<ReturnType<typeof loadDevBuildByProjectId>>;+ include: Set<BuildInclude>;+ projectId: string;+}) => {+ const snapshot: Record<string, unknown> = {+ projectId,+ buildId: build.id,+ version: build.version,+ };+ const add = (name: BuildInclude, value: unknown) => {+ if (include.has(name)) {+ snapshot[name] = value;+ }+ };++ if (include.has("pages") || include.has("folders")) {+ const pages = serializePages(build.pages);+ snapshot.homePageId = pages.homePageId;+ snapshot.rootFolderId = pages.rootFolderId;+ if (include.has("pages")) {+ snapshot.meta = pages.meta;+ snapshot.compiler = pages.compiler;+ snapshot.redirects = pages.redirects;+ }+ add("pages", pages.pages);+ add("folders", pages.folders);+ }+ add("instances", build.instances);+ add("props", build.props);+ add("styles", build.styles);+ add("styleSources", build.styleSources);+ add("styleSourceSelections", build.styleSourceSelections);+ if (include.has("designTokens")) {+ snapshot.designTokens = build.styleSources.filter(+ (styleSource) => styleSource.type === "token"+ );+ }+ add("resources", build.resources);+ add("variables", build.dataSources);+ add("breakpoints", build.breakpoints);+ add("marketplaceProduct", build.marketplaceProduct);++ return snapshot;+};++export const serializeProjectSummary = (+ project: Awaited<ReturnType<typeof loadById>>+) => {+ if (project === null) {+ throwApiError("NOT_FOUND", "Project not found");+ }++ return {+ id: project.id,+ name: project.title,+ domain: project.domain ?? undefined,+ createdAt: project.createdAt,+ updatedAt:+ project.latestBuildVirtual?.createdAt ??+ project.latestStaticBuild?.updatedAt ??+ project.createdAt,+ };+};++export const commitBuildTransactions = async ({+ ctx,+ projectId,+ buildId,+ clientVersion,+ transactions,+}: {+ ctx: AppContext;+ projectId: string;+ buildId: string;+ clientVersion: number;+ transactions: z.infer<typeof buildPatchTransaction>[];+}) => {+ const result = await patchBuild(+ {+ buildId,+ projectId,+ clientVersion,+ transactions,+ },+ ctx+ );+ if (result.status === "version_mismatched") {+ throwApiError("CONFLICT", result.errors);+ }+ if (result.status === "error") {+ throwApiError("BAD_REQUEST", result.errors);+ }+ if (result.status !== "ok") {+ return throwApiError("BAD_REQUEST", "Unexpected patch result");+ }+ return { version: result.version };+};++export const commitBuildPatch = async ({+ build,+ ctx,+ projectId,+ payload,+}: {+ build: CompactBuild;+ ctx: AppContext;+ projectId: string;+ payload: z.infer<typeof buildPatchTransaction>["payload"];+}) => {+ return commitBuildTransactions({+ ctx,+ projectId,+ buildId: build.id,+ clientVersion: build.version,+ transactions: [{ id: nanoid(), payload }],+ });+};diff --git a/apps/builder/app/services/api-errors.server.test.ts b/apps/builder/app/services/api-errors.server.test.tsnew file mode 100644index 0000000000..f46507a7a7--- /dev/null+++ b/apps/builder/app/services/api-errors.server.test.ts@@ -0,0 +1,15 @@+import { describe, expect, test } from "vitest";+import { TRPCError } from "@trpc/server";+import { throwApiError } from "./api-errors.server";++describe("api errors", () => {+ test("throws public api trpc errors", () => {+ expect.assertions(2);+ try {+ throwApiError("NOT_FOUND", "Missing");+ } catch (error) {+ expect(error).toBeInstanceOf(TRPCError);+ expect(error).toMatchObject({ code: "NOT_FOUND", message: "Missing" });+ }+ });+});diff --git a/apps/builder/app/services/api-errors.server.ts b/apps/builder/app/services/api-errors.server.tsnew file mode 100644index 0000000000..9964b77459--- /dev/null+++ b/apps/builder/app/services/api-errors.server.ts@@ -0,0 +1,8 @@+import { TRPCError } from "@trpc/server";++export const throwApiError = (+ code: "BAD_REQUEST" | "NOT_FOUND" | "CONFLICT",+ message: string+): never => {+ throw new TRPCError({ code, message });+};diff --git a/apps/builder/app/services/api-permits.server.test.ts b/apps/builder/app/services/api-permits.server.test.tsnew file mode 100644index 0000000000..963587d755--- /dev/null+++ b/apps/builder/app/services/api-permits.server.test.ts@@ -0,0 +1,41 @@+import { expect, test } from "vitest";+import { TRPCError } from "@trpc/server";+import { getTokenPermits, loadApiToken } from "./api-permits.server";++const createContext = ({+ allowAdditionalPermissions = true,+}: {+ allowAdditionalPermissions?: boolean;+}) =>+ ({+ authorization: { type: "user" },+ planFeatures: { allowAdditionalPermissions },+ }) as Parameters<typeof loadApiToken>[0] & {+ planFeatures: { allowAdditionalPermissions: boolean };+ };++test("loadApiToken rejects non-token authorization before database lookup", async () => {+ await expect(loadApiToken(createContext({}))).rejects.toBeInstanceOf(+ TRPCError+ );+ await expect(loadApiToken(createContext({}))).rejects.toMatchObject({+ code: "FORBIDDEN",+ message: "Builder API requires an API token",+ });+});++test("getTokenPermits includes api only when token and plan allow it", () => {+ const token = {+ relation: "viewers",+ canUseApi: true,+ } as Parameters<typeof getTokenPermits>[0];+ const ctx = createContext({});++ expect(getTokenPermits(token, ctx)).toContain("api");+ expect(getTokenPermits({ ...token, canUseApi: false }, ctx)).not.toContain(+ "api"+ );+ expect(+ getTokenPermits(token, createContext({ allowAdditionalPermissions: false }))+ ).not.toContain("api");+});diff --git a/apps/builder/app/services/api-permits.server.ts b/apps/builder/app/services/api-permits.server.tsnew file mode 100644index 0000000000..3de4b246e1--- /dev/null+++ b/apps/builder/app/services/api-permits.server.ts@@ -0,0 +1,79 @@+import { TRPCError } from "@trpc/server";+import {+ authorizeProject,+ type AppContext,+ type AuthPermit,+} from "@webstudio-is/trpc-interface/index.server";+import { db as authDb } from "@webstudio-is/authorization-token/index.server";++type ApiPermit = AuthPermit | "api";++type ApiToken = Awaited<ReturnType<typeof authDb.getTokenInfo>>;++export const loadApiToken = async (ctx: AppContext) => {+ if (ctx.authorization.type !== "token") {+ throw new TRPCError({+ code: "FORBIDDEN",+ message: "Builder API requires an API token",+ });+ }++ return await authDb.getTokenInfo(ctx.authorization.authToken, ctx);+};++export const getTokenPermits = (token: ApiToken, ctx: AppContext) => {+ const permits: ApiPermit[] = [...authDb.getTokenProjectPermits(token)];+ if (+ token.canUseApi === true &&+ ctx.planFeatures.allowAdditionalPermissions === true+ ) {+ permits.push("api");+ }+ return permits;+};++export const assertApiTokenPermit = async (ctx: AppContext) => {+ const token = await loadApiToken(ctx);+ const permits = getTokenPermits(token, ctx);+ if (permits.includes("api") === false) {+ throw new TRPCError({+ code: "FORBIDDEN",+ message: "Authorization token cannot use Builder API",+ });+ }+ return { token, permits };+};++export const assertApiProjectPermit = async (+ ctx: AppContext,+ projectId: string,+ permit: AuthPermit+) => {+ const { token, permits } = await assertApiTokenPermit(ctx);+ if (token.projectId !== projectId) {+ throw new TRPCError({+ code: "FORBIDDEN",+ message: "Authorization token is not valid for project",+ });+ }++ if (permits.includes(permit) === false) {+ throw new TRPCError({+ code: "FORBIDDEN",+ message: `Authorization token does not have ${permit} permission`,+ });+ }++ const canUseProject = await authorizeProject.hasProjectPermit(+ { projectId, permit },+ ctx+ );+ if (canUseProject === false) {+ throw new TRPCError({+ code: "FORBIDDEN",+ message: "You don't have access to this project",+ });+ }++ return { token, permits };+};diff --git a/apps/builder/app/services/api-router.server.test.ts b/apps/builder/app/services/api-router.server.test.tsnew file mode 100644index 0000000000..e927e8c06a--- /dev/null+++ b/apps/builder/app/services/api-router.server.test.ts@@ -0,0 +1,856 @@+import { access, readFile } from "node:fs/promises";+import { join } from "node:path";+import { afterEach, describe, expect, test, vi } from "vitest";+import { z } from "zod";+import { createDefaultPages } from "@webstudio-is/project-build";+import type { CompactBuild } from "@webstudio-is/project-build";+import * as projectBuild from "@webstudio-is/project-build/index.server";+import * as projectApi from "@webstudio-is/project/index.server";+import {+ buildPatchTransaction,+ publicApiOperations,+} from "@webstudio-is/protocol";+import {+ authorizeProject,+ type AppContext,+} from "@webstudio-is/trpc-interface/index.server";+import { db as authDb } from "@webstudio-is/authorization-token/index.server";+import { blockComponent } from "@webstudio-is/sdk";+import { apiRouter, __testing__ } from "./api-router.server";+import {+ assertApiProjectPermit,+ assertApiTokenPermit,+ getTokenPermits,+} from "./api-permits.server";++const servicesDir = new URL(".", import.meta.url);++const { assertContentOrBuildPayload, assertApiPublishDomains } = __testing__;++const createContext = (+ allowAdditionalPermissions: boolean,+ authorization: AppContext["authorization"] = {+ type: "token",+ authToken: "secret-token",+ ownerId: "user-1",+ }+) =>+ ({+ authorization,+ planFeatures: {+ allowAdditionalPermissions,+ },+ }) as AppContext;++const createToken = (+ overrides: Partial<Awaited<ReturnType<typeof authDb.getTokenInfo>>> = {}+) =>+ ({+ token: "token-1",+ projectId: "project-1",+ name: "Token",+ relation: "builders",+ createdAt: "2024-01-01T00:00:00.000Z",+ canClone: true,+ canCopy: true,+ canPublish: false,+ canUseApi: true,+ ...overrides,+ }) as Awaited<ReturnType<typeof authDb.getTokenInfo>>;++describe("api router build operation adapters", () => {+ test("public operation catalog paths exist on the api router", () => {+ const procedures = (+ apiRouter as unknown as {+ _def: { procedures: Record<string, unknown> };+ }+ )._def.procedures;++ for (const operation of publicApiOperations) {+ if (operation.path === undefined) {+ continue;+ }+ const procedure = procedures[operation.path.replace(/^api\./, "")] as+ | { _def?: Partial<Record<typeof operation.method, boolean>> }+ | undefined;+ expect(procedure).toBeDefined();+ expect(procedure?._def?.[operation.method]).toBe(true);+ }+ });++ test("does not keep an api-only build operations service", async () => {+ await expect(+ access(join(servicesDir.pathname, "build-operations.server.ts"))+ ).rejects.toThrow();+ });++ test("api router tests do not mock modules", async () => {+ const content = await readFile(new URL(import.meta.url), "utf-8");+ const forbidden = [+ new RegExp("\\bvi\\.mock\\("),+ new RegExp("\\bjest\\.mock\\("),+ new RegExp("unstable_" + "mock" + "Module"),+ new RegExp("mock" + "Module"),+ ];+ for (const pattern of forbidden) {+ expect(content).not.toMatch(pattern);+ }+ });++ test("api router does not assemble semantic patches inline", async () => {+ const content = await readFile(+ new URL("api-router.server.ts", servicesDir),+ "utf-8"+ );+ expect(content).not.toMatch(/\bnamespace:/);+ expect(content).not.toMatch(/\bpatches:/);+ expect(content).not.toMatch(/\bop: ["'](add|remove|replace)["']/);+ });+});++afterEach(() => {+ vi.restoreAllMocks();+});++describe("api router permits", () => {+ test("adds api permit only when token and plan both allow it", () => {+ const token = createToken();++ expect(getTokenPermits(token, createContext(true))).toEqual([+ "view",+ "edit",+ "build",+ "api",+ ]);+ expect(getTokenPermits(token, createContext(false))).toEqual([+ "view",+ "edit",+ "build",+ ]);+ expect(+ getTokenPermits(+ {+ ...token,+ canUseApi: false,+ },+ createContext(true)+ )+ ).toEqual(["view", "edit", "build"]);+ });++ test("maps token relation to project permits", () => {+ expect(+ getTokenPermits(createToken({ relation: "viewers" }), createContext(true))+ ).toEqual(["view", "api"]);+ expect(+ getTokenPermits(createToken({ relation: "editors" }), createContext(true))+ ).toEqual(["view", "edit", "api"]);+ expect(+ getTokenPermits(+ createToken({ relation: "builders" }),+ createContext(true)+ )+ ).toEqual(["view", "edit", "build", "api"]);+ expect(+ getTokenPermits(+ createToken({ relation: "administrators" }),+ createContext(true)+ )+ ).toEqual(["view", "edit", "build", "admin", "api"]);+ });++ test("requires token auth for project-scoped api procedures", async () => {+ await expect(+ assertApiProjectPermit(+ createContext(true, {+ type: "user",+ userId: "user-1",+ sessionCreatedAt: 0,+ isLoggedInToBuilder: async () => true,+ }),+ "project-1",+ "view"+ )+ ).rejects.toMatchObject({+ code: "FORBIDDEN",+ message: "Builder API requires an API token",+ });+ });++ test("rejects tokens from another project", async () => {+ vi.spyOn(authDb, "getTokenInfo").mockResolvedValue(+ createToken({ projectId: "project-2" })+ );++ await expect(+ assertApiProjectPermit(createContext(true), "project-1", "view")+ ).rejects.toThrow("Authorization token is not valid for project");+ });++ test("rejects tokens without api permission", async () => {+ vi.spyOn(authDb, "getTokenInfo").mockResolvedValue(+ createToken({ canUseApi: false })+ );++ await expect(assertApiTokenPermit(createContext(true))).rejects.toThrow(+ "Authorization token cannot use Builder API"+ );+ await expect(+ assertApiProjectPermit(createContext(true), "project-1", "view")+ ).rejects.toThrow("Authorization token cannot use Builder API");+ });++ test("allows token introspection without api permission", async () => {+ const token = createToken({ canUseApi: false, relation: "editors" });+ vi.spyOn(authDb, "getTokenInfo").mockResolvedValue(token);+ vi.spyOn(authorizeProject, "hasProjectPermit").mockResolvedValue(true);++ const caller = apiRouter.createCaller(createContext(true));++ await expect(caller.auth.me()).resolves.toEqual({+ actor: { type: "token", tokenId: token.token },+ projectId: token.projectId,+ relation: "editors",+ permits: ["view", "edit"],+ });+ await expect(+ caller.projects.permissions({ projectId: token.projectId })+ ).resolves.toEqual({+ relation: "editors",+ permits: ["view", "edit"],+ canView: true,+ canEdit: true,+ canBuild: false,+ canAdmin: false,+ canOwn: false,+ canUseApi: false,+ canPublish: false,+ canPublishProjectDomain: false,+ canPublishCustomDomains: false,+ });+ });++ test("returns publish capabilities from token permissions", async () => {+ vi.spyOn(authorizeProject, "hasProjectPermit").mockResolvedValue(true);+ const caller = apiRouter.createCaller(createContext(true));++ vi.spyOn(authDb, "getTokenInfo").mockResolvedValue(+ createToken({ relation: "editors", canPublish: true })+ );+ await expect(+ caller.projects.permissions({ projectId: "project-1" })+ ).resolves.toMatchObject({+ relation: "editors",+ canPublish: true,+ canPublishProjectDomain: true,+ canPublishCustomDomains: true,+ });++ vi.spyOn(authDb, "getTokenInfo").mockResolvedValue(+ createToken({ relation: "builders", canPublish: false })+ );+ await expect(+ caller.projects.permissions({ projectId: "project-1" })+ ).resolves.toMatchObject({+ relation: "builders",+ canPublish: false,+ canPublishProjectDomain: true,+ canPublishCustomDomains: false,+ });++ vi.spyOn(authDb, "getTokenInfo").mockResolvedValue(+ createToken({ relation: "administrators", canPublish: true })+ );+ await expect(+ caller.projects.permissions({ projectId: "project-1" })+ ).resolves.toMatchObject({+ relation: "administrators",+ canPublish: true,+ canPublishProjectDomain: true,+ canPublishCustomDomains: true,+ });+ });++ test("rejects tokens when current plan does not allow api permission", async () => {+ vi.spyOn(authDb, "getTokenInfo").mockResolvedValue(createToken());++ await expect(+ assertApiProjectPermit(createContext(false), "project-1", "view")+ ).rejects.toThrow("Authorization token cannot use Builder API");+ });++ test("rejects tokens without the required relation permit", async () => {+ vi.spyOn(authDb, "getTokenInfo").mockResolvedValue(+ createToken({ relation: "viewers" })+ );++ await expect(+ assertApiProjectPermit(createContext(true), "project-1", "edit")+ ).rejects.toThrow("Authorization token does not have edit permission");+ });++ test("requires build permission before semantic build mutation handlers", async () => {+ vi.spyOn(authDb, "getTokenInfo").mockResolvedValue(+ createToken({ relation: "viewers" })+ );++ const caller = apiRouter.createCaller(createContext(true));++ await expect(+ caller.pages.update({+ projectId: "project-1",+ pageId: "page-id",+ values: {},+ })+ ).rejects.toThrow("Authorization token does not have build permission");+ });++ test("checks project authorization after token permission checks", async () => {+ const hasProjectPermit = vi+ .spyOn(authorizeProject, "hasProjectPermit")+ .mockResolvedValue(false);+ vi.spyOn(authDb, "getTokenInfo").mockResolvedValue(createToken());++ await expect(+ assertApiProjectPermit(createContext(true), "project-1", "view")+ ).rejects.toThrow("You don't have access to this project");++ expect(hasProjectPermit).toHaveBeenCalledWith(+ { projectId: "project-1", permit: "view" },+ expect.anything()+ );+ });++ test("returns token and effective permits when access is allowed", async () => {+ const token = createToken({ relation: "editors" });+ vi.spyOn(authorizeProject, "hasProjectPermit").mockResolvedValue(true);+ vi.spyOn(authDb, "getTokenInfo").mockResolvedValue(token);++ await expect(+ assertApiProjectPermit(createContext(true), "project-1", "edit")+ ).resolves.toEqual({+ token,+ permits: ["view", "edit", "api"],+ });+ });++ test("requires publish permission for api publish domains", () => {+ const project = { domain: "project.wstd.dev" };++ expect(() =>+ assertApiPublishDomains({+ auth: {+ token: createToken({ relation: "editors", canPublish: false }),+ permits: ["view", "edit", "api"],+ },+ domains: ["project.wstd.dev"],+ project,+ })+ ).toThrow("Authorization token does not have publish permission");++ expect(() =>+ assertApiPublishDomains({+ auth: {+ token: createToken({ relation: "editors", canPublish: true }),+ permits: ["view", "edit", "api"],+ },+ domains: ["custom.example.com"],+ project,+ })+ ).not.toThrow();++ expect(() =>+ assertApiPublishDomains({+ auth: {+ token: createToken({ relation: "builders", canPublish: false }),+ permits: ["view", "edit", "build", "api"],+ },+ domains: ["project.wstd.dev"],+ project,+ })+ ).not.toThrow();++ expect(() =>+ assertApiPublishDomains({+ auth: {+ token: createToken({ relation: "builders", canPublish: false }),+ permits: ["view", "edit", "build", "api"],+ },+ domains: ["custom.example.com"],+ project,+ })+ ).toThrow("Authorization token does not have publish permission");++ expect(() =>+ assertApiPublishDomains({+ auth: {+ token: createToken({+ relation: "administrators",+ canPublish: true,+ }),+ permits: ["view", "edit", "build", "admin", "api"],+ },+ domains: ["custom.example.com"],+ project,+ })+ ).not.toThrow();+ });++ test("allows editor api tokens to commit content-mode payloads only", () => {+ const build = {+ id: "build",+ projectId: "project-1",+ version: 1,+ createdAt: "2024-01-01T00:00:00.000Z",+ updatedAt: "2024-01-01T00:00:00.000Z",+ pages: createDefaultPages({ rootInstanceId: "block" }),+ breakpoints: [],+ styles: [],+ styleSources: [],+ styleSourceSelections: [],+ props: [],+ dataSources: [],+ resources: [],+ instances: [+ {+ type: "instance",+ id: "block",+ component: blockComponent,+ children: [{ type: "id", value: "text-instance" }],+ },+ {+ type: "instance",+ id: "text-instance",+ component: "ws:element",+ tag: "p",+ children: [{ type: "text", value: "Old" }],+ },+ ],+ marketplaceProduct: {},+ } as unknown as CompactBuild;+ const editorAuth = {+ token: createToken({ relation: "editors" }),+ permits: ["view", "edit", "api"],+ } satisfies Awaited<ReturnType<typeof assertApiProjectPermit>>;+ const builderAuth = {+ token: createToken({ relation: "builders" }),+ permits: ["view", "edit", "build", "api"],+ } satisfies Awaited<ReturnType<typeof assertApiProjectPermit>>;+ const contentPayload: z.infer<typeof buildPatchTransaction>["payload"] = [+ {+ namespace: "instances",+ patches: [+ {+ op: "replace",+ path: ["text-instance", "children", 0],+ value: { type: "text", value: "New" },+ },+ ],+ },+ ];+ const designPayload: z.infer<typeof buildPatchTransaction>["payload"] = [+ {+ namespace: "styles",+ patches: [+ {+ op: "add",+ path: ["style"],+ value: {+ breakpointId: "base",+ property: "color",+ styleSourceId: "local",+ value: { type: "keyword", value: "red" },+ },+ },+ ],+ },+ ];++ expect(() =>+ assertContentOrBuildPayload({+ auth: editorAuth,+ build,+ payload: contentPayload,+ })+ ).not.toThrow();+ expect(() =>+ assertContentOrBuildPayload({+ auth: editorAuth,+ build,+ payload: designPayload,+ })+ ).toThrow("content mode");+ expect(() =>+ assertContentOrBuildPayload({+ auth: builderAuth,+ build,+ payload: designPayload,+ })+ ).not.toThrow();+ });++ test("commits content-mode mutations with editor api tokens", async () => {+ const build = {+ id: "build-1",+ projectId: "project-1",+ version: 3,+ pages: createDefaultPages({ rootInstanceId: "block" }),+ breakpoints: [],+ styles: [],+ styleSources: [],+ styleSourceSelections: [],+ props: [],+ dataSources: [],+ resources: [],+ instances: [+ {+ type: "instance",+ id: "block",+ component: blockComponent,+ children: [{ type: "id", value: "text-instance" }],+ },+ {+ type: "instance",+ id: "text-instance",+ component: "ws:element",+ tag: "p",+ children: [{ type: "text", value: "Old" }],+ },+ ],+ marketplaceProduct: {},+ } as unknown as Awaited<+ ReturnType<typeof projectBuild.loadDevBuildByProjectId>+ >;+ vi.spyOn(authDb, "getTokenInfo").mockResolvedValue(+ createToken({ relation: "editors" })+ );+ vi.spyOn(authorizeProject, "hasProjectPermit").mockResolvedValue(true);+ vi.spyOn(projectBuild, "loadDevBuildByProjectId").mockResolvedValue(build);+ const patchBuild = vi+ .spyOn(projectApi, "patchBuild")+ .mockResolvedValue({ status: "ok", version: 4 });++ const caller = apiRouter.createCaller(createContext(true));++ await expect(+ caller.instances.updateText({+ projectId: "project-1",+ instanceId: "text-instance",+ childIndex: 0,+ text: "New",+ mode: "text",+ })+ ).resolves.toMatchObject({+ version: 4,+ instanceId: "text-instance",+ childIndex: 0,+ mode: "text",+ });++ expect(patchBuild).toHaveBeenCalledWith(+ expect.objectContaining({+ buildId: "build-1",+ projectId: "project-1",+ clientVersion: 3,+ }),+ expect.anything()+ );+ });++ test("does not commit empty runtime mutation payloads", async () => {+ const build = {+ id: "build-1",+ projectId: "project-1",+ version: 7,+ pages: createDefaultPages({ rootInstanceId: "root" }),+ breakpoints: [],+ styles: [],+ styleSources: [],+ styleSourceSelections: [],+ props: [],+ dataSources: [],+ resources: [],+ instances: [+ {+ type: "instance",+ id: "root",+ component: blockComponent,+ children: [],+ },+ ],+ marketplaceProduct: {},+ } as unknown as Awaited<+ ReturnType<typeof projectBuild.loadDevBuildByProjectId>+ >;+ vi.spyOn(authDb, "getTokenInfo").mockResolvedValue(createToken());+ vi.spyOn(authorizeProject, "hasProjectPermit").mockResolvedValue(true);+ vi.spyOn(projectBuild, "loadDevBuildByProjectId").mockResolvedValue(build);+ const patchBuild = vi.spyOn(projectApi, "patchBuild");++ const caller = apiRouter.createCaller(createContext(true));++ await expect(+ caller.pages.update({+ projectId: "project-1",+ pageId: build.pages.homePageId,+ values: {},+ })+ ).resolves.toEqual({+ version: 7,+ pageId: build.pages.homePageId,+ });++ expect(patchBuild).not.toHaveBeenCalled();+ });+});++describe("api instance queries", () => {+ const createInstanceQueryBuild = () =>+ ({+ id: "build-1",+ projectId: "project-1",+ version: 1,+ pages: createDefaultPages({ rootInstanceId: "root-1" }),+ instances: [+ {+ type: "instance",+ id: "root-1",+ component: "Body",+ tag: "body",+ label: "Root",+ children: [+ { type: "id", value: "hero-1" },+ { type: "text", value: "Root text" },+ ],+ },+ {+ type: "instance",+ id: "hero-1",+ component: blockComponent,+ tag: "section",+ label: "Hero",+ children: [{ type: "expression", value: "system.params.slug" }],+ },+ ],+ props: [],+ styles: [],+ styleSources: [],+ styleSourceSelections: [],+ resources: [],+ dataSources: [],+ breakpoints: [],+ }) as unknown as Awaited<+ ReturnType<typeof projectBuild.loadDevBuildByProjectId>+ >;++ test("lists instances through server semantics", async () => {+ vi.spyOn(authDb, "getTokenInfo").mockResolvedValue(createToken());+ vi.spyOn(authorizeProject, "hasProjectPermit").mockResolvedValue(true);+ vi.spyOn(projectBuild, "loadDevBuildByProjectId").mockResolvedValue(+ createInstanceQueryBuild()+ );++ const caller = apiRouter.createCaller(createContext(true));++ await expect(+ caller.instances.list({+ projectId: "project-1",+ pagePath: "",+ maxDepth: 1,+ labelContains: "Hero",+ })+ ).resolves.toEqual({+ instances: [+ {+ id: "hero-1",+ label: "Hero",+ component: blockComponent,+ tag: "section",+ depth: 1,+ childCount: 1,+ },+ ],+ });+ });++ test("lists text and expression children through server semantics", async () => {+ vi.spyOn(authDb, "getTokenInfo").mockResolvedValue(createToken());+ vi.spyOn(authorizeProject, "hasProjectPermit").mockResolvedValue(true);+ vi.spyOn(projectBuild, "loadDevBuildByProjectId").mockResolvedValue(+ createInstanceQueryBuild()+ );++ const caller = apiRouter.createCaller(createContext(true));++ await expect(+ caller.instances.listTexts({+ projectId: "project-1",+ pagePath: "",+ mode: "expression",+ maxValueLength: 6,+ })+ ).resolves.toEqual({+ texts: [+ {+ instanceId: "hero-1",+ childIndex: 0,+ component: blockComponent,+ label: "Hero",+ mode: "expression",+ value: "system",+ },+ ],+ });+ });++ test("lists project entities through semantic routes", async () => {+ const build = createInstanceQueryBuild();+ build.pages.folders.set("folder-1", {+ id: "folder-1",+ name: "Blog",+ slug: "blog",+ children: ["page-1"],+ });+ build.pages.folders+ .get(build.pages.rootFolderId)+ ?.children.push("folder-1");+ build.pages.pages.set("page-1", {+ id: "page-1",+ name: "Post",+ path: "/first-post",+ title: "Post",+ rootInstanceId: "hero-1",+ meta: { description: "Post description" },+ });+ build.styleSources.push({+ id: "token-1",+ type: "token",+ name: "Primary",+ });+ build.styles.push({+ styleSourceId: "token-1",+ breakpointId: "base",+ property: "color",+ value: { type: "keyword", value: "red" },+ });+ build.styleSourceSelections.push({+ instanceId: "hero-1",+ values: ["token-1"],+ });+ build.dataSources.push(+ {+ id: "variable-1",+ type: "variable",+ scopeInstanceId: "hero-1",+ name: "Title",+ value: { type: "string", value: "Hello" },+ },+ {+ id: "resource-data-source-1",+ type: "resource",+ scopeInstanceId: "hero-1",+ name: "Posts",+ resourceId: "resource-1",+ }+ );+ build.resources.push({+ id: "resource-1",+ name: "Posts",+ method: "get",+ url: '"https://example.com/posts"',+ headers: [],+ });+ vi.spyOn(authDb, "getTokenInfo").mockResolvedValue(createToken());+ vi.spyOn(authorizeProject, "hasProjectPermit").mockResolvedValue(true);+ vi.spyOn(projectBuild, "loadDevBuildByProjectId").mockResolvedValue(build);++ const caller = apiRouter.createCaller(createContext(true));++ await expect(+ caller.pages.list({ projectId: "project-1", includeFolders: true })+ ).resolves.toMatchObject({+ pages: [+ expect.objectContaining({ isHome: true, path: "" }),+ expect.objectContaining({+ id: "page-1",+ path: "/blog/first-post",+ parentFolderId: "folder-1",+ }),+ ],+ folders: expect.arrayContaining([+ expect.objectContaining({ id: "folder-1", slug: "blog" }),+ ]),+ });+ await expect(+ caller.pages.getByPath({+ projectId: "project-1",+ path: "/blog/first-post",+ })+ ).resolves.toMatchObject({+ id: "page-1",+ meta: { description: "Post description" },+ });+ await expect(+ caller.folders.list({ projectId: "project-1", includePages: true })+ ).resolves.toMatchObject({+ folders: expect.arrayContaining([+ expect.objectContaining({+ id: "folder-1",+ parentFolderId: build.pages.rootFolderId,+ children: ["page-1"],+ }),+ ]),+ pages: expect.arrayContaining([+ expect.objectContaining({ id: "page-1" }),+ ]),+ });+ await expect(+ caller.designTokens.list({+ projectId: "project-1",+ withUsage: true,+ })+ ).resolves.toEqual({+ tokens: [+ {+ id: "token-1",+ name: "Primary",+ styles: { color: { type: "keyword", value: "red" } },+ usageCount: 1,+ },+ ],+ });+ await expect(+ caller.variables.list({+ projectId: "project-1",+ scopeInstanceId: "hero-1",+ })+ ).resolves.toEqual({+ variables: [+ {+ id: "variable-1",+ name: "Title",+ scopeInstanceId: "hero-1",+ value: { type: "string", value: "Hello" },+ },+ ],+ });+ await expect(+ caller.resources.list({+ projectId: "project-1",+ scopeInstanceId: "hero-1",+ })+ ).resolves.toEqual({+ resources: [+ {+ id: "resource-1",+ name: "Posts",+ method: "get",+ url: '"https://example.com/posts"',+ scopeInstanceId: "hero-1",+ exposedAsDataSource: true,+ dataSourceId: "resource-data-source-1",+ },+ ],+ });+ });+});diff --git a/apps/builder/app/services/api-router.server.ts b/apps/builder/app/services/api-router.server.tsnew file mode 100644index 0000000000..ebe87f5faf--- /dev/null+++ b/apps/builder/app/services/api-router.server.ts@@ -0,0 +1,1525 @@+import { z } from "zod";+import {+ AuthorizationError,+ authorizeProject,+ procedure,+ router,+ type AppContext,+ type AuthPermit,+} from "@webstudio-is/trpc-interface/index.server";+import { loadById } from "@webstudio-is/project/index.server";+import { loadDevBuildByProjectId } from "@webstudio-is/project-build/index.server";+import {+ cssVariableValueInput,+ designTokenCreateInput,+ designTokenStyleInput,+ styleDeleteInput,+ styleReplaceInput,+ styleUpdateInput,+} from "@webstudio-is/project-build/runtime/styles";+import {+ dataVariableValueInput,+ resourceFieldsInput,+ resourceFieldsUpdateInput,+} from "@webstudio-is/project-build/runtime/data";+import {+ pageFieldsInput,+ pageMetaInput,+} from "@webstudio-is/project-build/runtime/pages";+import {+ propBindingInput,+ propValueInput,+} from "@webstudio-is/project-build/runtime/props";+import {+ createProjectDomain,+ createUnpublishJobId,+ deleteProjectDomain,+ getDefaultPublishDomains,+ getProjectPublishJob,+ listProjectDomains,+ listProjectPublishes,+ publishProject,+ updateProjectDomain,+ unpublishProjectDomains,+ verifyProjectDomain,+} from "@webstudio-is/domain/index.server";+import {+ breakpointFieldsInput,+ breakpointUpdateFieldsInput,+ projectSettingsUpdateInput as projectSettingsRuntimeUpdateInput,+ redirectFieldsInput,+ redirectUpdateFieldsInput,+} from "@webstudio-is/project-build/runtime/project-settings";+import { loadAssetsByProject } from "@webstudio-is/asset-uploader/index.server";+import { buildPatchTransaction } from "@webstudio-is/protocol";+import {+ assertApiProjectPermit,+ getTokenPermits,+ loadApiToken,+} from "./api-permits.server";+import { componentMetas } from "~/shared/component-metas.server";+import { type Asset } from "@webstudio-is/sdk";+import {+ applyContentModeTransaction,+ getContentModeCapabilities,+} from "@webstudio-is/project/content-mode-permissions";+import type { CompactBuild } from "@webstudio-is/project-build";+import {+ buildGetInput,+ buildPatchInput,+ commitBuildPatch,+ commitBuildTransactions,+ createBuildSnapshot,+ loadBuildByProjectVersion,+ loadReadableDevBuild,+ serializeProjectSummary,+} from "./api-build.server";+import { throwApiError } from "./api-errors.server";+import {+ createBuilderRuntimeState,+ executeApiRuntimeMutation,+ executeApiRuntimeOperation,+} from "./api-runtime.server";++const assertApiPublishDomains = ({+ auth,+ domains,+ project,+}: {+ auth: Awaited<ReturnType<typeof assertApiProjectPermit>>;+ domains: string[];+ project: { domain: string };+}) => {+ const { token } = auth;+ if (token.canPublish === true) {+ return;+ }+ if (+ token.relation === "builders" &&+ domains.length > 0 &&+ domains.every((domain) => domain === project.domain)+ ) {+ return;+ }+ throw new AuthorizationError(+ "Authorization token does not have publish permission"+ );+};++const projectIdInput = z.object({ projectId: z.string() });++const projectSettingsUpdateInput = projectIdInput.merge(+ projectSettingsRuntimeUpdateInput+);++const applyBuildPayload = async <Result extends Record<string, unknown> = {}>(+ ctx: AppContext,+ build: Awaited<ReturnType<typeof loadDevBuildByProjectId>>,+ projectId: string,+ payload: z.infer<typeof buildPatchTransaction>["payload"],+ result?: Result+) => ({+ ...(await commitBuildPatch({ build, ctx, projectId, payload })),+ ...(result ?? {}),+});++const projectQuery = <Schema extends z.ZodType<{ projectId: string }>, Result>(+ input: Schema,+ permit: AuthPermit,+ handler: (args: {+ ctx: AppContext;+ input: z.infer<Schema>;+ auth: Awaited<ReturnType<typeof assertApiProjectPermit>>;+ }) => Promise<Result>+) =>+ procedure.input(input).query(async ({ ctx, input }) => {+ const parsedInput = input as z.infer<Schema>;+ return await handler({+ ctx,+ input: parsedInput,+ auth: await assertApiProjectPermit(ctx, parsedInput.projectId, permit),+ });+ });++const projectMutation = <+ Schema extends z.ZodType<{ projectId: string }>,+ Result,+>(+ input: Schema,+ permit: AuthPermit,+ handler: (args: {+ ctx: AppContext;+ input: z.infer<Schema>;+ auth: Awaited<ReturnType<typeof assertApiProjectPermit>>;+ }) => Promise<Result>+) =>+ procedure.input(input).mutation(async ({ ctx, input }) => {+ const parsedInput = input as z.infer<Schema>;+ return await handler({+ ctx,+ input: parsedInput,+ auth: await assertApiProjectPermit(ctx, parsedInput.projectId, permit),+ });+ });++const buildQuery = <Schema extends z.ZodType<{ projectId: string }>, Result>(+ input: Schema,+ handler: (args: {+ ctx: AppContext;+ input: z.infer<Schema>;+ build: Awaited<ReturnType<typeof loadDevBuildByProjectId>>;+ }) => Promise<Result>+) =>+ procedure.input(input).query(async ({ ctx, input }) => {+ const parsedInput = input as z.infer<Schema>;+ return await handler({+ ctx,+ input: parsedInput,+ build: await loadReadableDevBuild(ctx, parsedInput.projectId),+ });+ });++const buildMutation = <Schema extends z.ZodType<{ projectId: string }>, Result>(+ input: Schema,+ handler: (args: {+ ctx: AppContext;+ input: z.infer<Schema>;+ build: Awaited<ReturnType<typeof loadDevBuildByProjectId>>;+ commit: BuildCommit;+ }) => Promise<Result>+) =>+ procedure.input(input).mutation(async ({ ctx, input }) => {+ const parsedInput = input as z.infer<Schema>;+ await assertApiProjectPermit(ctx, parsedInput.projectId, "build");+ const build = await loadDevBuildByProjectId(ctx, parsedInput.projectId);+ return await handler({+ ctx,+ input: parsedInput,+ build,+ commit: async <CommitResult extends Record<string, unknown> = {}>(+ payload: z.infer<typeof buildPatchTransaction>["payload"],+ result?: CommitResult+ ) =>+ (await applyBuildPayload(+ ctx,+ build,+ parsedInput.projectId,+ payload,+ result+ )) as { version: number } & CommitResult,+ });+ });++type BuildCommit = <CommitResult extends Record<string, unknown> = {}>(+ payload: z.infer<typeof buildPatchTransaction>["payload"],+ result?: CommitResult+) => Promise<{ version: number } & CommitResult>;++const commitRuntimeMutation = async <+ Result extends Record<string, unknown> = Record<string, unknown>,+>({+ id,+ build,+ assets,+ input,+ commit,+}: {+ id: string;+ build: Awaited<ReturnType<typeof loadDevBuildByProjectId>>;+ assets?: Asset[];+ input: unknown;+ commit: BuildCommit;+}) => {+ const mutation = executeApiRuntimeMutation<Result>({+ id,+ build,+ assets,+ input,+ });+ if (mutation.noop || mutation.payload.length === 0) {+ return {+ version: build.version,+ ...mutation.result,+ };+ }+ return await commit(mutation.payload, mutation.result);+};++const createContentModeCapabilitiesFromBuild = (build: CompactBuild) => {+ const state = createBuilderRuntimeState(build);+ return getContentModeCapabilities({+ instances: state.instances!,+ metas: componentMetas,+ props: state.props!,+ styleSources: state.styleSources!,+ styleSourceSelections: state.styleSourceSelections,+ styles: state.styles,+ breakpoints: state.breakpoints,+ });+};++const assertContentOrBuildPayload = ({+ auth,+ build,+ payload,+}: {+ auth: Awaited<ReturnType<typeof assertApiProjectPermit>>;+ build: CompactBuild;+ payload: z.infer<typeof buildPatchTransaction>["payload"];+}) => {+ if (auth.permits.includes("build")) {+ return;+ }+ const result = applyContentModeTransaction({+ capabilities: createContentModeCapabilitiesFromBuild(build),+ transaction: { id: "api-content-mode", payload },+ });+ if (result.success === false) {+ throw new AuthorizationError(result.error);+ }+};++const contentOrBuildMutation = <+ Schema extends z.ZodType<{ projectId: string }>,+ Result,+>(+ input: Schema,+ handler: (args: {+ ctx: AppContext;+ input: z.infer<Schema>;+ build: Awaited<ReturnType<typeof loadDevBuildByProjectId>>;+ commit: BuildCommit;+ }) => Promise<Result>+) =>+ procedure.input(input).mutation(async ({ ctx, input }) => {+ const parsedInput = input as z.infer<Schema>;+ const auth = await assertApiProjectPermit(+ ctx,+ parsedInput.projectId,+ "edit"+ );+ const build = await loadDevBuildByProjectId(ctx, parsedInput.projectId);+ return await handler({+ ctx,+ input: parsedInput,+ build,+ commit: async <CommitResult extends Record<string, unknown> = {}>(+ payload: z.infer<typeof buildPatchTransaction>["payload"],+ result?: CommitResult+ ) => {+ assertContentOrBuildPayload({ auth, build, payload });+ return (await applyBuildPayload(+ ctx,+ build,+ parsedInput.projectId,+ payload,+ result+ )) as { version: number } & CommitResult;+ },+ });+ });++const cssVariableListInput = projectIdInput.extend({+ filter: z.string().optional(),+ withUsage: z.boolean().optional(),+});++const cssVariableDefineInput = projectIdInput.extend({+ vars: z.record(cssVariableValueInput),+ overwrite: z.boolean().optional(),+});++const cssVariableDeleteInput = projectIdInput.extend({+ names: z.array(z.string()).min(1),+ force: z.boolean().optional(),+ confirm: z.literal(true),+});++const cssVariableRewriteRefsInput = projectIdInput.extend({+ map: z.record(z.string()),+ scopeRegex: z.string().optional(),+});++export const apiRouter = router({+ auth: router({+ me: procedure.query(async ({ ctx }) => {+ const token = await loadApiToken(ctx);+ const permits = getTokenPermits(token, ctx);+ return {+ actor: { type: "token" as const, tokenId: token.token },+ projectId: token.projectId,+ relation: token.relation,+ permits,+ };+ }),+ }),++ projects: router({+ permissions: procedure+ .input(projectIdInput)+ .query(async ({ ctx, input }) => {+ const token = await loadApiToken(ctx);+ if (token.projectId !== input.projectId) {+ throw new AuthorizationError(+ "Authorization token is not valid for project"+ );+ }+ const permits = getTokenPermits(token, ctx);+ const canUseProject = await authorizeProject.hasProjectPermit(+ { projectId: input.projectId, permit: "view" },+ ctx+ );+ if (canUseProject === false) {+ throw new AuthorizationError("You don't have access to this project");+ }+ return {+ relation: token.relation,+ permits,+ canView: permits.includes("view"),+ canEdit: permits.includes("edit"),+ canBuild: permits.includes("build"),+ canAdmin: permits.includes("admin"),+ canOwn: false,+ canUseApi: permits.includes("api"),+ canPublish: token.canPublish === true,+ canPublishProjectDomain:+ token.canPublish === true || token.relation === "builders",+ canPublishCustomDomains: token.canPublish === true,+ };+ }),++ get: projectQuery(projectIdInput, "view", async ({ ctx, input }) => {+ const project = await loadById(input.projectId, ctx);+ const build = await loadDevBuildByProjectId(ctx, input.projectId);+ return {+ ...serializeProjectSummary(project),+ buildId: build.id,+ version: build.version,+ homePageId: build.pages.homePageId,+ features: ctx.planFeatures,+ };+ }),+ }),++ build: router({+ get: projectQuery(buildGetInput, "view", async ({ ctx, input }) => {+ const build =+ input.version === undefined+ ? await loadDevBuildByProjectId(ctx, input.projectId)+ : await loadBuildByProjectVersion(+ ctx,+ input.projectId,+ input.version+ );++ if (build.projectId !== input.projectId) {+ throwApiError("NOT_FOUND", "Build not found for project");+ }++ const include = new Set(input.include ?? []);+ const snapshot = createBuildSnapshot({+ build,+ include,+ projectId: input.projectId,+ });+ if (include.has("assets")) {+ snapshot.assets = await loadAssetsByProject(input.projectId, ctx);+ }++ return snapshot;+ }),++ patch: projectMutation(buildPatchInput, "build", async ({ ctx, input }) => {+ const build = await loadDevBuildByProjectId(ctx, input.projectId);+ return commitBuildTransactions({+ ctx,+ projectId: input.projectId,+ buildId: build.id,+ clientVersion: input.baseVersion,+ transactions: input.transactions,+ });+ }),+ }),++ pages: router({+ list: buildQuery(+ projectIdInput.extend({ includeFolders: z.boolean().optional() }),+ async ({ input, build }) => {+ return executeApiRuntimeOperation({+ id: "pages.list",+ build,+ input,+ });+ }+ ),++ get: buildQuery(+ projectIdInput.extend({ pageId: z.string() }),+ async ({ input, build }) => {+ return executeApiRuntimeOperation({+ id: "pages.get",+ build,+ input,+ });+ }+ ),++ getByPath: buildQuery(+ projectIdInput.extend({ path: z.string() }),+ async ({ input, build }) => {+ return executeApiRuntimeOperation({+ id: "pages.getByPath",+ build,+ input,+ });+ }+ ),++ create: buildMutation(+ projectIdInput.extend({+ pageId: z.string().optional(),+ name: z.string().min(1),+ path: z.string(),+ title: z.string().optional(),+ parentFolderId: z.string().optional(),+ meta: pageMetaInput.optional(),+ }),+ async ({ input, build, commit }) => {+ return await commitRuntimeMutation<{ pageId: string }>({+ id: "pages.create",+ build,+ input,+ commit,+ });+ }+ ),++ update: buildMutation(+ projectIdInput.extend({+ pageId: z.string(),+ values: pageFieldsInput,+ }),+ async ({ input, build, commit }) => {+ return await commitRuntimeMutation<{ pageId: string }>({+ id: "pages.update",+ build,+ input,+ commit,+ });+ }+ ),++ delete: buildMutation(+ projectIdInput.extend({ pageId: z.string() }),+ async ({ input, build, commit }) => {+ return await commitRuntimeMutation<{ pageId: string }>({+ id: "pages.delete",+ build,+ input,+ commit,+ });+ }+ ),++ duplicate: buildMutation(+ projectIdInput.extend({+ pageId: z.string(),+ parentFolderId: z.string().optional(),+ name: z.string().min(1).optional(),+ path: z.string().optional(),+ }),+ async ({ input, build, commit }) => {+ return await commitRuntimeMutation<{ pageId: string }>({+ id: "pages.duplicate",+ build,+ input,+ commit,+ });+ }+ ),+ }),++ pageTemplates: router({+ list: buildQuery(projectIdInput, async ({ build }) => {+ return executeApiRuntimeOperation({+ id: "pageTemplates.list",+ build,+ input: {},+ });+ }),++ createPage: buildMutation(+ projectIdInput.extend({+ templateId: z.string(),+ parentFolderId: z.string().optional(),+ name: z.string().min(1),+ path: z.string(),+ }),+ async ({ input, build, commit }) => {+ return await commitRuntimeMutation<{ pageId: string }>({+ id: "pageTemplates.createPage",+ build,+ input,+ commit,+ });+ }+ ),+ }),++ projectSettings: router({+ get: buildQuery(projectIdInput, async ({ build }) => {+ return executeApiRuntimeOperation({+ id: "projectSettings.get",+ build,+ input: {},+ });+ }),++ update: buildMutation(+ projectSettingsUpdateInput,+ async ({ input, build, commit }) => {+ return await commitRuntimeMutation<{ updated: boolean }>({+ id: "projectSettings.update",+ build,+ input,+ commit,+ });+ }+ ),+ }),++ redirects: router({+ list: buildQuery(projectIdInput, async ({ build }) => {+ return executeApiRuntimeOperation({+ id: "redirects.list",+ build,+ input: {},+ });+ }),++ create: buildMutation(+ projectIdInput.merge(redirectFieldsInput),+ async ({ input, build, commit }) => {+ return await commitRuntimeMutation<{ old: string }>({+ id: "redirects.create",+ build,+ input,+ commit,+ });+ }+ ),++ update: buildMutation(+ projectIdInput.extend({+ old: z.string(),+ values: redirectUpdateFieldsInput,+ }),+ async ({ input, build, commit }) => {+ return await commitRuntimeMutation<{ old: string }>({+ id: "redirects.update",+ build,+ input,+ commit,+ });+ }+ ),++ delete: buildMutation(+ projectIdInput.extend({ old: z.string() }),+ async ({ input, build, commit }) => {+ return await commitRuntimeMutation<{ old: string }>({+ id: "redirects.delete",+ build,+ input,+ commit,+ });+ }+ ),+ }),++ breakpoints: router({+ list: buildQuery(projectIdInput, async ({ build }) => {+ return executeApiRuntimeOperation({+ id: "breakpoints.list",+ build,+ input: {},+ });+ }),++ create: buildMutation(+ projectIdInput.merge(breakpointFieldsInput),+ async ({ input, build, commit }) => {+ return await commitRuntimeMutation<{ breakpointId: string }>({+ id: "breakpoints.create",+ build,+ input,+ commit,+ });+ }+ ),++ update: buildMutation(+ projectIdInput.extend({+ breakpointId: z.string(),+ values: breakpointUpdateFieldsInput,+ }),+ async ({ input, build, commit }) => {+ return await commitRuntimeMutation<{ breakpointId: string }>({+ id: "breakpoints.update",+ build,+ input,+ commit,+ });+ }+ ),++ delete: buildMutation(+ projectIdInput.extend({ breakpointId: z.string() }),+ async ({ input, build, commit }) => {+ return await commitRuntimeMutation<{ breakpointId: string }>({+ id: "breakpoints.delete",+ build,+ input,+ commit,+ });+ }+ ),+ }),++ folders: router({+ list: buildQuery(+ projectIdInput.extend({ includePages: z.boolean().optional() }),+ async ({ input, build }) => {+ return executeApiRuntimeOperation({+ id: "folders.list",+ build,+ input,+ });+ }+ ),++ create: buildMutation(+ projectIdInput.extend({+ folderId: z.string().optional(),+ name: z.string().min(1),+ slug: z.string(),+ parentFolderId: z.string().optional(),+ }),+ async ({ input, build, commit }) => {+ return await commitRuntimeMutation<{ folderId: string }>({+ id: "folders.create",+ build,+ input,+ commit,+ });+ }+ ),++ update: buildMutation(+ projectIdInput.extend({+ folderId: z.string(),+ values: z.object({+ name: z.string().min(1).optional(),+ slug: z.string().optional(),+ parentFolderId: z.string().optional(),+ }),+ }),+ async ({ input, build, commit }) => {+ return await commitRuntimeMutation<{ folderId: string }>({+ id: "folders.update",+ build,+ input,+ commit,+ });+ }+ ),++ delete: buildMutation(+ projectIdInput.extend({ folderId: z.string() }),+ async ({ input, build, commit }) => {+ return await commitRuntimeMutation<{+ folderId: string;+ pageIds: string[];+ folderIds: string[];+ }>({+ id: "folders.delete",+ build,+ input,+ commit,+ });+ }+ ),+ }),++ instances: router({+ list: buildQuery(+ projectIdInput.extend({+ pageId: z.string().optional(),+ pagePath: z.string().optional(),+ rootInstanceId: z.string().optional(),+ maxDepth: z.number().int().nonnegative().optional(),+ topLevelOnly: z.boolean().optional(),+ component: z.string().optional(),+ tag: z.string().optional(),+ labelContains: z.string().optional(),+ }),+ async ({ input, build }) => {+ return executeApiRuntimeOperation({+ id: "instances.list",+ build,+ input,+ });+ }+ ),++ inspect: buildQuery(+ projectIdInput.extend({+ instanceId: z.string(),+ include: z+ .array(z.enum(["props", "styles", "children", "bindings", "sources"]))+ .optional(),+ childDepth: z.number().int().optional(),+ }),+ async ({ input, build }) => {+ return executeApiRuntimeOperation({+ id: "instances.inspect",+ build,+ input,+ });+ }+ ),++ append: buildMutation(+ projectIdInput.extend({+ parentInstanceId: z.string(),+ mode: z.enum(["append", "prepend", "replace"]).optional(),+ insertIndex: z.number().int().nonnegative().optional(),+ children: z+ .array(+ z.object({+ instanceId: z.string().optional(),+ component: z.string().optional(),+ tag: z.string(),+ label: z.string().optional(),+ text: z.string().optional(),+ })+ )+ .min(1),+ }),+ async ({ input, build, commit }) => {+ return await commitRuntimeMutation<{+ instanceIds: string[];+ removedInstanceIds: string[];+ }>({+ id: "instances.append",+ build,+ input,+ commit,+ });+ }+ ),++ move: buildMutation(+ projectIdInput.extend({+ moves: z+ .array(+ z.object({+ instanceId: z.string(),+ parentInstanceId: z.string(),+ insertIndex: z.number().int().nonnegative().optional(),+ })+ )+ .min(1),+ }),+ async ({ input, build, commit }) => {+ return await commitRuntimeMutation<{ instanceIds: string[] }>({+ id: "instances.move",+ build,+ input,+ commit,+ });+ }+ ),++ clone: buildMutation(+ projectIdInput.extend({+ sourceInstanceId: z.string(),+ targetParentInstanceId: z.string().optional(),+ insertIndex: z.number().int().nonnegative().optional(),+ }),+ async ({ input, build, commit }) => {+ return await commitRuntimeMutation<{+ instanceId: string;+ instanceIds: string[];+ }>({+ id: "instances.clone",+ build,+ input,+ commit,+ });+ }+ ),++ delete: buildMutation(+ projectIdInput.extend({+ instanceIds: z.array(z.string()).min(1),+ }),+ async ({ input, build, commit }) => {+ return await commitRuntimeMutation<{ instanceIds: string[] }>({+ id: "instances.delete",+ build,+ input,+ commit,+ });+ }+ ),++ updateProps: contentOrBuildMutation(+ projectIdInput.extend({+ updates: z.array(propValueInput).min(1),+ }),+ async ({ input, build, commit }) => {+ return await commitRuntimeMutation<{ propIds: string[] }>({+ id: "instances.updateProps",+ build,+ input,+ commit,+ });+ }+ ),++ deleteProps: contentOrBuildMutation(+ projectIdInput.extend({+ deletions: z+ .array(z.object({ instanceId: z.string(), name: z.string() }))+ .min(1),+ }),+ async ({ input, build, commit }) => {+ return await commitRuntimeMutation<{ propIds: string[] }>({+ id: "instances.deleteProps",+ build,+ input,+ commit,+ });+ }+ ),++ bindProps: buildMutation(+ projectIdInput.extend({+ bindings: z.array(propBindingInput).min(1),+ }),+ async ({ input, build, commit }) => {+ return await commitRuntimeMutation<{ propIds: string[] }>({+ id: "instances.bindProps",+ build,+ input,+ commit,+ });+ }+ ),++ listTexts: buildQuery(+ projectIdInput.extend({+ pageId: z.string().optional(),+ pagePath: z.string().optional(),+ instanceId: z.string().optional(),+ mode: z.enum(["text", "expression", "all"]).optional(),+ contains: z.string().optional(),+ maxValueLength: z.number().int().nonnegative().optional(),+ }),+ async ({ input, build }) => {+ return executeApiRuntimeOperation({+ id: "instances.listTexts",+ build,+ input,+ });+ }+ ),++ updateText: contentOrBuildMutation(+ projectIdInput.extend({+ instanceId: z.string(),+ childIndex: z.number().int().nonnegative(),+ text: z.string(),+ mode: z.enum(["text", "expression"]).optional(),+ }),+ async ({ input, build, commit }) => {+ return await commitRuntimeMutation<{+ instanceId: string;+ childIndex: number;+ mode: "text" | "expression";+ }>({+ id: "instances.updateText",+ build,+ input,+ commit,+ });+ }+ ),+ }),++ styles: router({+ getDeclarations: buildQuery(+ projectIdInput.extend({+ instanceIds: z.array(z.string()).optional(),+ pageId: z.string().optional(),+ pagePath: z.string().optional(),+ breakpoint: z.string().optional(),+ state: z.string().optional(),+ property: z.string().optional(),+ propertyFilter: z.string().optional(),+ includeTokens: z.boolean().optional(),+ }),+ async ({ input, build }) => {+ return executeApiRuntimeOperation({+ id: "styles.getDeclarations",+ build,+ input,+ });+ }+ ),++ updateDeclarations: buildMutation(+ projectIdInput.extend({+ updates: z.array(styleUpdateInput).min(1),+ }),+ async ({ input, build, commit }) => {+ return await commitRuntimeMutation<{ styleKeys: string[] }>({+ id: "styles.updateDeclarations",+ build,+ input,+ commit,+ });+ }+ ),++ deleteDeclarations: buildMutation(+ projectIdInput.extend({+ deletions: z.array(styleDeleteInput).min(1),+ }),+ async ({ input, build, commit }) => {+ return await commitRuntimeMutation<{ styleKeys: string[] }>({+ id: "styles.deleteDeclarations",+ build,+ input,+ commit,+ });+ }+ ),++ replaceValues: buildMutation(+ projectIdInput.merge(styleReplaceInput),+ async ({ input, build, commit }) => {+ return await commitRuntimeMutation<{ styleKeys: string[] }>({+ id: "styles.replaceValues",+ build,+ input,+ commit,+ });+ }+ ),+ }),++ designTokens: router({+ list: buildQuery(+ projectIdInput.extend({+ filter: z.string().optional(),+ withUsage: z.boolean().optional(),+ sort: z.enum(["name", "usage"]).optional(),+ }),+ async ({ input, build }) => {+ return executeApiRuntimeOperation({+ id: "designTokens.list",+ build,+ input,+ });+ }+ ),++ create: buildMutation(+ projectIdInput.extend({+ tokens: z.array(designTokenCreateInput).min(1),+ }),+ async ({ input, build, commit }) => {+ return await commitRuntimeMutation<{ tokenIds: string[] }>({+ id: "designTokens.create",+ build,+ input,+ commit,+ });+ }+ ),++ updateStyles: buildMutation(+ projectIdInput.extend({+ designTokenId: z.string(),+ updates: z.array(designTokenStyleInput).min(1),+ }),+ async ({ input, build, commit }) => {+ return await commitRuntimeMutation<{+ designTokenId: string;+ styleKeys: string[];+ }>({+ id: "designTokens.updateStyles",+ build,+ input,+ commit,+ });+ }+ ),++ deleteStyles: buildMutation(+ projectIdInput.extend({+ designTokenId: z.string(),+ deletions: z.array(styleDeleteInput.omit({ instanceId: true })).min(1),+ }),+ async ({ input, build, commit }) => {+ return await commitRuntimeMutation<{+ designTokenId: string;+ styleKeys: string[];+ }>({+ id: "designTokens.deleteStyles",+ build,+ input,+ commit,+ });+ }+ ),++ attach: buildMutation(+ projectIdInput.extend({+ designTokenId: z.string(),+ instanceIds: z.array(z.string()).min(1),+ position: z.enum(["before-local", "after-local"]).optional(),+ }),+ async ({ input, build, commit }) => {+ return await commitRuntimeMutation<{+ designTokenId: string;+ }>({+ id: "designTokens.attach",+ build,+ input,+ commit,+ });+ }+ ),++ detach: buildMutation(+ projectIdInput.extend({+ designTokenId: z.string(),+ instanceIds: z.array(z.string()).min(1),+ }),+ async ({ input, build, commit }) => {+ return await commitRuntimeMutation<{+ designTokenId: string;+ }>({+ id: "designTokens.detach",+ build,+ input,+ commit,+ });+ }+ ),++ extract: buildMutation(+ projectIdInput.extend({+ instanceIds: z.array(z.string()).min(1),+ name: z.string().min(1),+ removeLocalProps: z.array(z.string()).optional(),+ }),+ async ({ input, build, commit }) => {+ return await commitRuntimeMutation<{+ designTokenId: string;+ styleKeys: string[];+ }>({+ id: "designTokens.extract",+ build,+ input,+ commit,+ });+ }+ ),+ }),++ cssVariables: router({+ list: buildQuery(cssVariableListInput, async ({ input, build }) => {+ return executeApiRuntimeOperation({+ id: "cssVariables.list",+ build,+ input,+ });+ }),++ define: buildMutation(+ cssVariableDefineInput,+ async ({ input, build, commit }) => {+ return await commitRuntimeMutation<{ names: string[] }>({+ id: "cssVariables.define",+ build,+ input,+ commit,+ });+ }+ ),++ delete: buildMutation(+ cssVariableDeleteInput,+ async ({ input, build, commit }) => {+ return await commitRuntimeMutation<{+ names: string[];+ styleKeys: string[];+ }>({+ id: "cssVariables.delete",+ build,+ input,+ commit,+ });+ }+ ),++ rewriteRefs: buildMutation(+ cssVariableRewriteRefsInput,+ async ({ input, build, commit }) => {+ return await commitRuntimeMutation<{+ styleKeys: string[];+ propIds: string[];+ }>({+ id: "cssVariables.rewriteRefs",+ build,+ input,+ commit,+ });+ }+ ),+ }),++ variables: router({+ list: buildQuery(+ projectIdInput.extend({ scopeInstanceId: z.string().optional() }),+ async ({ input, build }) => {+ return executeApiRuntimeOperation({+ id: "variables.list",+ build,+ input,+ });+ }+ ),++ create: buildMutation(+ projectIdInput.extend({+ dataSourceId: z.string().optional(),+ scopeInstanceId: z.string(),+ name: z.string(),+ value: dataVariableValueInput,+ }),+ async ({ input, build, commit }) => {+ return await commitRuntimeMutation<{ dataSourceId: string }>({+ id: "variables.create",+ build,+ input,+ commit,+ });+ }+ ),++ update: buildMutation(+ projectIdInput.extend({+ dataSourceId: z.string(),+ values: z.object({+ scopeInstanceId: z.string().optional(),+ name: z.string().optional(),+ value: dataVariableValueInput.optional(),+ }),+ }),+ async ({ input, build, commit }) => {+ return await commitRuntimeMutation<{ dataSourceId: string }>({+ id: "variables.update",+ build,+ input,+ commit,+ });+ }+ ),++ delete: buildMutation(+ projectIdInput.extend({+ dataSourceId: z.string(),+ }),+ async ({ input, build, commit }) => {+ return await commitRuntimeMutation<{ dataSourceId: string }>({+ id: "variables.delete",+ build,+ input,+ commit,+ });+ }+ ),+ }),++ resources: router({+ list: buildQuery(+ projectIdInput.extend({ scopeInstanceId: z.string().optional() }),+ async ({ input, build }) => {+ return executeApiRuntimeOperation({+ id: "resources.list",+ build,+ input,+ });+ }+ ),++ create: buildMutation(+ projectIdInput.extend({+ resourceId: z.string().optional(),+ resource: resourceFieldsInput,+ dataSourceId: z.string().optional(),+ scopeInstanceId: z.string().optional(),+ dataSourceName: z.string().optional(),+ }),+ async ({ input, build, commit }) => {+ return await commitRuntimeMutation<{+ resourceId: string;+ dataSourceId?: string;+ }>({+ id: "resources.create",+ build,+ input,+ commit,+ });+ }+ ),++ update: buildMutation(+ projectIdInput.extend({+ resourceId: z.string(),+ values: resourceFieldsUpdateInput,+ dataSourceName: z.string().optional(),+ scopeInstanceId: z.string().optional(),+ }),+ async ({ input, build, commit }) => {+ return await commitRuntimeMutation<{ resourceId: string }>({+ id: "resources.update",+ build,+ input,+ commit,+ });+ }+ ),++ delete: buildMutation(+ projectIdInput.extend({+ resourceId: z.string(),+ force: z.boolean().optional(),+ }),+ async ({ input, build, commit }) => {+ return await commitRuntimeMutation<{+ resourceId: string;+ dataSourceIds: string[];+ propIds: string[];+ }>({+ id: "resources.delete",+ build,+ input,+ commit,+ });+ }+ ),+ }),++ publish: router({+ list: projectQuery(projectIdInput, "view", async ({ ctx, input }) => {+ return await listProjectPublishes(input.projectId, ctx);+ }),++ create: projectMutation(+ projectIdInput.extend({+ target: z.enum(["staging", "production"]),+ domains: z.array(z.string()).optional(),+ message: z.string().optional(),+ idempotencyKey: z.string().optional(),+ }),+ "edit",+ async ({ auth, ctx, input }) => {+ const project = await loadById(input.projectId, ctx);+ const domains =+ input.domains ?? getDefaultPublishDomains(project, input.target);+ assertApiPublishDomains({ auth, domains, project });+ const { build, deploymentNotImplemented } = await publishProject(+ { project, domains },+ ctx+ );+ return {+ jobId: build.id,+ warning: deploymentNotImplemented+ ? "Publish was recorded locally, but the deployment service is not available in this environment."+ : undefined,+ };+ }+ ),++ getJob: projectQuery(+ projectIdInput.extend({ jobId: z.string() }),+ "view",+ async ({ ctx, input }) => {+ const publishJob = await getProjectPublishJob(input, ctx);+ if (publishJob === undefined) {+ return throwApiError("NOT_FOUND", "Publish job not found");+ }+ return publishJob;+ }+ ),++ unpublish: projectMutation(+ projectIdInput.extend({+ target: z.enum(["staging", "production"]),+ domains: z.array(z.string()).optional(),+ message: z.string().optional(),+ idempotencyKey: z.string().optional(),+ confirm: z.literal(true),+ }),+ "edit",+ async ({ auth, ctx, input }) => {+ const project = await loadById(input.projectId, ctx);+ const domains =+ input.domains ?? getDefaultPublishDomains(project, input.target);+ assertApiPublishDomains({ auth, domains, project });+ await unpublishProjectDomains(+ { projectId: input.projectId, domains },+ ctx+ );+ return { jobId: input.idempotencyKey ?? createUnpublishJobId() };+ }+ ),+ }),++ domains: router({+ list: projectQuery(projectIdInput, "view", async ({ ctx, input }) => {+ return { domains: await listProjectDomains(input.projectId, ctx) };+ }),++ create: projectMutation(+ projectIdInput.extend({ domain: z.string() }),+ "admin",+ async ({ ctx, input }) => {+ return await createProjectDomain(input, ctx);+ }+ ),++ update: projectMutation(+ projectIdInput.extend({+ domainId: z.string(),+ updates: z.object({ domain: z.string().optional() }),+ }),+ "admin",+ async ({ ctx, input }) => {+ return await updateProjectDomain(input, ctx);+ }+ ),++ delete: projectMutation(+ projectIdInput.extend({+ domainId: z.string(),+ confirm: z.literal(true),+ }),+ "admin",+ async ({ ctx, input }) => {+ return await deleteProjectDomain(input, ctx);+ }+ ),++ verify: projectMutation(+ projectIdInput.extend({ domainId: z.string() }),+ "admin",+ async ({ ctx, input }) => {+ return await verifyProjectDomain(input, ctx);+ }+ ),+ }),++ assets: router({+ list: projectQuery(+ projectIdInput.extend({+ type: z.enum(["image", "font"]).optional(),+ withUsage: z.boolean().optional(),+ sort: z.enum(["name", "size", "createdAt", "usage"]).optional(),+ cursor: z.string().optional(),+ limit: z.number().int().min(1).optional(),+ }),+ "view",+ async ({ ctx, input }) => {+ const assets = await loadAssetsByProject(input.projectId, ctx, {+ skipPermissionsCheck: true,+ });+ const build = await loadDevBuildByProjectId(ctx, input.projectId);+ return executeApiRuntimeOperation({+ id: "assets.list",+ build,+ assets,+ input,+ });+ }+ ),++ findUsage: projectQuery(+ projectIdInput.extend({ assetId: z.string() }),+ "view",+ async ({ ctx, input }) => {+ const assets = await loadAssetsByProject(input.projectId, ctx, {+ skipPermissionsCheck: true,+ });+ const build = await loadDevBuildByProjectId(ctx, input.projectId);+ return executeApiRuntimeOperation({+ id: "assets.findUsage",+ build,+ assets,+ input,+ });+ }+ ),++ replace: buildMutation(+ projectIdInput.extend({+ fromAssetId: z.string(),+ toAssetId: z.string(),+ confirm: z.literal(true),+ }),+ async ({ ctx, input, build, commit }) => {+ const assets = await loadAssetsByProject(input.projectId, ctx, {+ skipPermissionsCheck: true,+ });+ return await commitRuntimeMutation({+ id: "assets.replace",+ build,+ assets,+ input,+ commit,+ });+ }+ ),++ delete: buildMutation(+ projectIdInput.extend({+ assetIdsOrPrefixes: z.array(z.string()).min(1),+ force: z.boolean().optional(),+ confirm: z.literal(true),+ }),+ async ({ ctx, input, build, commit }) => {+ const assets = await loadAssetsByProject(input.projectId, ctx, {+ skipPermissionsCheck: true,+ });+ return await commitRuntimeMutation({+ id: "assets.delete",+ build,+ assets,+ input,+ commit,+ });+ }+ ),+ }),+});++export const __testing__ = {+ assertContentOrBuildPayload,+ assertApiPublishDomains,+};diff --git a/apps/builder/app/services/api-runtime.server.test.ts b/apps/builder/app/services/api-runtime.server.test.tsnew file mode 100644index 0000000000..c2409d357e--- /dev/null+++ b/apps/builder/app/services/api-runtime.server.test.ts@@ -0,0 +1,62 @@+import { describe, expect, test } from "vitest";+import { createDefaultPages } from "@webstudio-is/project-build";+import type { CompactBuild } from "@webstudio-is/project-build";+import type { Asset } from "@webstudio-is/sdk";+import {+ createBuilderRuntimeState,+ executeApiRuntimeOperation,+} from "./api-runtime.server";++const createBuild = (): CompactBuild =>+ ({+ id: "build-1",+ projectId: "project-1",+ version: 1,+ pages: createDefaultPages({ rootInstanceId: "root-1" }),+ instances: [{ type: "instance", id: "root-1", component: "Body" }],+ props: [],+ styles: [],+ styleSources: [],+ styleSourceSelections: [],+ dataSources: [],+ resources: [],+ assets: [],+ breakpoints: [],+ }) as unknown as CompactBuild;++describe("api runtime adapter", () => {+ test("normalizes compact build arrays into builder state maps", () => {+ const asset = { id: "asset-1", name: "image.png" } as Asset;+ const state = createBuilderRuntimeState(createBuild(), [asset]);++ expect(state.pages?.homePageId).toBeDefined();+ expect(state.instances?.get("root-1")).toMatchObject({+ id: "root-1",+ component: "Body",+ });+ expect(state.assets?.get("asset-1")).toEqual(asset);+ expect(state.assets?.get("asset-1")).not.toBe(asset);+ });++ test("executes runtime reads and maps runtime errors to public api errors", () => {+ const build = createBuild();++ expect(+ executeApiRuntimeOperation({+ id: "pages.list",+ build,+ input: { projectId: "project-1" },+ })+ ).toMatchObject({+ pages: [expect.objectContaining({ isHome: true })],+ });++ expect(() =>+ executeApiRuntimeOperation({+ id: "pages.get",+ build,+ input: { pageId: "missing" },+ })+ ).toThrow("Page not found");+ });+});diff --git a/apps/builder/app/services/api-runtime.server.ts b/apps/builder/app/services/api-runtime.server.tsnew file mode 100644index 0000000000..e2932a7798--- /dev/null+++ b/apps/builder/app/services/api-runtime.server.ts@@ -0,0 +1,54 @@+import { nanoid } from "nanoid";+import type { CompactBuild } from "@webstudio-is/project-build";+import { executeBuilderRuntimeOperation } from "@webstudio-is/project-build/runtime/registry";+import { BuilderRuntimeError } from "@webstudio-is/project-build/runtime/errors";+import { type BuilderRuntimeMutation } from "@webstudio-is/project-build/runtime/mutation";+import type { BuilderState } from "@webstudio-is/project-build/state/builder-state";+import { createBuilderStateFromCompactBuild } from "@webstudio-is/project-build/state/adapters";+import { type Asset } from "@webstudio-is/sdk";+import { throwApiError } from "./api-errors.server";++const defaultBuilderRuntimeContext = {+ createId: nanoid,+ now: () => new Date(),+};++export const createBuilderRuntimeState = (+ build: CompactBuild,+ assets?: Asset[]+): BuilderState => createBuilderStateFromCompactBuild({ ...build, assets });++export const executeApiRuntimeOperation = <Result>({+ id,+ build,+ assets,+ input,+}: {+ id: string;+ build: CompactBuild;+ assets?: Asset[];+ input: unknown;+}): Result => {+ try {+ return executeBuilderRuntimeOperation<Result>({+ id,+ state: createBuilderRuntimeState(build, assets),+ input,+ context: defaultBuilderRuntimeContext,+ });+ } catch (error) {+ if (error instanceof BuilderRuntimeError) {+ return throwApiError(error.code, error.message);+ }+ throw error;+ }+};++export const executeApiRuntimeMutation = <+ Result extends Record<string, unknown> = Record<string, unknown>,+>(args: {+ id: string;+ build: CompactBuild;+ assets?: Asset[];+ input: unknown;+}) => executeApiRuntimeOperation<BuilderRuntimeMutation<Result>>(args);diff --git a/apps/builder/app/routes-tests/rest-assets-name.server.test.ts b/apps/builder/app/services/asset-upload.server.test.tssimilarity index 97%rename from apps/builder/app/routes-tests/rest-assets-name.server.test.tsrename to apps/builder/app/services/asset-upload.server.test.tsindex 412f244fad..d89bc7c60a 100644--- a/apps/builder/app/routes-tests/rest-assets-name.server.test.ts+++ b/apps/builder/app/services/asset-upload.server.test.ts@@ -1,13 +1,13 @@+// @vitest-environment node+import { afterEach, expect, test, vi } from "vitest";import { RESIZABLE_IMAGE_MIME_TYPES } from "@webstudio-is/sdk";-import { __testing__ } from "../routes/rest.assets_.$name";--const {+import {getAssetInfoFallback,getBrowserAssetFormat,getBrowserUploadBody,parseAssetType,-} = __testing__;+} from "./asset-upload.server";afterEach(() => {vi.unstubAllGlobals();diff --git a/apps/builder/app/services/asset-upload.server.ts b/apps/builder/app/services/asset-upload.server.tsnew file mode 100644index 0000000000..7bd30cc033--- /dev/null+++ b/apps/builder/app/services/asset-upload.server.ts@@ -0,0 +1,106 @@+import { z } from "zod";+import {+ ALLOWED_FILE_TYPES,+ assetType,+ isAllowedMimeCategory,+ RESIZABLE_IMAGE_MIME_TYPES,+} from "@webstudio-is/sdk";++const urlBody = z.object({+ url: z.string(),+});++export const parseAssetType = (value: string | null) => {+ const result = assetType.safeParse(value);+ return result.success ? result.data : undefined;+};++export type AssetInfoFallback =+ | { width: number; height: number; format: string }+ | undefined;++export const getAssetInfoFallback = ({+ format,+ searchParams,+}: {+ format: string | undefined;+ searchParams: URLSearchParams;+}): AssetInfoFallback => {+ const width = Number.parseInt(searchParams.get("width") ?? "", 10);+ const height = Number.parseInt(searchParams.get("height") ?? "", 10);+ if (+ Number.isFinite(width) === false ||+ Number.isFinite(height) === false ||+ format === undefined+ ) {+ return;+ }+ return { width, height, format };+};++export const getBrowserUploadBody = async (+ request: Request,+ contentType: string | null+) => {+ let body = request.body;+ if (body === null) {+ throw new Error("Asset body is empty");+ }++ if (contentType?.includes("application/json")) {+ const jsonBody = await request.json();+ const urlParse = urlBody.safeParse(jsonBody);++ if (urlParse.success) {+ const { url } = urlParse.data;+ const imageRequest = await fetch(url, {+ method: "GET",+ headers: {+ Accept: RESIZABLE_IMAGE_MIME_TYPES.join(","),+ },+ });++ if (imageRequest.ok === false) {+ const error = await imageRequest.text();+ throw new Error(+ `An error occurred while fetching the image at ${url}: ${error.slice(0, 500)}`+ );+ }++ if (imageRequest.body === null) {+ throw new Error(+ `An error occurred while fetching the image at ${url}: Image body is null`+ );+ }++ body = imageRequest.body;+ } else {+ body = new Blob([JSON.stringify(jsonBody)], {+ type: "application/json",+ }).stream();+ }+ }++ return body;+};++export const getBrowserAssetFormat = ({+ contentType,+ name,+}: {+ contentType: string | null;+ name: string;+}) => {+ const fileExtension = name.split(".").pop()?.toLowerCase();+ const correctMimeType =+ ALLOWED_FILE_TYPES[fileExtension as keyof typeof ALLOWED_FILE_TYPES] ??+ contentType?.split(";")[0];++ const contentTypeArr = correctMimeType?.split("/") ?? [];+ const mimeCategory = contentTypeArr[0];+ if (mimeCategory && correctMimeType && !isAllowedMimeCategory(mimeCategory)) {+ throw new Error(`MIME type "${mimeCategory}/*" is not allowed`);+ }++ return contentTypeArr[0] === "video" ? contentTypeArr[1] : undefined;+};diff --git a/apps/builder/app/services/builder-auth.server.ts b/apps/builder/app/services/builder-auth.server.tsindex 7b522ba3fa..813daf4146 100644--- a/apps/builder/app/services/builder-auth.server.ts+++ b/apps/builder/app/services/builder-auth.server.ts@@ -10,7 +10,7 @@ import {getAuthorizationServerOrigin,getRequestOrigin,} from "~/shared/router-utils/origins";-import { parseBuilderUrl } from "@webstudio-is/http-client";+import { parseBuilderUrl } from "@webstudio-is/protocol";import { createDebug } from "~/shared/debug";import { readAccessToken } from "./token.server";import { isUserAuthorizedForProject } from "./builder-access.server";diff --git a/apps/builder/app/routes-tests/builder-logout.test.ts b/apps/builder/app/services/builder-logout-action.server.test.tssimilarity index 87%rename from apps/builder/app/routes-tests/builder-logout.test.tsrename to apps/builder/app/services/builder-logout-action.server.test.tsindex 1d355abe22..a53e72ae5b 100644--- a/apps/builder/app/routes-tests/builder-logout.test.ts+++ b/apps/builder/app/services/builder-logout-action.server.test.ts@@ -1,19 +1,13 @@import { beforeEach, describe, expect, test, vi } from "vitest";--const logoutMock = vi.hoisted(() => vi.fn());--vi.mock("~/services/builder-auth.server", () => ({- builderAuthenticator: {- logout: logoutMock,- },-}));--import { action } from "../routes/builder-logout";+import { createBuilderLogoutAction } from "./builder-logout-action.server";const projectOrigin ="https://p-042d35b0-718e-4c5f-a5dd-8568282366e5.apps.webstudio.is";const dashboardOrigin = "https://apps.webstudio.is";+const logout = vi.fn();+const action = createBuilderLogoutAction(logout);+const callAction = (request: Request) =>action({request,@@ -21,9 +15,9 @@ const callAction = (request: Request) =>context: {},});-describe("builder logout route", () => {+describe("builder logout action", () => {beforeEach(() => {- logoutMock.mockReset();+ logout.mockReset();});test("responds to authorized preflight with CORS headers", async () => {@@ -52,7 +46,7 @@ describe("builder logout route", () => {});test("adds CORS headers to successful logout response", async () => {- logoutMock.mockRejectedValueOnce(+ logout.mockRejectedValueOnce(new Response(null, {status: 302,headers: {@@ -81,6 +75,9 @@ describe("builder logout route", () => {expect(response.headers.get("Access-Control-Allow-Credentials")).toBe("true");+ expect(logout).toHaveBeenCalledWith(expect.any(Request), {+ redirectTo: `${dashboardOrigin}/login`,+ });});test("rejects preflight from a different origin", async () => {@@ -110,6 +107,6 @@ describe("builder logout route", () => {);expect(response.status).toBe(403);- expect(logoutMock).not.toHaveBeenCalled();+ expect(logout).not.toHaveBeenCalled();});});diff --git a/apps/builder/app/services/builder-logout-action.server.ts b/apps/builder/app/services/builder-logout-action.server.tsnew file mode 100644index 0000000000..1a0fb55e9c--- /dev/null+++ b/apps/builder/app/services/builder-logout-action.server.ts@@ -0,0 +1,151 @@+import { json, type ActionFunctionArgs } from "@remix-run/server-runtime";+import { createDebug } from "~/shared/debug";+import { getAuthorizationServerOrigin } from "~/shared/router-utils/origins";+import { isBuilder, loginPath } from "~/shared/router-utils";+import { isRedirectResponse } from "~/services/cookie.server";+import {+ appendVaryHeader,+ createPrivateNoStoreHeaders,+} from "~/services/cache-control.server";++const debug = createDebug(import.meta.url);++const getCorsHeaders = (request: Request) => {+ const origin = request.headers.get("Origin");+ const allowedOrigin = getAuthorizationServerOrigin(request.url);++ if (origin !== allowedOrigin) {+ return;+ }++ return {+ "Access-Control-Allow-Credentials": "true",+ "Access-Control-Allow-Headers": "Content-Type",+ "Access-Control-Allow-Methods": "POST, OPTIONS",+ "Access-Control-Allow-Origin": origin,+ };+};++const withCors = (request: Request, response: Response) => {+ const corsHeaders = getCorsHeaders(request);+ if (corsHeaders === undefined) {+ return response;+ }++ const headers = createPrivateNoStoreHeaders(response.headers);+ for (const [name, value] of Object.entries(corsHeaders)) {+ headers.set(name, value);+ }+ appendVaryHeader(headers, "Origin");++ return new Response(response.body, {+ status: response.status,+ statusText: response.statusText,+ headers,+ });+};++type BuilderLogout = (+ request: Request,+ options: { redirectTo: string }+) => Promise<unknown>;++export const createBuilderLogoutAction =+ (logout: BuilderLogout) =>+ async ({ request }: ActionFunctionArgs) => {+ // IMPORTANT: This route allows cross-origin cookies to enable dashboard logout from builders.+ // Enforcing preflight by checking Content-Type to be application/json.+ // Both the preflight and actual logout response must include CORS headers+ // or browser fetch reports the project logout as failed.++ if (false === isBuilder(request)) {+ throw new Response("Not found", {+ status: 404,+ });+ }++ if (request.method === "OPTIONS") {+ const corsHeaders = getCorsHeaders(request);+ if (corsHeaders === undefined) {+ return new Response("Origin not allowed", {+ status: 403,+ });+ }++ const headers = createPrivateNoStoreHeaders(corsHeaders);+ appendVaryHeader(headers, "Origin");++ return new Response(null, {+ status: 204,+ headers,+ });+ }++ if (request.method !== "POST") {+ return withCors(+ request,+ json(+ { message: "Method not allowed" },+ {+ status: 405,+ }+ )+ );+ }++ if (request.headers.get("sec-fetch-site") === "same-origin") {+ // To prevent logout initiated from the builder iframe++ return withCors(+ request,+ new Response("Only cross-origin requests are allowed", {+ status: 403,+ })+ );+ }++ if (+ false ===+ request.headers.get("Content-Type")?.includes("application/json")+ ) {+ // Enforce preflight request, preflight is checked on allowed origin++ return withCors(+ request,+ new Response("Invalid content type, only application/json is allowed", {+ status: 415,+ })+ );+ }++ const redirectTo = `${getAuthorizationServerOrigin(request.url)}${loginPath({})}`;++ try {+ debug("Logging out");++ await logout(request, {+ redirectTo,+ });+ } catch (error) {+ if (error instanceof Response) {+ if (isRedirectResponse(error)) {+ return withCors(+ request,+ new Response(null, {+ status: 204,+ headers: error.headers,+ })+ );+ }++ return withCors(request, error);+ }++ console.error(error);+ throw error;+ }++ throw new Response("Should not reach this point", {+ status: 500,+ });+ };diff --git a/apps/builder/app/services/trcp-router.server.ts b/apps/builder/app/services/trcp-router.server.tsindex 022b24815c..2059c62233 100644--- a/apps/builder/app/services/trcp-router.server.ts+++ b/apps/builder/app/services/trcp-router.server.ts@@ -10,8 +10,10 @@ import { logoutRouter } from "./logout-router.server";import { notificationRouter } from "./notification-router.server";import { workspaceRouter } from "./workspace-router.server";import { buildRouter } from "./build-router.server";+import { apiRouter } from "./api-router.server";export const appRouter = router({+ api: apiRouter,build: buildRouter,user: userRouter,marketplace: marketplaceRouter,diff --git a/apps/builder/app/shared/$resources/assets.server.ts b/apps/builder/app/shared/$resources/assets.server.tsindex d6bc0ba5ba..bffdd290b2 100644--- a/apps/builder/app/shared/$resources/assets.server.ts+++ b/apps/builder/app/shared/$resources/assets.server.ts@@ -1,5 +1,5 @@import { json } from "@remix-run/server-runtime";-import { parseBuilderUrl } from "@webstudio-is/http-client";+import { parseBuilderUrl } from "@webstudio-is/protocol";import { loadAssetsByProject } from "@webstudio-is/asset-uploader/index.server";import { toRuntimeAsset } from "@webstudio-is/sdk";import { isBuilder } from "../router-utils";diff --git a/apps/builder/app/shared/$resources/current-date.server.ts b/apps/builder/app/shared/$resources/current-date.server.tsindex 505579579a..fe82a6e3aa 100644--- a/apps/builder/app/shared/$resources/current-date.server.ts+++ b/apps/builder/app/shared/$resources/current-date.server.ts@@ -1,5 +1,5 @@import { json } from "@remix-run/server-runtime";-import { parseBuilderUrl } from "@webstudio-is/http-client";+import { parseBuilderUrl } from "@webstudio-is/protocol";import { isBuilder } from "../router-utils";/**diff --git a/apps/builder/app/shared/$resources/sitemap.xml.server.ts b/apps/builder/app/shared/$resources/sitemap.xml.server.tsindex 2ca651dabd..4d4604a179 100644--- a/apps/builder/app/shared/$resources/sitemap.xml.server.ts+++ b/apps/builder/app/shared/$resources/sitemap.xml.server.ts@@ -1,7 +1,7 @@import { json } from "@remix-run/server-runtime";import { parsePages } from "@webstudio-is/project-build/index.server";import { getStaticSiteMapXml } from "@webstudio-is/sdk";-import { parseBuilderUrl } from "@webstudio-is/http-client";+import { parseBuilderUrl } from "@webstudio-is/protocol";import { isBuilder } from "../router-utils";import { createContext } from "../context.server";diff --git a/apps/builder/app/shared/breakpoints-utils.test.ts b/apps/builder/app/shared/breakpoints-utils.test.tsdeleted file mode 100644index b4456f651f..0000000000--- a/apps/builder/app/shared/breakpoints-utils.test.ts+++ /dev/null@@ -1,392 +0,0 @@-import { describe, test, expect } from "vitest";-import {- isBaseBreakpoint,- groupBreakpoints,- buildMergedBreakpointIds,- findClosestBreakpoint,- hasReachedBreakpointLimit,- maxBreakpoints,-} from "./breakpoints-utils";-import type { Breakpoint, Breakpoints } from "@webstudio-is/sdk";--describe("isBaseBreakpoint", () => {- test("returns true for breakpoint without min or max width", () => {- expect(isBaseBreakpoint({})).toBe(true);- expect(isBaseBreakpoint({ minWidth: undefined, maxWidth: undefined })).toBe(- true- );- });-- test("returns false for breakpoint with min width", () => {- expect(isBaseBreakpoint({ minWidth: 768 })).toBe(false);- });-- test("returns false for breakpoint with max width", () => {- expect(isBaseBreakpoint({ maxWidth: 991 })).toBe(false);- });-- test("returns false for breakpoint with both min and max width", () => {- expect(isBaseBreakpoint({ minWidth: 768, maxWidth: 991 })).toBe(false);- });-});--describe("groupBreakpoints", () => {- test("groups breakpoints in UI order: min-width (desc), base, max-width (desc)", () => {- const initial = [- { minWidth: 1920 },- { minWidth: 1440 },- { minWidth: 1280 },- {},- { maxWidth: 991 },- { maxWidth: 767 },- { maxWidth: 479 },- ];- const result = groupBreakpoints(initial);- expect(result.widthBased).toStrictEqual([- { minWidth: 1920 },- { minWidth: 1440 },- { minWidth: 1280 },- {},- { maxWidth: 991 },- { maxWidth: 767 },- { maxWidth: 479 },- ]);- expect(result.custom).toStrictEqual([]);- });-- test("handles unsorted input", () => {- const initial = [- { maxWidth: 479 },- { minWidth: 1920 },- {},- { maxWidth: 991 },- { minWidth: 1280 },- ];- const result = groupBreakpoints(initial);- expect(result.widthBased).toStrictEqual([- { minWidth: 1920 },- { minWidth: 1280 },- {},- { maxWidth: 991 },- { maxWidth: 479 },- ]);- expect(result.custom).toStrictEqual([]);- });-- test("handles only min-width breakpoints", () => {- const initial = [{ minWidth: 768 }, { minWidth: 1024 }];- const result = groupBreakpoints(initial);- expect(result.widthBased).toStrictEqual([- { minWidth: 1024 },- { minWidth: 768 },- ]);- expect(result.custom).toStrictEqual([]);- });-- test("handles only max-width breakpoints", () => {- const initial = [{ maxWidth: 991 }, { maxWidth: 479 }];- const result = groupBreakpoints(initial);- expect(result.widthBased).toStrictEqual([- { maxWidth: 991 },- { maxWidth: 479 },- ]);- expect(result.custom).toStrictEqual([]);- });-- test("handles only base breakpoint", () => {- const initial = [{}];- const result = groupBreakpoints(initial);- expect(result.widthBased).toStrictEqual([{}]);- expect(result.custom).toStrictEqual([]);- });-- test("handles empty array", () => {- const result = groupBreakpoints([]);- expect(result.widthBased).toStrictEqual([]);- expect(result.custom).toStrictEqual([]);- });-- test("separates custom condition breakpoints from width-based", () => {- const initial = [- { minWidth: 1920 },- { condition: "orientation: portrait" },- { minWidth: 1280 },- {},- { condition: "hover: hover" },- { maxWidth: 991 },- ];- const result = groupBreakpoints(initial);- expect(result.widthBased).toStrictEqual([- { minWidth: 1920 },- { minWidth: 1280 },- {},- { maxWidth: 991 },- ]);- expect(result.custom).toStrictEqual([- { condition: "orientation: portrait" },- { condition: "hover: hover" },- ]);- });-});--describe("buildMergedBreakpointIds", () => {- test("merges breakpoints with matching minWidth, maxWidth, and label", () => {- const fragmentBreakpoints: Breakpoint[] = [- { id: "frag-1", minWidth: 768, label: "Tablet" },- { id: "frag-2", maxWidth: 479, label: "Mobile" },- { id: "frag-3", minWidth: 1024, label: "Desktop" },- ];-- const existingBreakpoints: Breakpoints = new Map([- ["exist-1", { id: "exist-1", minWidth: 768, label: "Tablet" }],- ["exist-2", { id: "exist-2", maxWidth: 991, label: "Small Desktop" }],- ["exist-3", { id: "exist-3", maxWidth: 479, label: "Mobile" }],- ]);-- const result = buildMergedBreakpointIds(- fragmentBreakpoints,- existingBreakpoints- );-- expect(result.size).toBe(2);- expect(result.get("frag-1")).toBe("exist-1"); // Tablet matches- expect(result.get("frag-2")).toBe("exist-3"); // Mobile matches- expect(result.has("frag-3")).toBe(false); // Desktop doesn't match- });-- test("returns empty map when no matches found", () => {- const fragmentBreakpoints: Breakpoint[] = [- { id: "frag-1", minWidth: 1440, label: "Large Desktop" },- ];-- const existingBreakpoints: Breakpoints = new Map([- ["exist-1", { id: "exist-1", minWidth: 768, label: "Tablet" }],- ]);-- const result = buildMergedBreakpointIds(- fragmentBreakpoints,- existingBreakpoints- );-- expect(result.size).toBe(0);- });-- test("matches base breakpoints (no min/max)", () => {- const fragmentBreakpoints: Breakpoint[] = [- { id: "frag-base", label: "Base" },- ];-- const existingBreakpoints: Breakpoints = new Map([- ["exist-base", { id: "exist-base", label: "Base" }],- ]);-- const result = buildMergedBreakpointIds(- fragmentBreakpoints,- existingBreakpoints- );-- expect(result.size).toBe(1);- expect(result.get("frag-base")).toBe("exist-base");- });-- test("handles empty fragment breakpoints", () => {- const fragmentBreakpoints: Breakpoint[] = [];- const existingBreakpoints: Breakpoints = new Map([- ["exist-1", { id: "exist-1", minWidth: 768, label: "Tablet" }],- ]);-- const result = buildMergedBreakpointIds(- fragmentBreakpoints,- existingBreakpoints- );-- expect(result.size).toBe(0);- });-- test("handles empty existing breakpoints", () => {- const fragmentBreakpoints: Breakpoint[] = [- { id: "frag-1", minWidth: 768, label: "Tablet" },- ];- const existingBreakpoints: Breakpoints = new Map();-- const result = buildMergedBreakpointIds(- fragmentBreakpoints,- existingBreakpoints- );-- expect(result.size).toBe(0);- });-- test("merges only first matching breakpoint", () => {- const fragmentBreakpoints: Breakpoint[] = [- { id: "frag-1", minWidth: 768, label: "Tablet" },- ];-- const existingBreakpoints: Breakpoints = new Map([- ["exist-1", { id: "exist-1", minWidth: 768, label: "Tablet" }],- ["exist-2", { id: "exist-2", minWidth: 768, label: "Tablet" }],- ]);-- const result = buildMergedBreakpointIds(- fragmentBreakpoints,- existingBreakpoints- );-- expect(result.size).toBe(1);- expect(result.get("frag-1")).toBe("exist-1"); // Should match first one- });-- test("does not merge breakpoints with different labels", () => {- const fragmentBreakpoints: Breakpoint[] = [- { id: "frag-1", minWidth: 768, label: "Tablet" },- ];-- const existingBreakpoints: Breakpoints = new Map([- ["exist-1", { id: "exist-1", minWidth: 768, label: "iPad" }],- ]);-- const result = buildMergedBreakpointIds(- fragmentBreakpoints,- existingBreakpoints- );-- // equalMedia only checks minWidth/maxWidth, not labels- // So breakpoints with same dimensions but different labels will still merge- expect(result.size).toBe(1);- expect(result.get("frag-1")).toBe("exist-1");- });-- test("keeps total breakpoints within max count by merging overflow into closest existing breakpoint", () => {- const existingBreakpoints: Breakpoints = new Map([- ["base", { id: "base", label: "" }],- ["desktop", { id: "desktop", label: "Desktop", minWidth: 1200 }],- ["tablet", { id: "tablet", label: "Tablet", maxWidth: 900 }],- ["mobile", { id: "mobile", label: "Mobile", maxWidth: 480 }],- ["wide", { id: "wide", label: "Wide", minWidth: 1600 }],- ["large", { id: "large", label: "Large", minWidth: 2000 }],- ["print", { id: "print", label: "Print", condition: "print" }],- ["hover", { id: "hover", label: "Hover", condition: "hover: hover" }],- ]);- const fragmentBreakpoints: Breakpoint[] = [- { id: "frag-existing", label: "Same", maxWidth: 480 },- { id: "frag-new", label: "New", minWidth: 1440 },- { id: "frag-overflow", label: "Overflow", maxWidth: 760 },- ];-- const result = buildMergedBreakpointIds(- fragmentBreakpoints,- existingBreakpoints,- { maxBreakpointCount: maxBreakpoints }- );-- expect(result.get("frag-existing")).toBe("mobile");- expect(result.has("frag-new")).toBe(false);- expect(result.get("frag-overflow")).toBe("tablet");- });-- test("merges all new breakpoints when existing non-base breakpoints are already at the max count", () => {- const existingBreakpoints: Breakpoints = new Map([- ["base", { id: "base", label: "" }],- ["0", { id: "0", label: "320", maxWidth: 320 }],- ["1", { id: "1", label: "480", maxWidth: 480 }],- ["2", { id: "2", label: "768", maxWidth: 768 }],- ["3", { id: "3", label: "1024", maxWidth: 1024 }],- ["4", { id: "4", label: "1280", minWidth: 1280 }],- ["5", { id: "5", label: "1440", minWidth: 1440 }],- ["6", { id: "6", label: "1920", minWidth: 1920 }],- ["7", { id: "7", label: "2560", minWidth: 2560 }],- ]);-- const result = buildMergedBreakpointIds(- [{ id: "frag", label: "New", minWidth: 1500 }],- existingBreakpoints,- { maxBreakpointCount: maxBreakpoints }- );-- expect(result.get("frag")).toBe("5");- });-- test("reports when breakpoint is merged because of max count", () => {- const existingBreakpoints: Breakpoints = new Map([- ["base", { id: "base", label: "" }],- ["0", { id: "0", label: "320", maxWidth: 320 }],- ["1", { id: "1", label: "480", maxWidth: 480 }],- ["2", { id: "2", label: "768", maxWidth: 768 }],- ["3", { id: "3", label: "1024", maxWidth: 1024 }],- ["4", { id: "4", label: "1280", minWidth: 1280 }],- ["5", { id: "5", label: "1440", minWidth: 1440 }],- ["6", { id: "6", label: "1920", minWidth: 1920 }],- ["7", { id: "7", label: "2560", minWidth: 2560 }],- ]);- let mergeCount = 0;-- buildMergedBreakpointIds(- [{ id: "frag", label: "New", minWidth: 1500 }],- existingBreakpoints,- {- maxBreakpointCount: maxBreakpoints,- onBreakpointMergedDueToLimit: () => {- mergeCount += 1;- },- }- );-- expect(mergeCount).toBe(1);- });-- test("does not count base breakpoint against max count", () => {- const existingBreakpoints: Breakpoints = new Map([- ["base", { id: "base", label: "" }],- ["0", { id: "0", label: "320", maxWidth: 320 }],- ["1", { id: "1", label: "480", maxWidth: 480 }],- ["2", { id: "2", label: "768", maxWidth: 768 }],- ["3", { id: "3", label: "1024", maxWidth: 1024 }],- ["4", { id: "4", label: "1280", minWidth: 1280 }],- ["5", { id: "5", label: "1440", minWidth: 1440 }],- ["6", { id: "6", label: "1920", minWidth: 1920 }],- ]);-- const result = buildMergedBreakpointIds(- [{ id: "frag", label: "New", minWidth: 1500 }],- existingBreakpoints,- { maxBreakpointCount: maxBreakpoints }- );-- expect(result.has("frag")).toBe(false);- });-});--describe("findClosestBreakpoint", () => {- test("finds the closest width-based breakpoint", () => {- const result = findClosestBreakpoint(- { id: "new", label: "New", maxWidth: 760 },- [- { id: "base", label: "" },- { id: "mobile", label: "Mobile", maxWidth: 480 },- { id: "tablet", label: "Tablet", maxWidth: 768 },- ]- );-- expect(result?.id).toBe("tablet");- });-- test("falls back to base for condition breakpoints without comparable widths", () => {- const result = findClosestBreakpoint(- { id: "new", label: "Dark", condition: "prefers-color-scheme: dark" },- [- { id: "base", label: "" },- { id: "hover", label: "Hover", condition: "hover: hover" },- ]- );-- expect(result?.id).toBe("base");- });-});--describe("hasReachedBreakpointLimit", () => {- test("counts saved and pending breakpoints", () => {- expect(hasReachedBreakpointLimit(maxBreakpoints - 1)).toBe(false);- expect(hasReachedBreakpointLimit(maxBreakpoints)).toBe(true);- expect(hasReachedBreakpointLimit(maxBreakpoints - 1, 1)).toBe(true);- });-});diff --git a/apps/builder/app/shared/breakpoints-utils.ts b/apps/builder/app/shared/breakpoints-utils.tsindex a35bf2e4e4..0ee84b4ccd 100644--- a/apps/builder/app/shared/breakpoints-utils.ts+++ b/apps/builder/app/shared/breakpoints-utils.ts@@ -1,151 +1,2 @@-import { compareMedia, equalMedia } from "@webstudio-is/css-engine";-import type { Breakpoint, Breakpoints } from "@webstudio-is/sdk";--export const maxBreakpoints = 8;--export const breakpointLimitWarning =- "You can have up to 8 breakpoints. More breakpoints can make the project harder to maintain.";--export const breakpointPasteLimitWarning = `${breakpointLimitWarning} Pasted breakpoint styles were merged into the closest existing breakpoints.`;--export const hasReachedBreakpointLimit = (- breakpointCount: number,- pendingBreakpointCount = 0-) => breakpointCount + pendingBreakpointCount >= maxBreakpoints;--/**- * Check if a breakpoint is the base breakpoint (no min or max width).- * Note: Does not check for custom conditions.- */-export const isBaseBreakpoint = (breakpoint: {- minWidth?: number;- maxWidth?: number;-}) => breakpoint.minWidth === undefined && breakpoint.maxWidth === undefined;--/**- * Group breakpoints into width-based and custom condition categories.- * Width-based breakpoints are ordered: min-width (largest to smallest), base, max-width (largest to smallest).- * Custom condition breakpoints are kept separate and not sorted.- *- * Note: minWidth/maxWidth and condition are mutually exclusive - a breakpoint has either- * width-based properties OR a custom condition, never both.- */-export const groupBreakpoints = <- T extends { minWidth?: number; maxWidth?: number; condition?: string },->(- breakpoints: Array<T>-): { widthBased: Array<T>; custom: Array<T> } => {- const custom = breakpoints.filter(- (breakpoint) => breakpoint.condition !== undefined- );- const widthBased = breakpoints.filter(- (breakpoint) => breakpoint.condition === undefined- );-- const sorted = [...widthBased].sort(compareMedia);- const maxs = sorted.filter((breakpoint) => breakpoint.maxWidth !== undefined);- const mins = sorted- .filter((breakpoint) => breakpoint.minWidth !== undefined)- .reverse();- const base = sorted.filter(isBaseBreakpoint);-- return {- widthBased: [...mins, ...base, ...maxs],- custom,- };-};--const getBreakpointWidthValue = (breakpoint: Breakpoint) => {- if (breakpoint.minWidth !== undefined && breakpoint.maxWidth !== undefined) {- return (breakpoint.minWidth + breakpoint.maxWidth) / 2;- }- return breakpoint.minWidth ?? breakpoint.maxWidth;-};--export const findClosestBreakpoint = (- breakpoint: Breakpoint,- existingBreakpoints: Breakpoint[]-): Breakpoint | undefined => {- let closestBreakpoint: Breakpoint | undefined;- let closestDistance = Number.POSITIVE_INFINITY;- const widthValue = getBreakpointWidthValue(breakpoint);-- if (widthValue !== undefined) {- for (const existingBreakpoint of existingBreakpoints) {- const existingWidthValue = getBreakpointWidthValue(existingBreakpoint);- if (existingWidthValue === undefined) {- continue;- }- const distance = Math.abs(widthValue - existingWidthValue);- if (distance < closestDistance) {- closestBreakpoint = existingBreakpoint;- closestDistance = distance;- }- }- }-- return (- closestBreakpoint ??- existingBreakpoints.find(- (existingBreakpoint) =>- existingBreakpoint.condition === undefined &&- isBaseBreakpoint(existingBreakpoint)- ) ??- existingBreakpoints[0]- );-};--/**- * Build a map of merged breakpoint IDs from fragment breakpoints to existing breakpoints.- * Breakpoints are merged when they have matching minWidth, maxWidth, condition, and label.- * Note: minWidth/maxWidth and condition are mutually exclusive.- *- * @param fragmentBreakpoints - Breakpoints from the fragment being inserted- * @param existingBreakpoints - Existing breakpoints in the project- * @param options.maxBreakpointCount - When provided, overflow fragment breakpoints are merged into the closest existing breakpoint.- * @returns Map of fragment breakpoint IDs to existing breakpoint IDs- */-export const buildMergedBreakpointIds = (- fragmentBreakpoints: Breakpoint[],- existingBreakpoints: Breakpoints,- options?: {- maxBreakpointCount?: number;- onBreakpointMergedDueToLimit?: () => void;- }-): Map<Breakpoint["id"], Breakpoint["id"]> => {- const mergedBreakpointIds = new Map<Breakpoint["id"], Breakpoint["id"]>();- const acceptedBreakpoints = Array.from(existingBreakpoints.values());-- for (const newBreakpoint of fragmentBreakpoints) {- for (const breakpoint of acceptedBreakpoints) {- if (equalMedia(breakpoint, newBreakpoint)) {- mergedBreakpointIds.set(newBreakpoint.id, breakpoint.id);- break;- }- }- if (mergedBreakpointIds.has(newBreakpoint.id)) {- continue;- }-- if (- options?.maxBreakpointCount !== undefined &&- acceptedBreakpoints.length >= options.maxBreakpointCount + 1- ) {- const closestBreakpoint = findClosestBreakpoint(- newBreakpoint,- acceptedBreakpoints- );- if (closestBreakpoint !== undefined) {- mergedBreakpointIds.set(newBreakpoint.id, closestBreakpoint.id);- options.onBreakpointMergedDueToLimit?.();- }- continue;- }-- acceptedBreakpoints.push(newBreakpoint);- }- return mergedBreakpointIds;-};-// Doesn't make sense to allow resizing the canvas lower than this.export const minCanvasWidth = 240;diff --git a/apps/builder/app/shared/breakpoints/index.ts b/apps/builder/app/shared/breakpoints/index.tsindex e059e9020a..99a4051637 100644--- a/apps/builder/app/shared/breakpoints/index.ts+++ b/apps/builder/app/shared/breakpoints/index.ts@@ -1,13 +1,2 @@-export {- isBaseBreakpoint,- groupBreakpoints,- buildMergedBreakpointIds,- breakpointLimitWarning,- breakpointPasteLimitWarning,- findClosestBreakpoint,- hasReachedBreakpointLimit,- maxBreakpoints,- minCanvasWidth,-} from "../breakpoints-utils";export * from "./select-breakpoint-by-order";export * from "./stores";diff --git a/apps/builder/app/shared/breakpoints/select-breakpoint-by-order.ts b/apps/builder/app/shared/breakpoints/select-breakpoint-by-order.tsindex 42b2d021b0..721e499715 100644--- a/apps/builder/app/shared/breakpoints/select-breakpoint-by-order.ts+++ b/apps/builder/app/shared/breakpoints/select-breakpoint-by-order.ts@@ -1,4 +1,4 @@-import { groupBreakpoints } from "../breakpoints-utils";+import { groupBreakpoints } from "@webstudio-is/project-build/runtime/breakpoints";import { $selectedBreakpointId } from "../nano-states";import { $breakpoints } from "~/shared/sync/data-stores";import { setCanvasWidth } from "~/builder/shared/calc-canvas-width";diff --git a/apps/builder/app/shared/component-metas.server.test.ts b/apps/builder/app/shared/component-metas.server.test.tsnew file mode 100644index 0000000000..9e952dce3b--- /dev/null+++ b/apps/builder/app/shared/component-metas.server.test.ts@@ -0,0 +1,12 @@+import { describe, expect, test } from "vitest";+import { coreMetas } from "@webstudio-is/sdk";+import { componentMetas } from "./component-metas.server";++describe("component metas", () => {+ test("combines core and component package metadata", () => {+ for (const component of Object.keys(coreMetas)) {+ expect(componentMetas.has(component)).toBe(true);+ }+ expect(componentMetas.size).toBeGreaterThan(Object.keys(coreMetas).length);+ });+});diff --git a/apps/builder/app/shared/component-metas.server.ts b/apps/builder/app/shared/component-metas.server.tsnew file mode 100644index 0000000000..2bc1c92e6c--- /dev/null+++ b/apps/builder/app/shared/component-metas.server.ts@@ -0,0 +1,17 @@+import {+ coreMetas,+ type Instance,+ type WsComponentMeta,+} from "@webstudio-is/sdk";+import * as baseComponentMetas from "@webstudio-is/sdk-components-react/metas";+import * as animationComponentMetas from "@webstudio-is/sdk-components-animation/metas";+import * as radixComponentMetas from "@webstudio-is/sdk-components-react-radix/metas";++export const componentMetas = new Map<Instance["component"], WsComponentMeta>(+ Object.entries({+ ...coreMetas,+ ...baseComponentMetas,+ ...animationComponentMetas,+ ...radixComponentMetas,+ })+);diff --git a/apps/builder/app/shared/content-mode-copy-policy.test.ts b/apps/builder/app/shared/content-mode-copy-policy.test.tsnew file mode 100644index 0000000000..c5d2c429ab--- /dev/null+++ b/apps/builder/app/shared/content-mode-copy-policy.test.ts@@ -0,0 +1,77 @@+import { expect, test } from "vitest";+import type {+ Instance,+ Prop,+ WebstudioFragment,+ WsComponentMeta,+} from "@webstudio-is/sdk";+import { isFragmentContentModeCopyableProp } from "./content-mode-copy-policy";++test("checks whether fragment props are copyable in content mode", () => {+ const prop: Prop = {+ id: "prop-alt",+ instanceId: "image",+ name: "alt",+ type: "string",+ value: "Logo",+ };+ const instance: Instance = {+ type: "instance",+ id: "image",+ component: "Image",+ children: [],+ };+ const fragment: WebstudioFragment = {+ children: [{ type: "id", value: "image" }],+ instances: [instance],+ props: [prop],+ assets: [],+ dataSources: [],+ resources: [],+ breakpoints: [],+ styleSourceSelections: [],+ styleSources: [],+ styles: [],+ };+ const metas = new Map<string, WsComponentMeta>([+ [+ "Image",+ {+ label: "Image",+ props: {+ alt: {+ type: "string",+ control: "text",+ required: false,+ contentMode: true,+ },+ },+ },+ ],+ ]);++ expect(+ isFragmentContentModeCopyableProp({+ prop,+ fragment,+ fragmentInstances: new Map([["image", instance]]),+ styleSources: new Map(),+ metas,+ })+ ).toBe(true);++ expect(+ isFragmentContentModeCopyableProp({+ prop: { ...prop, id: "prop-expression", type: "expression", value: "x" },+ fragment: {+ ...fragment,+ props: [+ { ...prop, id: "prop-expression", type: "expression", value: "x" },+ ],+ },+ fragmentInstances: new Map([["image", instance]]),+ styleSources: new Map(),+ metas,+ })+ ).toBe(false);+});diff --git a/apps/builder/app/shared/content-mode-copy-policy.ts b/apps/builder/app/shared/content-mode-copy-policy.tsnew file mode 100644index 0000000000..49982e7b23--- /dev/null+++ b/apps/builder/app/shared/content-mode-copy-policy.ts@@ -0,0 +1,38 @@+import {+ getContentModeCapabilities,+ isContentModeCopyableProp,+} from "@webstudio-is/project/content-mode-permissions";+import type {+ Instance,+ Prop,+ WebstudioData,+ WebstudioFragment,+ WsComponentMeta,+} from "@webstudio-is/sdk";++export const isFragmentContentModeCopyableProp = ({+ prop,+ fragment,+ fragmentInstances,+ styleSources,+ metas,+}: {+ prop: Prop;+ fragment: WebstudioFragment;+ fragmentInstances: Map<Instance["id"], Instance>;+ styleSources: WebstudioData["styleSources"];+ metas: Map<string, WsComponentMeta>;+}) => {+ const capabilities = getContentModeCapabilities({+ instances: fragmentInstances,+ metas,+ props: new Map(fragment.props.map((prop) => [prop.id, prop])),+ styleSources,+ contentRootIds: new Set(+ fragment.children+ .filter((child) => child.type === "id")+ .map((child) => child.value)+ ),+ });+ return isContentModeCopyableProp({ capabilities, prop });+};diff --git a/apps/builder/app/shared/context.server.test.ts b/apps/builder/app/shared/context.server.test.tsindex c304643330..170f353f2e 100644--- a/apps/builder/app/shared/context.server.test.ts+++ b/apps/builder/app/shared/context.server.test.ts@@ -65,10 +65,6 @@ vi.mock("./router-utils", () => ({isCanvas,}));-vi.mock("@webstudio-is/http-client", () => ({- parseBuilderUrl: vi.fn(),-}));-import { extractAuthFromRequest } from "./context.server";describe("extractAuthFromRequest", () => {diff --git a/apps/builder/app/shared/context.server.ts b/apps/builder/app/shared/context.server.tsindex 94aaeb24a8..74ec42cc75 100644--- a/apps/builder/app/shared/context.server.ts+++ b/apps/builder/app/shared/context.server.ts@@ -15,7 +15,7 @@ import { builderAuthenticator } from "~/services/builder-auth.server";import { readLoginSessionBloomFilter } from "~/services/session.server";import type { BloomFilter } from "~/services/bloom-filter.server";import { isBuilder, isCanvas } from "./router-utils";-import { parseBuilderUrl } from "@webstudio-is/http-client";+import { parseBuilderUrl } from "@webstudio-is/protocol";import {apiClient,apiClientHeader,diff --git a/apps/builder/app/shared/copy-paste/plugin-html.ts b/apps/builder/app/shared/copy-paste/plugin-html.tsindex c9bd238b10..05bf9c49c5 100644--- a/apps/builder/app/shared/copy-paste/plugin-html.ts+++ b/apps/builder/app/shared/copy-paste/plugin-html.ts@@ -5,7 +5,7 @@ import { generateFragmentFromTailwind } from "../tailwind/tailwind";import { denormalizeSrcProps } from "./asset-upload";import type { Plugin } from "./copy-paste";import { builderApi } from "../builder-api";-import { breakpointPasteLimitWarning } from "../breakpoints";+import { breakpointPasteLimitWarning } from "@webstudio-is/project-build/runtime/breakpoints";const inceptionMark = `<!-- @webstudio/inception/1 -->`;diff --git a/apps/builder/app/shared/copy-paste/plugin-instance.ts b/apps/builder/app/shared/copy-paste/plugin-instance.tsindex 047b9e6770..02b4098456 100644--- a/apps/builder/app/shared/copy-paste/plugin-instance.ts+++ b/apps/builder/app/shared/copy-paste/plugin-instance.ts@@ -1,9 +1,9 @@import {+ detectFragmentTokenConflicts,extractWebstudioFragment,insertWebstudioFragmentCopy,-} from "../instance-utils/fragment";+} from "@webstudio-is/project-build/runtime/fragment";import { findClosestInsertable } from "../instance-utils/insert";-import { detectFragmentTokenConflicts } from "../instance-utils/fragment";import {updateInstanceData,updateWebstudioData,@@ -27,6 +27,7 @@ import {} from "@webstudio-is/sdk";import { $instances, $project } from "~/shared/sync/data-stores";import type { InstanceSelector } from "../instance-utils/tree";+import { findChildReferenceIndex } from "@webstudio-is/project-build/runtime/instances";import {deleteInstanceMutable,sortInstancePathsForChildMutation,@@ -39,10 +40,10 @@ import {$selectedInstanceSelector,selectInstances,} from "~/shared/nano-states";-import { findAvailableVariables } from "../data-variables";+import { findAvailableVariables } from "@webstudio-is/project-build/runtime/data";import { builderApi } from "../builder-api";import type { Plugin } from "./copy-paste";-import { breakpointPasteLimitWarning } from "../breakpoints";+import { breakpointPasteLimitWarning } from "@webstudio-is/project-build/runtime/breakpoints";const version = "@webstudio/instance/v0.1";const multiRootVersion = "@webstudio/instances/v0.1";@@ -206,14 +207,6 @@ const getPortalFragmentSelector = (return [instance.children[0].value, ...instanceSelector];};-const getIdChildIndex = (- children: Instance["children"],- instanceId: Instance["id"]-) =>- children.findIndex(- (child) => child.type === "id" && child.value === instanceId- );-const getCommonAncestorSelector = (instanceSelectors: InstanceSelector[]): undefined | InstanceSelector => {@@ -264,7 +257,7 @@ const findMultiSelectionInsertable = (return;}const selectedSiblingIndexes = selectedPaths.map((path) =>- getIdChildIndex(parentInstance.children, path[0].instance.id)+ findChildReferenceIndex(parentInstance.children, path[0].instance.id));if (selectedSiblingIndexes.includes(-1)) {return;@@ -386,7 +379,10 @@ const findPasteTarget = (data: InstanceData): undefined | Insertable => {};const resolveFragmentTokenConflicts = async (fragment: WebstudioFragment) => {- const conflicts = detectFragmentTokenConflicts({ fragment });+ const conflicts = detectFragmentTokenConflicts({+ fragment,+ targetData: getWebstudioData(),+ });return conflicts.length > 0? await builderApi.showTokenConflictDialog(conflicts): "theirs";diff --git a/apps/builder/app/shared/copy-paste/plugin-markdown.ts b/apps/builder/app/shared/copy-paste/plugin-markdown.tsindex 3cab7261a8..bdd648d46d 100644--- a/apps/builder/app/shared/copy-paste/plugin-markdown.ts+++ b/apps/builder/app/shared/copy-paste/plugin-markdown.ts@@ -5,7 +5,7 @@ import { denormalizeSrcProps } from "./asset-upload";import { generateFragmentFromHtml } from "../html";import type { Plugin } from "./copy-paste";import { builderApi } from "../builder-api";-import { breakpointPasteLimitWarning } from "../breakpoints";+import { breakpointPasteLimitWarning } from "@webstudio-is/project-build/runtime/breakpoints";const parse = (clipboardData: string) => {const html = micromark(clipboardData, "utf-8", {diff --git a/apps/builder/app/shared/copy-paste/plugin-page.ts b/apps/builder/app/shared/copy-paste/plugin-page.tsindex 83d9c0584b..f4d6ca6b53 100644--- a/apps/builder/app/shared/copy-paste/plugin-page.ts+++ b/apps/builder/app/shared/copy-paste/plugin-page.ts@@ -11,8 +11,8 @@ import {type Page,type PageTemplate,} from "@webstudio-is/sdk";-import { $pages } from "~/shared/sync/data-stores";-import { detectFragmentTokenConflicts } from "../instance-utils/fragment";+import { $pages, $project } from "~/shared/sync/data-stores";+import { detectFragmentTokenConflicts } from "@webstudio-is/project-build/runtime/fragment";import { builderApi } from "../builder-api";import {createFolderCopyData,@@ -24,11 +24,11 @@ import {type FolderCopyData,type PageCopyData,type TemplateCopyData,-} from "../page-utils";+} from "@webstudio-is/project-build/runtime/page-copy";import { $selectedPage } from "../nano-states";import { getPageActionTarget } from "../page-action-target";import type { Plugin } from "./copy-paste";-import { breakpointPasteLimitWarning } from "../breakpoints";+import { breakpointPasteLimitWarning } from "@webstudio-is/project-build/runtime/breakpoints";const version = "@webstudio/page/v0.1";@@ -214,9 +214,15 @@ export const handlePastePage = async (}try {+ const targetData = getWebstudioData();+ const projectId = $project.get()?.id;+ if (projectId === undefined) {+ return true;+ }const conflicts = collectPageLikeItems(item).flatMap((item) =>detectFragmentTokenConflicts({fragment: mergeWebstudioFragments(item.rootFragment, item.bodyFragment),+ targetData,}));const conflictResolution =@@ -233,6 +239,7 @@ export const handlePastePage = async (newId = insertPageCopyFromFragmentsMutable({source: item,target: { data, folderId },+ projectId,conflictResolution,onBreakpointLimitMerge,});@@ -242,6 +249,7 @@ export const handlePastePage = async (newId = insertTemplateCopyFromFragmentsMutable({source: item,target: { data },+ projectId,conflictResolution,onBreakpointLimitMerge,});@@ -250,6 +258,7 @@ export const handlePastePage = async (newId = insertFolderCopyFromDataMutable({source: item,target: { data, parentFolderId: folderId },+ projectId,conflictResolution,onBreakpointLimitMerge,});diff --git a/apps/builder/app/shared/copy-paste/plugin-webflow/plugin-webflow.ts b/apps/builder/app/shared/copy-paste/plugin-webflow/plugin-webflow.tsindex 97d807e29f..34e707259e 100644--- a/apps/builder/app/shared/copy-paste/plugin-webflow/plugin-webflow.ts+++ b/apps/builder/app/shared/copy-paste/plugin-webflow/plugin-webflow.ts@@ -3,7 +3,7 @@ import {findClosestInsertable,insertInstanceChildrenMutable,} from "../../instance-utils/insert";-import { insertWebstudioFragmentCopy } from "../../instance-utils/fragment";+import { insertWebstudioFragmentCopy } from "@webstudio-is/project-build/runtime/fragment";import { updateWebstudioData } from "../../instance-utils/data";import { $project } from "~/shared/sync/data-stores";import {@@ -19,9 +19,9 @@ import { addStyles } from "./styles";import { builderApi } from "~/shared/builder-api";import { denormalizeSrcProps } from "../asset-upload";import { nanoHash } from "~/shared/nano-hash";-import { findAvailableVariables } from "~/shared/data-variables";+import { findAvailableVariables } from "@webstudio-is/project-build/runtime/data";import type { Plugin } from "../copy-paste";-import { breakpointPasteLimitWarning } from "~/shared/breakpoints";+import { breakpointPasteLimitWarning } from "@webstudio-is/project-build/runtime/breakpoints";const { toast } = builderApi;diff --git a/apps/builder/app/shared/data-variables.ts b/apps/builder/app/shared/data-variables.tsdeleted file mode 100644index c0606fc89d..0000000000--- a/apps/builder/app/shared/data-variables.ts+++ /dev/null@@ -1,708 +0,0 @@-import {- type DataSource,- type DataSources,- type Instance,- type Instances,- type Props,- type Resource,- type Resources,- type WebstudioData,- type Pages,- ROOT_INSTANCE_ID,- SYSTEM_VARIABLE_ID,- collectionComponent,- decodeDataVariableId,- decodeDataSourceVariable,- encodeDataVariableId,- encodeDataSourceVariable,- findTreeInstanceIds,- findTreeInstanceIdsExcludingSlotDescendants,- getAllPages,- getExpressionIdentifiers,- systemParameter,- transpileExpression,-} from "@webstudio-is/sdk";-import {- createJsonStringifyProxy,- isPlainObject,-} from "@webstudio-is/sdk/runtime";-import { setUnion } from "./shim";--const allowedJsChars = /[A-Za-z_]/;-const compiledExpressionCacheLimit = 10_000;-type CompiledExpression = (variables: {- get: (key: DataSource["name"]) => unknown;- // Dynamic expressions intentionally preserve the historical `any` result.- // eslint-disable-next-line @typescript-eslint/no-explicit-any-}) => any;--const compiledExpressionCache = new Map<string, CompiledExpression>();--const getCompiledExpression = (expression: string) => {- const cached = compiledExpressionCache.get(expression);- if (cached) {- return cached;- }-- const usedVariables = new Map<string, DataSource["name"]>();- const transpiled = transpileExpression({- expression,- executable: true,- replaceVariable: (identifier) => {- const id = decodeDataVariableId(identifier);- if (id) {- usedVariables.set(identifier, id);- } else {- // access all variable values from specified map- const name = decodeDataVariableName(identifier);- usedVariables.set(identifier, name);- }- },- });- let code = "";- // add only used variables in expression and get values- // from variables map without additional serializing of these values- for (const [identifier, name] of usedVariables) {- code += `let ${identifier} = _variables.get(${JSON.stringify(name)});\n`;- }- code += `return (${transpiled})`;-- const compiledExpression = new Function(- "_variables",- code- ) as CompiledExpression;- compiledExpressionCache.set(expression, compiledExpression);- if (compiledExpressionCache.size > compiledExpressionCacheLimit) {- const oldestExpression = compiledExpressionCache.keys().next().value;- if (oldestExpression !== undefined) {- compiledExpressionCache.delete(oldestExpression);- }- }- return compiledExpression;-};--/**- * variable names can contain any characters and- * this utility encodes data variable name into valid js identifier- * for example- * "Collection Item" -> "Collection$20$Item"- */-export const encodeDataVariableName = (name: string) => {- let encodedName = "";- for (let index = 0; index < name.length; index += 1) {- const char = name[index];- encodedName += allowedJsChars.test(char)- ? char- : `$${char.codePointAt(0)}$`;- }- return encodedName;-};--/**- * Variable name should be restorable from encoded js identifier- */-export const decodeDataVariableName = (identifier: string) => {- const name = identifier.replaceAll(/\$(\d+)\$/g, (_match, code) =>- String.fromCodePoint(code)- );- return name;-};--/**- * replace all encoded ids with encoded names- * to make expression transferrable- */-export const unsetExpressionVariables = ({- expression,- unsetNameById,-}: {- expression: string;- unsetNameById: Map<DataSource["id"], DataSource["name"]>;-}) => {- try {- return transpileExpression({- expression,- replaceVariable: (identifier) => {- const id = decodeDataVariableId(identifier);- if (id) {- const name = unsetNameById.get(id);- if (name) {- return encodeDataVariableName(name);- }- }- return identifier;- },- });- } catch {- return expression;- }-};--/**- * restore variable ids by js identifiers- */-export const restoreExpressionVariables = ({- expression,- maskedIdByName,-}: {- expression: string;- maskedIdByName: Map<DataSource["name"], DataSource["id"]>;-}) => {- try {- return transpileExpression({- expression,- replaceVariable: (identifier) => {- const name = decodeDataVariableName(identifier);- if (name) {- const id = maskedIdByName.get(name);- if (id) {- return encodeDataVariableId(id);- }- }- return identifier;- },- });- } catch {- return expression;- }-};--export const replaceDataSourcesInExpression = (- expression: string,- replacements: Map<DataSource["id"], DataSource["id"]>-) => {- return transpileExpression({- expression,- replaceVariable: (identifier) => {- const dataSourceId = decodeDataSourceVariable(identifier);- if (dataSourceId === undefined) {- return;- }- return encodeDataSourceVariable(- replacements.get(dataSourceId) ?? dataSourceId- );- },- });-};--export const computeExpression = (- expression: string,- variables: Map<DataSource["name"], unknown>-) => {- try {- /**- *- * We are using structuredClone on frozen values because, for some reason,- * the Proxy example below throws a cryptic error:- * TypeError: 'get' on proxy: property 'data' is a read-only and non-configurable- * data property on the proxy target, but the proxy did not return its actual value- * (expected '[object Array]' but got '[object Array]').- *- * ```- * const createJsonStringifyProxy = (target) => {- * return new Proxy(target, {- * get(target, prop, receiver) {- *- * console.log((prop in target), prop)- *- * const value = Reflect.get(target, prop, receiver);- *- * if (typeof value === "object" && value !== null) {- * return createJsonStringifyProxy(value);- * }- *- * return value;- * },- * });- * };- * const obj = Object.freeze({ data: [1, 2, 3, 4] });- * const proxy = createJsonStringifyProxy(obj)- * proxy.data- *- * ```- */- const proxiedVariables = new Map<DataSource["name"], unknown>();- const getVariable = (key: DataSource["name"]) => {- if (proxiedVariables.has(key)) {- return proxiedVariables.get(key);- }- const value = variables.get(key);- const proxiedValue = isPlainObject(value)- ? createJsonStringifyProxy(- Object.isFrozen(value) ? structuredClone(value) : value- )- : value;- proxiedVariables.set(key, proxiedValue);- return proxiedValue;- };-- const result = getCompiledExpression(expression)({ get: getVariable });- return result;- } catch (error) {- console.error(error);- }-};--const getParentInstanceById = (instances: Instances) => {- const parentInstanceById = new Map<Instance["id"], Instance["id"]>();- for (const instance of instances.values()) {- // interrupt lookup because slot variables cannot be passed to slot content- if (instance.component === "Slot") {- continue;- }- for (const child of instance.children) {- if (child.type === "id") {- parentInstanceById.set(child.value, instance.id);- }- }- }- return parentInstanceById;-};--const getDataSourcesByScopeInstanceId = (dataSources: DataSources) => {- const dataSourcesByScopeInstanceId = new Map<- Instance["id"],- Array<DataSource>- >();- for (const dataSource of dataSources.values()) {- const instanceId = dataSource.scopeInstanceId ?? ROOT_INSTANCE_ID;- const dataSourcesByScope =- dataSourcesByScopeInstanceId.get(instanceId) ?? [];- dataSourcesByScope.push(dataSource);- dataSourcesByScopeInstanceId.set(instanceId, dataSourcesByScope);- }- return dataSourcesByScopeInstanceId;-};--const findMaskedVariablesByInstanceId = ({- startingInstanceId,- parentInstanceById,- instances,- dataSources,- dataSourcesByScopeInstanceId = getDataSourcesByScopeInstanceId(dataSources),-}: {- startingInstanceId: Instance["id"];- parentInstanceById: Map<Instance["id"], Instance["id"]>;- instances: Instances;- dataSources: DataSources;- dataSourcesByScopeInstanceId?: Map<Instance["id"], Array<DataSource>>;-}) => {- let currentId: undefined | string = startingInstanceId;- const instanceIdsPath: Instance["id"][] = [];- while (currentId) {- instanceIdsPath.push(currentId);- currentId = parentInstanceById.get(currentId);- }- // allow accessing global variables everywhere- instanceIdsPath.push(ROOT_INSTANCE_ID);- const maskedVariables = new Map<DataSource["name"], DataSource["id"]>();- // global system variable always present- maskedVariables.set("system", SYSTEM_VARIABLE_ID);- // start from the root to descendant- // so child variables override parent variables- for (const instanceId of instanceIdsPath.reverse()) {- const instance = instances.get(instanceId);- const scopedDataSources = dataSourcesByScopeInstanceId.get(instanceId);- if (scopedDataSources === undefined) {- continue;- }- for (const dataSource of scopedDataSources) {- // when current instance is collection- // ignore its collection item parameter- // when rebind variables- if (- instanceId === startingInstanceId &&- instance?.component === collectionComponent &&- dataSource.type === "parameter"- ) {- continue;- }- maskedVariables.set(dataSource.name, dataSource.id);- }- }- return maskedVariables;-};--export const findAvailableVariables = ({- startingInstanceId,- instances,- dataSources,-}: {- startingInstanceId: Instance["id"];- instances: Instances;- dataSources: DataSources;-}) => {- const maskedVariables = findMaskedVariablesByInstanceId({- startingInstanceId,- parentInstanceById: getParentInstanceById(instances),- instances,- dataSources,- dataSourcesByScopeInstanceId: getDataSourcesByScopeInstanceId(dataSources),- });- const availableVariables: DataSource[] = [];- for (const dataSourceId of maskedVariables.values()) {- const dataSource = dataSources.get(dataSourceId);- if (dataSource) {- availableVariables.push(dataSource);- }- if (dataSourceId === SYSTEM_VARIABLE_ID) {- availableVariables.push(systemParameter);- }- }- return availableVariables;-};--const traverseExpressions = ({- startingInstanceId,- pages,- instances,- props,- dataSources,- resources,- update,-}: {- startingInstanceId: undefined | Instance["id"];- pages: undefined | Pages;- instances: Instances;- props: Props;- dataSources: DataSources;- resources: Resources;- update: (- expression: string,- instanceId: Instance["id"],- args?: string[]- ) => void | string;-}) => {- const pagesList = pages ? getAllPages(pages) : [];-- let instanceIds =- startingInstanceId === undefined- ? new Set(instances.keys())- : findTreeInstanceIdsExcludingSlotDescendants(- instances,- startingInstanceId- );- for (const page of pagesList) {- // global variables can be accessed on all pages and inside of slots- if (startingInstanceId === ROOT_INSTANCE_ID) {- instanceIds = setUnion(- instanceIds,- findTreeInstanceIds(instances, page.rootInstanceId)- );- }-- // global and body variables can be accessed in pages meta- if (- startingInstanceId === page.rootInstanceId ||- startingInstanceId === ROOT_INSTANCE_ID- ) {- const { rootInstanceId } = page;- page.title = update(page.title, rootInstanceId) ?? page.title;- if (page.meta.description) {- page.meta.description =- update(page.meta.description, rootInstanceId) ??- page.meta.description;- }- if (page.meta.excludePageFromSearch) {- page.meta.excludePageFromSearch =- update(page.meta.excludePageFromSearch, rootInstanceId) ??- page.meta.excludePageFromSearch;- }- if (page.meta.socialImageUrl) {- page.meta.socialImageUrl =- update(page.meta.socialImageUrl, rootInstanceId) ??- page.meta.socialImageUrl;- }- if (page.meta.language) {- page.meta.language =- update(page.meta.language, rootInstanceId) ?? page.meta.language;- }- if (page.meta.status) {- page.meta.status =- update(page.meta.status, rootInstanceId) ?? page.meta.status;- }- if (page.meta.redirect) {- page.meta.redirect =- update(page.meta.redirect, rootInstanceId) ?? page.meta.redirect;- }- if (page.meta.custom) {- for (const item of page.meta.custom) {- item.content = update(item.content, rootInstanceId) ?? item.content;- }- }- }- }- const instanceIdByResourceId = new Map<Resource["id"], Instance["id"]>();-- for (const instance of instances.values()) {- if (instanceIds.has(instance.id) === false) {- continue;- }- for (const child of instance.children) {- if (child.type === "expression") {- child.value = update(child.value, instance.id) ?? child.value;- }- }- }-- for (const prop of props.values()) {- if (instanceIds.has(prop.instanceId) === false) {- continue;- }- if (prop.type === "expression") {- prop.value = update(prop.value, prop.instanceId) ?? prop.value;- continue;- }- if (prop.type === "action") {- for (const action of prop.value) {- action.code =- update(action.code, prop.instanceId, action.args) ?? action.code;- }- continue;- }- if (prop.type === "resource") {- instanceIdByResourceId.set(prop.value, prop.instanceId);- continue;- }- }-- for (const dataSource of dataSources.values()) {- const instanceId = dataSource.scopeInstanceId ?? ROOT_INSTANCE_ID;- if (instanceIds.has(instanceId) && dataSource.type === "resource") {- instanceIdByResourceId.set(dataSource.resourceId, instanceId);- }- }-- for (const resource of resources.values()) {- const instanceId = instanceIdByResourceId.get(resource.id);- if (instanceId === undefined) {- continue;- }- resource.url = update(resource.url, instanceId) ?? resource.url;- for (const header of resource.headers) {- header.value = update(header.value, instanceId) ?? header.value;- }- if (resource.searchParams) {- for (const searchParam of resource.searchParams) {- searchParam.value =- update(searchParam.value, instanceId) ?? searchParam.value;- }- }- if (resource.body) {- resource.body = update(resource.body, instanceId) ?? resource.body;- }- }-};--export const findUnsetVariableNames = ({- instances,- props,- dataSources,- resources,-}: {- startingInstanceId: Instance["id"];- instances: Instances;- props: Props;- dataSources: DataSources;- resources: Resources;-}) => {- const unsetVariables = new Set<DataSource["name"]>();- traverseExpressions({- startingInstanceId: undefined,- pages: undefined,- instances,- props,- dataSources,- resources,- update: (expression, _instanceId, args = []) => {- transpileExpression({- expression,- replaceVariable: (identifier) => {- const id = decodeDataVariableId(identifier);- if (id === undefined && args.includes(identifier) === false) {- unsetVariables.add(decodeDataVariableName(identifier));- }- },- });- },- });- return Array.from(unsetVariables);-};--export const findUsedVariables = ({- startingInstanceId,- pages,- instances,- props,- dataSources,- resources,-}: {- startingInstanceId: Instance["id"];- pages: undefined | Pages;- instances: Instances;- props: Props;- dataSources: DataSources;- resources: Resources;-}) => {- const usedVariables = new Map<DataSource["id"], number>();- traverseExpressions({- startingInstanceId,- pages,- instances,- props,- dataSources,- resources,- update: (expression) => {- const identifiers = getExpressionIdentifiers(expression);- for (const identifier of identifiers) {- const id = decodeDataVariableId(identifier);- if (id !== undefined) {- const count = usedVariables.get(id) ?? 0;- usedVariables.set(id, count + 1);- }- }- },- });- return usedVariables;-};--export const findVariableUsagesByInstance = ({- startingInstanceId,- pages,- instances,- props,- dataSources,- resources,-}: {- startingInstanceId: Instance["id"];- pages: undefined | Pages;- instances: Instances;- props: Props;- dataSources: DataSources;- resources: Resources;-}) => {- const usedIn = new Map<DataSource["id"], Set<Instance["id"]>>();- traverseExpressions({- startingInstanceId,- pages,- instances,- props,- dataSources,- resources,- update: (expression, instanceId) => {- const identifiers = getExpressionIdentifiers(expression);- for (const identifier of identifiers) {- const id = decodeDataVariableId(identifier);- if (id !== undefined) {- if (!usedIn.has(id)) {- usedIn.set(id, new Set());- }- usedIn.get(id)?.add(instanceId);- }- }- },- });- return usedIn;-};--export const rebindTreeVariablesMutable = ({- startingInstanceId,- pages,- instances,- props,- dataSources,- resources,-}: {- startingInstanceId: Instance["id"];- pages: undefined | Pages;- instances: Instances;- props: Props;- dataSources: DataSources;- resources: Resources;-}) => {- // unset all variables- const unsetNameById = new Map<DataSource["id"], DataSource["name"]>();- for (const dataSource of dataSources.values()) {- unsetNameById.set(dataSource.id, dataSource.name);- }- // precompute parent instances outside of traverse- const parentInstanceById = getParentInstanceById(instances);- const dataSourcesByScopeInstanceId =- getDataSourcesByScopeInstanceId(dataSources);- traverseExpressions({- startingInstanceId,- pages,- instances,- props,- dataSources,- resources,- update: (expression, instanceId, args) => {- // restore all masked variables of current scope- const maskedVariables = findMaskedVariablesByInstanceId({- startingInstanceId: instanceId,- parentInstanceById,- instances,- dataSources,- dataSourcesByScopeInstanceId,- });- const maskedIdByName = new Map(maskedVariables);- if (args) {- for (const arg of args) {- maskedIdByName.delete(arg);- }- }- expression = unsetExpressionVariables({- expression,- unsetNameById,- });- expression = restoreExpressionVariables({- expression,- maskedIdByName,- });- return expression;- },- });-};--export const deleteVariableMutable = (- data: Omit<WebstudioData, "pages"> & { pages?: Pages },- variableId: DataSource["id"]-) => {- const dataSource = data.dataSources.get(variableId);- if (dataSource === undefined) {- return;- }- data.dataSources.delete(variableId);- if (dataSource.type === "resource") {- data.resources.delete(dataSource.resourceId);- }- const unsetNameById = new Map<DataSource["id"], DataSource["name"]>();- unsetNameById.set(dataSource.id, dataSource.name);- const startingInstanceId = dataSource.scopeInstanceId ?? ROOT_INSTANCE_ID;- const maskedIdByName = findMaskedVariablesByInstanceId({- startingInstanceId,- parentInstanceById: getParentInstanceById(data.instances),- instances: data.instances,- dataSources: data.dataSources,- dataSourcesByScopeInstanceId: getDataSourcesByScopeInstanceId(- data.dataSources- ),- });- // unset deleted variable in expressions- traverseExpressions({- ...data,- pages: data.pages,- startingInstanceId,- update: (expression) => {- expression = unsetExpressionVariables({- expression,- unsetNameById,- });- expression = restoreExpressionVariables({- expression,- maskedIdByName,- });- return expression;- },- });-};diff --git a/apps/builder/app/shared/expression-validation.test.ts b/apps/builder/app/shared/expression-validation.test.tsnew file mode 100644index 0000000000..5717d1a84e--- /dev/null+++ b/apps/builder/app/shared/expression-validation.test.ts@@ -0,0 +1,16 @@+import { expect, test } from "vitest";+import {+ getExpressionErrorMessages,+ hasExpressionDiagnostics,+} from "./expression-validation";++test("returns only expression error messages", () => {+ expect(getExpressionErrorMessages({ expression: "invalid {" })).not.toEqual(+ []+ );+});++test("detects expression diagnostics", () => {+ expect(hasExpressionDiagnostics({ expression: "invalid {" })).toBe(true);+ expect(hasExpressionDiagnostics({ expression: '"value"' })).toBe(false);+});diff --git a/apps/builder/app/shared/expression-validation.ts b/apps/builder/app/shared/expression-validation.tsnew file mode 100644index 0000000000..c9432324d5--- /dev/null+++ b/apps/builder/app/shared/expression-validation.ts@@ -0,0 +1,12 @@+import { lintExpression } from "@webstudio-is/sdk";++export const getExpressionErrorMessages = (+ options: Parameters<typeof lintExpression>[0]+) =>+ lintExpression(options)+ .filter((diagnostic) => diagnostic.severity === "error")+ .map((diagnostic) => diagnostic.message);++export const hasExpressionDiagnostics = (+ options: Parameters<typeof lintExpression>[0]+) => lintExpression(options).length > 0;diff --git a/apps/builder/app/shared/instance-utils/data.test.tsx b/apps/builder/app/shared/instance-utils/data.test.tsxindex b346b6f016..fa78ce0447 100644--- a/apps/builder/app/shared/instance-utils/data.test.tsx+++ b/apps/builder/app/shared/instance-utils/data.test.tsx@@ -1,12 +1,11 @@import { describe, expect, test } from "vitest";-import { produce } from "immer";import type { Instance, PageTemplate } from "@webstudio-is/sdk";import { blockComponent, blockTemplateComponent } from "@webstudio-is/sdk";import { createDefaultPages, findCycles } from "@webstudio-is/project-build";import {+ applyBuilderPatchPayloadMutable,canDeleteInstanceInContentMode,getWebstudioData,- unwrap,updateInstanceData,updateWebstudioData,} from "./data";@@ -86,16 +85,6 @@ describe("canDeleteInstanceInContentMode", () => {});describe("data store helpers", () => {- test("unwrap returns current value for immer drafts and original value otherwise", () => {- const source = { count: 1 };- expect(unwrap(source)).toBe(source);-- produce(source, (draft) => {- draft.count = 2;- expect(unwrap(draft)).toEqual({ count: 2 });- });- });-test("getWebstudioData reads all instance-related stores", () => {const pages = createDefaultPages({ rootInstanceId: "body" });const instances = new Map([["body", createInstance("body", "Body", [])]]);@@ -173,6 +162,52 @@ describe("data store helpers", () => {expect($assets.get()).toBe(assets);});+ test("applies shared build patch payloads to store data", () => {+ const data = {+ instances: new Map([+ [+ "parent",+ createInstance("parent", "Box", [{ type: "id", value: "child" }]),+ ],+ ["child", createInstance("child", "Box", [])],+ ]),+ props: new Map(),+ styleSourceSelections: new Map(),+ styleSources: new Map(),+ styles: new Map(),+ dataSources: new Map(),+ resources: new Map(),+ };++ applyBuilderPatchPayloadMutable(data, [+ {+ namespace: "instances",+ patches: [+ { op: "remove", path: ["parent", "children", 0] },+ {+ op: "add",+ path: ["parent", "children", 0],+ value: { type: "id", value: "next" },+ },+ {+ op: "add",+ path: ["next"],+ value: createInstance("next", "Box", []),+ },+ { op: "remove", path: ["child"] },+ ],+ },+ ]);++ expect(data.instances.get("parent")?.children).toEqual([+ { type: "id", value: "next" },+ ]);+ expect(data.instances.has("child")).toBe(false);+ expect(data.instances.get("next")).toEqual(+ createInstance("next", "Box", [])+ );+ });+test("updateWebstudioData skips page templates without build access", () => {const pages = createDefaultPages({ rootInstanceId: "body" });const template: PageTemplate = {diff --git a/apps/builder/app/shared/instance-utils/data.ts b/apps/builder/app/shared/instance-utils/data.tsindex d74ab17d9e..00a5c8e5f0 100644--- a/apps/builder/app/shared/instance-utils/data.ts+++ b/apps/builder/app/shared/instance-utils/data.ts@@ -1,7 +1,6 @@// Data utilities own access to Webstudio's instance-related stores and// transaction boundaries. Put generic store reads/writes and content-mode data// guards here, not tree-shape mutations.-import { current, isDraft } from "immer";import { toast } from "@webstudio-is/design-system";import {type Instances,@@ -9,6 +8,9 @@ import {blockTemplateComponent,isPageTemplate,} from "@webstudio-is/sdk";+import type { BuilderPatchChange } from "@webstudio-is/project-build/contracts/patch";+import type { BuilderState } from "@webstudio-is/project-build/state/builder-state";+import * as builderStatePatch from "@webstudio-is/project-build/state/patch";import { breakCyclesMutable, findCycles } from "@webstudio-is/project-build";import { findBlockSelector } from "../nano-states";import { $canOpenPageTemplates, $selectedPage } from "../nano-states";@@ -38,12 +40,31 @@ export type WebstudioInstanceData = Pick<| "resources">;-/**- * structuredClone can be invoked on draft and throw error- * extract current snapshot before cloning- */-export const unwrap = <Value>(value: Value) =>- isDraft(value) ? current(value) : value;+type PatchableWebstudioData =+ | BuilderState+ | WebstudioData+ | WebstudioInstanceData;++const getPatchNamespaceData = (+ data: PatchableWebstudioData,+ namespace: BuilderPatchChange["namespace"]+) => {+ const namespaceData = data[namespace as keyof PatchableWebstudioData];+ if (namespaceData !== undefined) {+ return namespaceData;+ }+ throw Error(`Cannot apply patch for unavailable namespace "${namespace}"`);+};++export const applyBuilderPatchPayloadMutable = (+ data: PatchableWebstudioData,+ payload: BuilderPatchChange[]+) => {+ builderStatePatch.applyBuilderPatchPayloadMutable(+ (namespace) => getPatchNamespaceData(data, namespace),+ payload+ );+};export const canDeleteInstanceInContentMode = ({instanceSelector,diff --git a/apps/builder/app/shared/instance-utils/fragment.test.tsx b/apps/builder/app/shared/instance-utils/fragment.test.tsxindex 45ff1e9b70..577e413967 100644--- a/apps/builder/app/shared/instance-utils/fragment.test.tsx+++ b/apps/builder/app/shared/instance-utils/fragment.test.tsx@@ -1,10 +1,10 @@import {+ __testing__,detectFragmentTokenConflicts,+ detectPageTokenConflicts,extractWebstudioFragment,insertWebstudioFragmentCopy,- detectPageTokenConflicts,-} from "./fragment";-import { __testing__ } from "./fragment";+} from "@webstudio-is/project-build/runtime/fragment";import { getWebstudioData } from "./data";import { enableMapSet } from "immer";import { describe, test, expect, beforeEach } from "vitest";@@ -47,9 +47,9 @@ import {} from "~/shared/sync/data-stores";import { registerContainers } from "../sync/sync-stores";import { getInstancePath } from "../nano-states";+import { isFragmentContentModeCopyableProp } from "../content-mode-copy-policy";const {- getFragmentContentModeCapabilities,getFragmentInstancesData,insertFragmentAssetsMutable,insertFragmentBreakpointsMutable,@@ -286,14 +286,15 @@ describe("fragment copy helpers", () => {});const { fragmentInstances } = getFragmentInstancesData(fragment);- const capabilities = getFragmentContentModeCapabilities({+ const isCopyable = isFragmentContentModeCopyableProp({+ prop: fragment.props[0],fragment,fragmentInstances,styleSources: new Map(),+ metas: $registeredComponentMetas.get(),});- expect(capabilities.contentRootIds).toEqual(new Set(["link"]));- expect(capabilities.editablePropIds.has("href-prop")).toBe(true);+ expect(isCopyable).toBe(true);} finally {$registeredComponentMetas.set(registeredComponentMetas);}@@ -793,7 +794,9 @@ describe("insert webstudio fragment copy", () => {fragment,availableVariables: [],projectId: "current_project",+ metas: defaultMetasMap,contentMode: true,+ contentModeCopyableProp: isFragmentContentModeCopyableProp,});const newInstanceId = newInstanceIds.get("templateBox");@@ -880,7 +883,9 @@ describe("insert webstudio fragment copy", () => {fragment,availableVariables: [],projectId: "current_project",+ metas: $registeredComponentMetas.get(),contentMode: true,+ contentModeCopyableProp: isFragmentContentModeCopyableProp,});const newInstanceId = newInstanceIds.get("item");@@ -934,7 +939,9 @@ describe("insert webstudio fragment copy", () => {fragment,availableVariables: [],projectId: "current_project",+ metas: defaultMetasMap,contentMode: true,+ contentModeCopyableProp: isFragmentContentModeCopyableProp,});const newInstanceId = newInstanceIds.get("image");@@ -2258,6 +2265,10 @@ describe("detectPageTokenConflicts", () => {const conflicts = detectFragmentTokenConflicts({fragment: extractWebstudioFragment(sourceData, "source-box"),+ targetData: {+ ...targetData,+ pages: createDefaultPages({ rootInstanceId: "body" }),+ },});expect(conflicts).toHaveLength(1);@@ -2300,6 +2311,7 @@ describe("detectPageTokenConflicts", () => {const conflicts = detectPageTokenConflicts({sourceData: sourceWebstudioData,+ targetData: { ...targetData, pages },pageId: sourcePages.homePageId,});@@ -2352,6 +2364,7 @@ describe("detectPageTokenConflicts", () => {const conflicts = detectPageTokenConflicts({sourceData: sourceWebstudioData,+ targetData: { ...targetData, pages },pageId: sourcePages.homePageId,});@@ -2425,6 +2438,7 @@ describe("detectPageTokenConflicts", () => {const conflicts = detectPageTokenConflicts({sourceData: sourceWebstudioData,+ targetData: { ...targetData, pages },pageId: sourcePages.homePageId,});@@ -2449,6 +2463,7 @@ describe("detectPageTokenConflicts", () => {expect(() =>detectPageTokenConflicts({sourceData: sourceWebstudioData,+ targetData: { ...targetData, pages },pageId: "non-existent-page-id",})).toThrow("Page not found");diff --git a/apps/builder/app/shared/instance-utils/insert.ts b/apps/builder/app/shared/instance-utils/insert.tsindex ec87acfdab..cd76269584 100644--- a/apps/builder/app/shared/instance-utils/insert.ts+++ b/apps/builder/app/shared/instance-utils/insert.ts@@ -29,7 +29,7 @@ import {findClosestNonTextualContainer,isTreeSatisfyingContentModel,} from "../content-model";-import { findAvailableVariables } from "../data-variables";+import { findAvailableVariables } from "@webstudio-is/project-build/runtime/data";import { getInstanceLabel } from "~/builder/shared/instance-label";import { getSlotFragmentDropTargetMutable } from "./slot";import {@@ -38,7 +38,7 @@ import {wrapEditableChildrenAroundDropTargetMutable,} from "./tree";import { updateWebstudioData } from "./data";-import { insertWebstudioFragmentCopy } from "./fragment";+import { insertWebstudioFragmentCopy } from "@webstudio-is/project-build/runtime/fragment";const getExistingInsertTargetPath = (insertable: Insertable) => {const instancePath = getInstancePath(diff --git a/apps/builder/app/shared/instance-utils/mutation.ts b/apps/builder/app/shared/instance-utils/mutation.tsindex fb3dab714e..8ec5062111 100644--- a/apps/builder/app/shared/instance-utils/mutation.ts+++ b/apps/builder/app/shared/instance-utils/mutation.ts@@ -14,7 +14,6 @@ import {type WsComponentMeta,elementComponent,findTreeInstanceIds,- findTreeInstanceIdsExcludingSlotDescendants,isComponentDetachable,} from "@webstudio-is/sdk";import { reactPropsToStandardAttributes } from "@webstudio-is/react-sdk";@@ -35,7 +34,11 @@ import { serverSyncStore } from "../sync/sync-stores";import {findAvailableVariables,rebindTreeVariablesMutable,-} from "../data-variables";+} from "@webstudio-is/project-build/runtime/data";+import {+ createInstanceChild,+ getSameParentAdjustedInsertIndex,+} from "@webstudio-is/project-build/runtime/instances";import {isRichTextContent,isTreeSatisfyingContentModel,@@ -55,20 +58,27 @@ import {import {type DroppableTarget,type InstanceSelector,- findLocalStyleSourcesWithinInstances,getReparentDropTargetMutable,} from "./tree";import {+ createInstanceDeletePayload,+ findChildReferenceIndex,+} from "@webstudio-is/project-build/runtime/instances";+import {+ applyBuilderPatchPayloadMutable,canDeleteInstanceInContentMode,updateInstanceData,updateWebstudioData,type WebstudioInstanceData,} from "./data";+import {+ createPropDeletePayload,+ createPropRenamePayload,+} from "@webstudio-is/project-build/runtime/props";import {extractWebstudioFragment,insertWebstudioFragmentCopy,-} from "./fragment";-import { deleteLocalStyleSourcesMutable } from "../style-source-utils";+} from "@webstudio-is/project-build/runtime/fragment";const getSlotChildrenSignature = (instance: Instance) => {return JSON.stringify(instance.children);@@ -188,17 +198,6 @@ const countInstanceChildReferences = (return count;};-const createInstanceChild = (instanceId: Instance["id"]) =>- ({ type: "id", value: instanceId }) as const;--const findChildReferenceIndex = (- children: Instance["children"],- instanceId: Instance["id"]-) =>- children.findIndex(- (child) => child.type === "id" && child.value === instanceId- );-const removeChildReferenceMutable = (children: Instance["children"],instanceId: Instance["id"]@@ -274,10 +273,10 @@ const reorderInstanceWithinParentMutable = (return;}// When parent is the same, account for removal before reinserting.- let nextPosition = dropTarget.position;- if (prevPosition < nextPosition) {- nextPosition -= 1;- }+ const nextPosition = getSameParentAdjustedInsertIndex({+ currentIndex: prevPosition,+ requestedIndex: dropTarget.position,+ });parent.children.splice(nextPosition, 0, child);};@@ -319,10 +318,7 @@ const moveInstanceToParentMutable = (const getDeleteTarget = (instances: Instances,instancePath: InstancePath-): {- targetInstance: Instance;- parentInstance?: Instance;-} => {+): Instance => {let targetInstance = instancePath[0].instance;let parentInstance = instancePath[1]?.instance;const grandparentInstance = instancePath[2]?.instance;@@ -339,7 +335,7 @@ const getDeleteTarget = (parentInstance = grandparentInstance;}- return { targetInstance, parentInstance };+ return targetInstance;};export const deleteInstanceMutable = (@@ -353,80 +349,30 @@ export const deleteInstanceMutable = (data.instances,instancePath);- const {- instances,- props,- styleSourceSelections,- styleSources,- styles,- dataSources,- resources,- } = data;- const { targetInstance, parentInstance } = getDeleteTarget(- instances,- instancePath- );-- const instanceIds = findTreeInstanceIdsExcludingSlotDescendants(- instances,- targetInstance.id- );- const localStyleSourceIds = findLocalStyleSourcesWithinInstances(- styleSources.values(),- styleSourceSelections.values(),- instanceIds- );-- // mutate instances from data instead of instance path- const parentToMutate = data.instances.get(parentInstance?.id as string);- // may not exist when delete root- if (parentToMutate) {- removeChildReferenceMutable(parentToMutate.children, targetInstance.id);- }-- for (const instanceId of instanceIds) {- instances.delete(instanceId);- }- // delete props, data sources and styles of deleted instance and its descendants- for (const prop of props.values()) {- if (instanceIds.has(prop.instanceId)) {- props.delete(prop.id);- if (prop.type === "resource") {- resources.delete(prop.value);- }- }- }- for (const dataSource of dataSources.values()) {- if (instanceIds.has(dataSource.scopeInstanceId ?? "")) {- dataSources.delete(dataSource.id);- if (dataSource.type === "resource") {- resources.delete(dataSource.resourceId);- }- }- }- for (const instanceId of instanceIds) {- styleSourceSelections.delete(instanceId);- }- deleteLocalStyleSourcesMutable({- localStyleSourceIds,- styleSources,- styles,+ const targetInstance = getDeleteTarget(data.instances, instancePath);+ const { errors, payload } = createInstanceDeletePayload({+ instances: data.instances,+ instanceIds: [targetInstance.id],+ props: data.props.values(),+ dataSources: data.dataSources.values(),+ styleSources: data.styleSources.values(),+ styleSourceSelections: data.styleSourceSelections.values(),+ styles: data.styles.values(),});+ if (errors.length > 0) {+ return false;+ }+ applyBuilderPatchPayloadMutable(data, payload);return true;};-const getIdChildIndex = (children: Instance["children"], instanceId: string) =>- children.findIndex(- (child) => child.type === "id" && child.value === instanceId- );-const getInstancePathSiblingIndex = (instancePath: InstancePath) => {const selectedItem = instancePath[0];const parentItem = instancePath[1];if (parentItem === undefined) {return -1;}- return getIdChildIndex(+ return findChildReferenceIndex(parentItem.instance.children,selectedItem.instance.id);@@ -1030,19 +976,38 @@ export const convertInstance = (component: string, tag?: string) => {if (tag || component === elementComponent) {instance.tag = tag ?? instanceTags.get(selectedInstance.id) ?? "div";// delete legacy tag prop if specified- for (const prop of data.props.values()) {+ for (const prop of Array.from(data.props.values())) {if (prop.instanceId !== selectedInstance.id) {continue;}if (prop.name === "tag") {- data.props.delete(prop.id);+ applyBuilderPatchPayloadMutable(+ data,+ createPropDeletePayload({+ deletions: [+ { instanceId: selectedInstance.id, name: prop.name },+ ],+ instances: data.instances,+ props: data.props.values(),+ }).payload+ );continue;}const newName = reactPropsToStandardAttributes[prop.name];if (newName) {- const newId = `${prop.instanceId}:${newName}`;- data.props.delete(prop.id);- data.props.set(newId, { ...prop, id: newId, name: newName });+ applyBuilderPatchPayloadMutable(+ data,+ createPropRenamePayload({+ props: data.props.values(),+ renames: [+ {+ propId: prop.id,+ name: newName,+ propIdPrefix: prop.instanceId,+ },+ ],+ }).payload+ );}}}diff --git a/apps/builder/app/shared/instance-utils/tree.test.ts b/apps/builder/app/shared/instance-utils/tree.test.tsindex b997eb6d73..49bacbc85b 100644--- a/apps/builder/app/shared/instance-utils/tree.test.ts+++ b/apps/builder/app/shared/instance-utils/tree.test.ts@@ -1,87 +1,13 @@-import { test, expect } from "vitest";-import type {- Instance,- Props,- StyleDecl,- Styles,- StyleSource,- StyleSourceSelection,- WsComponentMeta,-} from "@webstudio-is/sdk";-import {- collectionComponent,- elementComponent,- getStyleDeclKey,-} from "@webstudio-is/sdk";+import { expect, test } from "vitest";+import type { Instance, Props, WsComponentMeta } from "@webstudio-is/sdk";+import { collectionComponent, elementComponent } from "@webstudio-is/sdk";import {areInstanceSelectorsEqual,- cloneStyles,- findLocalStyleSourcesWithinInstances,getReparentDropTargetMutable,isDescendantOrSelf,wrapEditableChildrenAroundDropTargetMutable,} from "./tree";-const createStyleSource = (- type: StyleSource["type"],- id: StyleSource["id"]-): StyleSource => {- if (type === "token") {- return {- type,- id,- name: id,- };- }- return {- type,- id,- };-};--const createStyleSourceSelection = (- instanceId: Instance["id"],- values: StyleSource["id"][]-): StyleSourceSelection => {- return {- instanceId,- values,- };-};--const createStyleDecl = (- styleSourceId: string,- breakpointId: string,- value?: string-): StyleDecl => {- return {- styleSourceId,- breakpointId,- property: "width",- value: {- type: "keyword",- value: value ?? "value",- },- };-};--const createStyleDeclPair = (- styleSourceId: string,- breakpointId: string,- state?: string,- value?: string-) => {- return [- getStyleDeclKey({- styleSourceId,- breakpointId,- state,- property: "width",- }),- createStyleDecl(styleSourceId, breakpointId, value),- ] as const;-};-const createInstance = (id: Instance["id"],component: string,@@ -105,51 +31,6 @@ test("compares instance selectors", () => {expect(areInstanceSelectorsEqual(undefined, undefined)).toBe(false);});-test("clone styles with appled new style source ids", () => {- const styles: Styles = new Map([- createStyleDeclPair("styleSource1", "bp1"),- createStyleDeclPair("styleSource2", "bp2"),- createStyleDeclPair("styleSource1", "bp3"),- createStyleDeclPair("styleSource3", "bp4"),- createStyleDeclPair("styleSource1", "bp5"),- createStyleDeclPair("styleSource3", "bp6"),- ]);- const clonedStyleSourceIds = new Map<StyleSource["id"], StyleSource["id"]>();- clonedStyleSourceIds.set("styleSource2", "newStyleSource2");- clonedStyleSourceIds.set("styleSource3", "newStyleSource3");- expect(cloneStyles(styles, clonedStyleSourceIds)).toEqual([- createStyleDecl("newStyleSource2", "bp2"),- createStyleDecl("newStyleSource3", "bp4"),- createStyleDecl("newStyleSource3", "bp6"),- ]);-});--test("find local style sources within instances", () => {- const instanceIds = new Set(["instance2", "instance4"]);- const styleSources = [- createStyleSource("local", "local1"),- createStyleSource("local", "local2"),- createStyleSource("token", "token3"),- createStyleSource("local", "local4"),- createStyleSource("token", "token5"),- createStyleSource("local", "local6"),- ];- const styleSourceSelections = [- createStyleSourceSelection("instance1", ["local1"]),- createStyleSourceSelection("instance2", ["local2"]),- createStyleSourceSelection("instance3", ["token3"]),- createStyleSourceSelection("instance4", ["local4", "token5"]),- createStyleSourceSelection("instance5", ["local6"]),- ];- expect(- findLocalStyleSourcesWithinInstances(- styleSources,- styleSourceSelections,- instanceIds- )- ).toEqual(new Set(["local2", "local4"]));-});-test("is descendant or self", () => {expect(isDescendantOrSelf(["1", "2", "3"], [])).toBe(true);expect(isDescendantOrSelf(["1", "2", "3"], ["1", "2", "3"])).toBe(true);diff --git a/apps/builder/app/shared/instance-utils/tree.ts b/apps/builder/app/shared/instance-utils/tree.tsindex 7223831d03..972b232966 100644--- a/apps/builder/app/shared/instance-utils/tree.ts+++ b/apps/builder/app/shared/instance-utils/tree.ts@@ -1,16 +1,12 @@// Tree utilities own generic instance-tree mechanics that are not tied to a// specific command: selector comparison, ancestry checks, drop target shaping,-// and style-source traversal within instance trees.+// and rich-text drop target normalization.import { nanoid } from "nanoid";import { shallowEqual } from "shallow-equal";import type {Instance,Instances,Props,- StyleDecl,- Styles,- StyleSource,- StyleSourceSelection,WsComponentMeta,} from "@webstudio-is/sdk";import { collectionComponent, elementComponent } from "@webstudio-is/sdk";@@ -180,52 +176,3 @@ export const getReparentDropTargetMutable = () ?? dropTarget;return dropTarget;};--export const cloneStyles = (- styles: Styles,- clonedStyleSourceIds: Map<Instance["id"], Instance["id"]>-) => {- const clonedStyles: StyleDecl[] = [];- for (const styleDecl of styles.values()) {- const styleSourceId = clonedStyleSourceIds.get(styleDecl.styleSourceId);- if (styleSourceId === undefined) {- continue;- }- clonedStyles.push({- ...styleDecl,- styleSourceId,- });- }- return clonedStyles;-};--export const findLocalStyleSourcesWithinInstances = (- styleSources: IterableIterator<StyleSource> | StyleSource[],- styleSourceSelections:- | IterableIterator<StyleSourceSelection>- | StyleSourceSelection[],- instanceIds: Set<Instance["id"]>-) => {- const localStyleSourceIds = new Set<StyleSource["id"]>();- for (const styleSource of styleSources) {- if (styleSource.type === "local") {- localStyleSourceIds.add(styleSource.id);- }- }-- const subtreeLocalStyleSourceIds = new Set<StyleSource["id"]>();- for (const { instanceId, values } of styleSourceSelections) {- // skip selections outside of subtree- if (instanceIds.has(instanceId) === false) {- continue;- }- // find only local style sources on selections- for (const styleSourceId of values) {- if (localStyleSourceIds.has(styleSourceId)) {- subtreeLocalStyleSourceIds.add(styleSourceId);- }- }- }-- return subtreeLocalStyleSourceIds;-};diff --git a/apps/builder/app/shared/nano-states/breakpoints.ts b/apps/builder/app/shared/nano-states/breakpoints.tsindex 936ace03ff..056c77c78a 100644--- a/apps/builder/app/shared/nano-states/breakpoints.ts+++ b/apps/builder/app/shared/nano-states/breakpoints.ts@@ -1,7 +1,7 @@import { atom, computed } from "nanostores";import type { Breakpoint } from "@webstudio-is/sdk";import { $breakpoints } from "../sync/data-stores";-import { isBaseBreakpoint } from "../breakpoints-utils";+import { isBaseBreakpoint } from "@webstudio-is/project-build/runtime/breakpoints";export const $selectedBreakpointId = atom<undefined | Breakpoint["id"]>(undefineddiff --git a/apps/builder/app/shared/nano-states/props.ts b/apps/builder/app/shared/nano-states/props.tsindex 65880775bc..ab0b83b6fc 100644--- a/apps/builder/app/shared/nano-states/props.ts+++ b/apps/builder/app/shared/nano-states/props.ts@@ -31,7 +31,7 @@ import { $dataSourceVariables } from "./variables";import { uploadingFileDataToAsset } from "~/builder/shared/assets/asset-utils";import { $selectedPage } from "./pages";import { getInstanceKey } from "./instances";-import { computeExpression } from "../data-variables";+import { computeExpression } from "@webstudio-is/project-build/runtime/data";import { $currentSystem } from "../system";import {$resourcesCache,diff --git a/apps/builder/app/shared/page-utils/meta.test.ts b/apps/builder/app/shared/page-utils/meta.test.tsnew file mode 100644index 0000000000..6ba0854dd7--- /dev/null+++ b/apps/builder/app/shared/page-utils/meta.test.ts@@ -0,0 +1,91 @@+import { describe, expect, test } from "vitest";+import { createRootFolder } from "@webstudio-is/project-build";+import { migratePages } from "@webstudio-is/project-migrations/pages";+import { updatePageFieldsMutable } from "./meta";++const createPages = () =>+ migratePages({+ meta: {},+ homePage: {+ id: "home",+ name: "Home",+ path: "",+ title: `"Home"`,+ meta: {},+ rootInstanceId: "homeBody",+ },+ pages: [+ {+ id: "page",+ name: "Page",+ path: "/page",+ title: `"Page"`,+ meta: {+ language: "en",+ socialImageAssetId: "asset",+ },+ rootInstanceId: "pageBody",+ },+ ],+ folders: [+ createRootFolder(["home", "page", "folder"]),+ { id: "folder", name: "Folder", slug: "folder", children: [] },+ ],+ });++describe("updatePageFieldsMutable", () => {+ test("updates page fields and keeps home page path empty", () => {+ const pages = createPages();+ const page = pages.pages.get("home");++ updatePageFieldsMutable({+ page: page!,+ pages,+ values: {+ name: "Landing",+ path: "/landing",+ title: `"Landing"`,+ },+ });++ expect(page).toMatchObject({+ name: "Landing",+ path: "",+ title: `"Landing"`,+ });+ });++ test("removes empty optional metadata fields", () => {+ const pages = createPages();+ const page = pages.pages.get("page");++ updatePageFieldsMutable({+ page: page!,+ pages,+ values: {+ language: "",+ socialImageAssetId: "",+ },+ });++ expect(page?.meta.language).toBeUndefined();+ expect(page?.meta.socialImageAssetId).toBeUndefined();+ });++ test("moves page to another folder", () => {+ const pages = createPages();+ const page = pages.pages.get("page");++ updatePageFieldsMutable({+ page: page!,+ pages,+ values: { parentFolderId: "folder" },+ });++ expect(pages.folders.get(pages.rootFolderId)?.children).toEqual([+ "home",+ "folder",+ ]);+ expect(pages.folders.get("folder")?.children).toEqual(["page"]);+ });+});diff --git a/apps/builder/app/shared/page-utils/meta.ts b/apps/builder/app/shared/page-utils/meta.tsnew file mode 100644index 0000000000..0377cd26c3--- /dev/null+++ b/apps/builder/app/shared/page-utils/meta.ts@@ -0,0 +1,96 @@+import type { Page, Pages } from "@webstudio-is/sdk";+import { normalizePageMetaValue } from "@webstudio-is/project-build/runtime/pages";+import { registerFolderChildMutable } from "./tree";++type PageMeta = Page["meta"];++const assignPageMetaValueMutable = <Name extends keyof PageMeta>(+ meta: PageMeta,+ name: Name,+ value: PageMeta[Name]+) => {+ const normalizedValue = normalizePageMetaValue(name, value);+ if (normalizedValue === undefined) {+ delete meta[name];+ return;+ }+ meta[name] = normalizedValue;+};++type PageFieldsUpdate = Partial<{+ name: Page["name"];+ path: Page["path"];+ title: Page["title"];+ description: Page["meta"]["description"];+ excludePageFromSearch: Page["meta"]["excludePageFromSearch"];+ language: Page["meta"]["language"];+ status: Page["meta"]["status"];+ redirect: Page["meta"]["redirect"];+ socialImageAssetId: Page["meta"]["socialImageAssetId"];+ socialImageUrl: Page["meta"]["socialImageUrl"];+ customMetas: NonNullable<Page["meta"]["custom"]>;+ documentType: Page["meta"]["documentType"];+ content: Page["meta"]["content"];+ parentFolderId: string;+}>;++export const updatePageFieldsMutable = ({+ page,+ pages,+ values,+}: {+ page: Page;+ pages: Pages;+ values: PageFieldsUpdate;+}) => {+ if (values.name !== undefined) {+ page.name = values.name;+ }+ if (values.path !== undefined) {+ page.path = page.id === pages.homePageId ? "" : values.path;+ }+ if (values.title !== undefined) {+ page.title = values.title;+ }+ if (values.description !== undefined) {+ page.meta.description = values.description;+ }+ if (values.excludePageFromSearch !== undefined) {+ page.meta.excludePageFromSearch = values.excludePageFromSearch;+ }+ if (values.language !== undefined) {+ assignPageMetaValueMutable(page.meta, "language", values.language);+ }+ if ("status" in values) {+ page.meta.status = values.status;+ }+ if (values.redirect !== undefined) {+ assignPageMetaValueMutable(page.meta, "redirect", values.redirect);+ }+ if (values.socialImageAssetId !== undefined) {+ assignPageMetaValueMutable(+ page.meta,+ "socialImageAssetId",+ values.socialImageAssetId+ );+ }+ if (values.socialImageUrl !== undefined) {+ assignPageMetaValueMutable(+ page.meta,+ "socialImageUrl",+ values.socialImageUrl+ );+ }+ if (values.customMetas !== undefined) {+ page.meta.custom = values.customMetas;+ }+ if (values.documentType !== undefined) {+ page.meta.documentType = values.documentType;+ }+ if (values.content !== undefined) {+ page.meta.content = values.content;+ }+ if (values.parentFolderId !== undefined) {+ registerFolderChildMutable(pages, page.id, values.parentFolderId);+ }+};diff --git a/apps/builder/app/shared/page-utils/tree.test.ts b/apps/builder/app/shared/page-utils/tree.test.tsnew file mode 100644index 0000000000..e83de5abaf--- /dev/null+++ b/apps/builder/app/shared/page-utils/tree.test.ts@@ -0,0 +1,449 @@+import { describe, expect, test } from "vitest";+import { createDefaultPages } from "@webstudio-is/project-build";+import {+ isRootFolder,+ ROOT_FOLDER_ID,+ type Folder,+ type Page,+} from "@webstudio-is/sdk";+import {+ cleanupChildRefsMutable,+ insertFolderMutable,+ registerFolderChildMutable,+ reparentOrphansMutable,+ reparentPageOrFolderMutable,+ updateFolderFieldsMutable,+} from "./tree";++const createPages = () => {+ const data = createDefaultPages({+ rootInstanceId: "rootInstanceId",+ homePageId: "homePageId",+ });++ const { pages, folders } = data;++ function f(id: string, children?: Array<Page | Folder>): Folder;+ function f(id: string, slug: string, children?: Array<Page | Folder>): Folder;+ function f(id: string, slug?: unknown, children?: unknown) {+ if (Array.isArray(slug)) {+ children = slug;+ slug = id;+ }+ const folder = {+ id,+ name: id,+ slug: slug ?? id,+ children: register((children as Array<Page | Folder>) ?? [], false),+ };++ return folder;+ }++ const p = (id: string, path: string): Page => {+ const page = {+ id,+ meta: {},+ name: id,+ path,+ rootInstanceId: "rootInstanceId",+ title: `"${id}"`,+ };+ return page;+ };++ const register = (children: Array<Page | Folder>, root: boolean = true) => {+ const childIds = [];+ const rootFolder = Array.from(folders.values()).find(isRootFolder);++ for (const child of children) {+ childIds.push(child.id);+ if ("meta" in child) {+ pages.set(child.id, child);+ continue;+ }+ folders.set(child.id, child);++ if (root) {+ rootFolder?.children.push(child.id);+ }+ }++ return childIds;+ };++ return { f, p, register, pages: data };+};++describe("reparentOrphansMutable", () => {+ // We must deal with the fact there can be an orphaned folder or page in a collaborative mode,+ // because user A can add a page to a folder while user B deletes the folder without receiving the create page yet.+ test("reparent orphans to the root", () => {+ const { pages } = createPages();+ pages.pages.set("pageId", {+ id: "pageId",+ meta: {},+ name: "Page",+ path: "/page",+ rootInstanceId: "rootInstanceId",+ title: `"Page"`,+ });+ pages.folders.set("folderId", {+ id: "folderId",+ name: "Folder",+ slug: "folder",+ children: [],+ });+ reparentOrphansMutable(pages);+ const rootFolder = Array.from(pages.folders.values()).find(isRootFolder);+ expect(rootFolder).toEqual({+ id: ROOT_FOLDER_ID,+ name: "Root",+ slug: "",+ children: ["homePageId", "folderId", "pageId"],+ });+ });++ test("recreates missing root folder with rootFolderId", () => {+ const { pages } = createPages();+ pages.rootFolderId = "customRoot";+ pages.folders = new Map();+ pages.pages.set("pageId", {+ id: "pageId",+ meta: {},+ name: "Page",+ path: "/page",+ rootInstanceId: "rootInstanceId",+ title: `"Page"`,+ });++ reparentOrphansMutable(pages);++ expect(pages.folders.get("customRoot")).toEqual({+ id: "customRoot",+ name: "Root",+ slug: "",+ children: ["homePageId", "pageId"],+ });+ });++ test("keeps home page first in root folder", () => {+ const { pages } = createPages();+ pages.folders.set("folderId", {+ id: "folderId",+ name: "Folder",+ slug: "folder",+ children: ["homePageId"],+ });+ pages.folders.get(pages.rootFolderId)!.children = ["folderId"];++ reparentOrphansMutable(pages);++ expect(pages.folders.get(pages.rootFolderId)?.children).toEqual([+ "homePageId",+ "folderId",+ ]);+ expect(pages.folders.get("folderId")?.children).toEqual([]);+ });+});++describe("cleanupChildRefsMutable", () => {+ test("cleanup refs", () => {+ const {+ pages: { folders },+ } = createPages();+ folders.set("folderId", {+ id: "folderId",+ name: "Folder",+ slug: "folder",+ children: [],+ });+ const rootFolder = Array.from(folders.values()).find(isRootFolder);+ rootFolder?.children.push("folderId");+ cleanupChildRefsMutable("folderId", folders);+ expect(rootFolder).toEqual({+ id: ROOT_FOLDER_ID,+ name: "Root",+ slug: "",+ children: ["homePageId"],+ });+ });++ test("removes duplicate refs from every folder", () => {+ const {+ pages: { folders },+ } = createPages();+ folders.get(ROOT_FOLDER_ID)?.children.push("folderId", "folderId");+ folders.set("folderId", {+ id: "folderId",+ name: "Folder",+ slug: "folder",+ children: ["folderId"],+ });++ cleanupChildRefsMutable("folderId", folders);++ expect(folders.get(ROOT_FOLDER_ID)?.children).toEqual(["homePageId"]);+ expect(folders.get("folderId")?.children).toEqual([]);+ });+});++describe("registerFolderChildMutable", () => {+ test("register a folder child in the root via fallback", () => {+ const { pages } = createPages();+ const { folders } = pages;+ registerFolderChildMutable(pages, "folderId");+ const rootFolder = Array.from(folders.values()).find(isRootFolder);+ expect(rootFolder?.children).toEqual(["homePageId", "folderId"]);+ });++ test("register a folder child in a provided folder", () => {+ const { pages } = createPages();+ const { folders } = pages;+ const folder = {+ id: "folderId",+ name: "Folder",+ slug: "folder",+ children: [],+ };+ folders.set(folder.id, folder);+ registerFolderChildMutable(pages, "folderId2", "folderId");+ expect(folder.children).toEqual(["folderId2"]);+ });++ test("register in a provided folder & cleanup old refs", () => {+ const { pages } = createPages();+ const { folders } = pages;+ const folder = {+ id: "folderId",+ name: "Folder",+ slug: "folder",+ children: [],+ };+ folders.set(folder.id, folder);+ const rootFolder = Array.from(folders.values()).find(isRootFolder);+ registerFolderChildMutable(pages, "folderId", ROOT_FOLDER_ID);+ registerFolderChildMutable(pages, "folderId2", ROOT_FOLDER_ID);++ expect(rootFolder?.children).toEqual([+ "homePageId",+ "folderId",+ "folderId2",+ ]);++ // Moving folderId from root to folderId+ registerFolderChildMutable(pages, "folderId2", "folderId");++ expect(rootFolder?.children).toEqual(["homePageId", "folderId"]);+ expect(folder.children).toEqual(["folderId2"]);+ });++ test("uses rootFolderId for fallback instead of hardcoded root id", () => {+ const { pages } = createPages();+ pages.rootFolderId = "customRoot";+ pages.folders = new Map([+ [+ "customRoot",+ {+ id: "customRoot",+ name: "Root",+ slug: "",+ children: [],+ },+ ],+ ]);++ registerFolderChildMutable(pages, "folderId");++ expect(pages.folders.get("customRoot")?.children).toEqual(["folderId"]);+ });+});++describe("folder creation helpers", () => {+ test("creates and inserts folder into requested parent", () => {+ const { pages } = createPages();+ const folder: Folder = {+ id: "folderId",+ name: "Folder",+ slug: "folder",+ children: [],+ };++ insertFolderMutable({ pages, folder, parentFolderId: ROOT_FOLDER_ID });++ expect(pages.folders.get("folderId")).toEqual({+ id: "folderId",+ name: "Folder",+ slug: "folder",+ children: [],+ });+ expect(pages.folders.get(ROOT_FOLDER_ID)?.children).toEqual([+ "homePageId",+ "folderId",+ ]);+ });++ test("falls back to root folder when inserting into missing parent", () => {+ const { pages } = createPages();+ const folder: Folder = {+ id: "folderId",+ name: "Folder",+ slug: "folder",+ children: [],+ };++ insertFolderMutable({ pages, folder, parentFolderId: "missing" });++ expect(pages.folders.get(ROOT_FOLDER_ID)?.children).toEqual([+ "homePageId",+ "folderId",+ ]);+ });+});++describe("updateFolderFieldsMutable", () => {+ test("updates folder fields and moves folder", () => {+ const { pages } = createPages();+ const folder = {+ id: "folderId",+ name: "Folder",+ slug: "folder",+ children: [],+ };+ const target = {+ id: "targetId",+ name: "Target",+ slug: "target",+ children: [],+ };+ pages.folders.set(folder.id, folder);+ pages.folders.set(target.id, target);+ registerFolderChildMutable(pages, folder.id, ROOT_FOLDER_ID);+ registerFolderChildMutable(pages, target.id, ROOT_FOLDER_ID);++ updateFolderFieldsMutable({+ folder,+ folderId: folder.id,+ pages,+ values: {+ name: "Updated",+ slug: "updated",+ parentFolderId: target.id,+ },+ });++ expect(folder).toMatchObject({ name: "Updated", slug: "updated" });+ expect(pages.folders.get(ROOT_FOLDER_ID)?.children).toEqual([+ "homePageId",+ "targetId",+ ]);+ expect(target.children).toEqual(["folderId"]);+ });++ test("does not update root folder", () => {+ const { pages } = createPages();+ const root = pages.folders.get(ROOT_FOLDER_ID);++ updateFolderFieldsMutable({+ folder: root!,+ folderId: ROOT_FOLDER_ID,+ pages,+ values: { name: "Updated", slug: "updated" },+ });++ expect(root).toMatchObject({ name: "Root", slug: "" });+ });+});++describe("reparent pages and folders", () => {+ test("move page up within single parent", () => {+ const { f, p, register, pages } = createPages();+ register([+ f("folder", [+ p("page1", "/page1"),+ p("page2", "/page2"),+ p("page3", "/page3"),+ ]),+ ]);+ reparentPageOrFolderMutable(pages.folders, "page3", "folder", 1);+ const folder = pages.folders.get("folder");+ expect(folder?.children).toEqual(["page1", "page3", "page2"]);+ });++ test("move page down within single parent", () => {+ const { f, p, register, pages } = createPages();+ register([+ f("folder", [+ p("page1", "/page1"),+ p("page2", "/page2"),+ p("page3", "/page3"),+ ]),+ ]);+ reparentPageOrFolderMutable(pages.folders, "page1", "folder", 2);+ const folder = pages.folders.get("folder");+ expect(folder?.children).toEqual(["page2", "page1", "page3"]);+ });++ test("move page into another folder", () => {+ const { f, p, register, pages } = createPages();+ register([+ f("folder1", [p("page1", "/page1"), p("page2", "/page2")]),+ f("folder2", [p("page3", "/page3")]),+ ]);+ reparentPageOrFolderMutable(pages.folders, "page1", "folder2", 1);+ const folder1 = pages.folders.get("folder1");+ const folder2 = pages.folders.get("folder2");+ expect(folder1?.children).toEqual(["page2"]);+ expect(folder2?.children).toEqual(["page3", "page1"]);+ });++ test("move folder into another folder", () => {+ const { f, register, pages } = createPages();+ register([f("folder1", []), f("folder2", [])]);+ reparentPageOrFolderMutable(pages.folders, "folder1", "folder2", 1);+ expect(Array.from(pages.folders.values())).toEqual([+ expect.objectContaining({+ id: "root",+ children: ["homePageId", "folder2"],+ }),+ expect.objectContaining({ id: "folder1", children: [] }),+ expect.objectContaining({ id: "folder2", children: ["folder1"] }),+ ]);+ });++ test("prevent reparanting folder into itself", () => {+ const { f, register, pages } = createPages();+ register([f("folder1", [])]);+ reparentPageOrFolderMutable(pages.folders, "folder1", "folder1", 1);+ expect(Array.from(pages.folders.values())).toEqual([+ expect.objectContaining({+ id: "root",+ children: ["homePageId", "folder1"],+ }),+ expect.objectContaining({ id: "folder1", children: [] }),+ ]);+ });++ test("prevent reparanting folder own children", () => {+ const { f, register, pages } = createPages();+ register([f("folder1", [f("folder2", [])])]);+ reparentPageOrFolderMutable(pages.folders, "folder1", "folder2", 1);+ expect(Array.from(pages.folders.values())).toEqual([+ expect.objectContaining({+ id: "root",+ children: ["homePageId", "folder1"],+ }),+ expect.objectContaining({ id: "folder2", children: [] }),+ expect.objectContaining({ id: "folder1", children: ["folder2"] }),+ ]);+ });++ test("does not remove unrelated child when item is missing from previous parent", () => {+ const { f, p, register, pages } = createPages();+ register([f("folder", [p("page1", "/page1"), p("page2", "/page2")])]);++ reparentPageOrFolderMutable(pages.folders, "page3", "folder", 1);++ expect(pages.folders.get("folder")?.children).toEqual(["page1", "page2"]);+ });+});diff --git a/apps/builder/app/shared/page-utils/tree.ts b/apps/builder/app/shared/page-utils/tree.tsnew file mode 100644index 0000000000..cc88da5dcf--- /dev/null+++ b/apps/builder/app/shared/page-utils/tree.ts@@ -0,0 +1,159 @@+import {+ findParentFolderByChildId,+ getAllFolders,+ getAllPages,+ getFolderById,+ type Folder,+ type Page,+ type Pages,+} from "@webstudio-is/sdk";+import { getAllChildrenAndSelf } from "@webstudio-is/project-build/runtime/pages";++/**+ * When page or folder needs to be deleted or moved to a different parent,+ * cleanup every existing folder child reference to keep collaboration edge+ * cases from leaving double references behind.+ */+export const cleanupChildRefsMutable = (+ id: Folder["id"] | Page["id"],+ folders: Pages["folders"]+) => {+ for (const folder of Array.from(folders.values())) {+ folder.children = folder.children.filter((childId) => childId !== id);+ }+};++/**+ * Put orphaned pages/folders back into the root folder. Home page is always the+ * first root child and must only be referenced once.+ */+export const reparentOrphansMutable = (pages: Pages) => {+ const children = [pages.rootFolderId];+ for (const folder of getAllFolders(pages)) {+ children.push(...folder.children);+ }++ let rootFolder = getFolderById(pages, pages.rootFolderId);+ if (rootFolder === undefined) {+ rootFolder = {+ id: pages.rootFolderId,+ name: "Root",+ slug: "",+ children: [],+ };+ pages.folders.set(rootFolder.id, rootFolder);+ }++ if (pages.pages.has(pages.homePageId)) {+ let homePageRefCount = 0;+ for (const folder of getAllFolders(pages)) {+ for (const childId of folder.children) {+ if (childId === pages.homePageId) {+ homePageRefCount += 1;+ }+ }+ }+ if (rootFolder.children[0] !== pages.homePageId || homePageRefCount !== 1) {+ cleanupChildRefsMutable(pages.homePageId, pages.folders);+ rootFolder.children.unshift(pages.homePageId);+ children.push(pages.homePageId);+ }+ }++ for (const folder of getAllFolders(pages)) {+ if (children.includes(folder.id) === false) {+ rootFolder.children.push(folder.id);+ }+ }++ for (const page of getAllPages(pages)) {+ if (children.includes(page.id) === false) {+ rootFolder.children.push(page.id);+ }+ }+};++export const registerFolderChildMutable = (+ pages: Pick<Pages, "folders" | "rootFolderId">,+ id: Page["id"] | Folder["id"],+ parentFolderId?: Folder["id"]+) => {+ const { folders } = pages;+ const parentFolder =+ (parentFolderId === undefined ? undefined : folders.get(parentFolderId)) ??+ folders.get(pages.rootFolderId);+ cleanupChildRefsMutable(id, folders);+ parentFolder?.children.push(id);+};++export const insertFolderMutable = ({+ pages,+ folder,+ parentFolderId,+}: {+ pages: Pages;+ folder: Folder;+ parentFolderId?: Folder["id"];+}) => {+ pages.folders.set(folder.id, folder);+ registerFolderChildMutable(pages, folder.id, parentFolderId);+};++export const updateFolderFieldsMutable = ({+ folder,+ folderId,+ pages,+ values,+}: {+ folder: Folder;+ folderId: Folder["id"];+ pages: Pages;+ values: Partial<{+ name: Folder["name"];+ slug: Folder["slug"];+ parentFolderId: Folder["id"];+ }>;+}) => {+ if (folderId === pages.rootFolderId) {+ return;+ }+ if (values.name !== undefined) {+ folder.name = values.name;+ }+ if (values.slug !== undefined) {+ folder.slug = values.slug;+ }+ if (values.parentFolderId !== undefined) {+ registerFolderChildMutable(pages, folderId, values.parentFolderId);+ }+};++export const reparentPageOrFolderMutable = (+ folders: Pages["folders"],+ pageOrFolderId: string,+ newFolderId: string,+ newPosition: number+) => {+ const childrenAndSelf = getAllChildrenAndSelf(+ pageOrFolderId,+ folders,+ "folder"+ );+ if (childrenAndSelf.includes(newFolderId)) {+ return;+ }+ const prevParent = findParentFolderByChildId(pageOrFolderId, folders);+ const nextParent = folders.get(newFolderId);+ if (prevParent === undefined || nextParent === undefined) {+ return;+ }+ const prevPosition = prevParent.children.indexOf(pageOrFolderId);+ if (prevPosition === -1) {+ return;+ }+ if (prevParent.id === nextParent.id && prevPosition < newPosition) {+ newPosition -= 1;+ }+ prevParent.children.splice(prevPosition, 1);+ nextParent.children.splice(newPosition, 0, pageOrFolderId);+};diff --git a/apps/builder/app/shared/resources.test.ts b/apps/builder/app/shared/resource-utils.test.tssimilarity index 97%rename from apps/builder/app/shared/resources.test.tsrename to apps/builder/app/shared/resource-utils.test.tsindex de436d3097..95700e57ea 100644--- a/apps/builder/app/shared/resources.test.ts+++ b/apps/builder/app/shared/resource-utils.test.ts@@ -1,6 +1,6 @@-import { describe, test, expect } from "vitest";+import { describe, expect, test } from "vitest";+import { type ResourceRequest } from "@webstudio-is/sdk";import { getResourceKey } from "./resource-utils";-import type { ResourceRequest } from "@webstudio-is/sdk";describe("getResourceKey - pure function tests", () => {test("generates consistent hash for same resource", () => {diff --git a/apps/builder/app/shared/resource-utils.ts b/apps/builder/app/shared/resource-utils.tsindex 5b71714842..8b196ff584 100644--- a/apps/builder/app/shared/resource-utils.ts+++ b/apps/builder/app/shared/resource-utils.ts@@ -1,5 +1,5 @@import hash from "@emotion/hash";-import type { ResourceRequest } from "@webstudio-is/sdk";+import { type ResourceRequest } from "@webstudio-is/sdk";export const getResourceKey = (resource: ResourceRequest) => {try {diff --git a/apps/builder/app/shared/resources.ts b/apps/builder/app/shared/resources.tsindex 90310e0883..38724f9f8b 100644--- a/apps/builder/app/shared/resources.ts+++ b/apps/builder/app/shared/resources.ts@@ -1,7 +1,7 @@import { atom, computed } from "nanostores";import type { DataSource, Resource, ResourceRequest } from "@webstudio-is/sdk";import { restResourcesLoader } from "./router-utils";-import { computeExpression } from "./data-variables";+import { computeExpression } from "@webstudio-is/project-build/runtime/data";import { fetch } from "./fetch.client";import { getResourceKey } from "./resource-utils";diff --git a/apps/builder/app/shared/router-utils/origins.ts b/apps/builder/app/shared/router-utils/origins.tsindex 2ddf420d5b..8174cf95c5 100644--- a/apps/builder/app/shared/router-utils/origins.ts+++ b/apps/builder/app/shared/router-utils/origins.ts@@ -1,4 +1,4 @@-import { parseBuilderUrl } from "@webstudio-is/http-client";+import { parseBuilderUrl } from "@webstudio-is/protocol";export const getRequestOrigin = (urlStr: string) => {const url = new URL(urlStr);diff --git a/apps/builder/app/shared/share-project/share-project-container.tsx b/apps/builder/app/shared/share-project/share-project-container.tsxindex d895039f78..6aa3f59318 100644--- a/apps/builder/app/shared/share-project/share-project-container.tsx+++ b/apps/builder/app/shared/share-project/share-project-container.tsx@@ -5,6 +5,13 @@ import { trpcClient } from "../trpc/trpc-client";import { ShareProject, type LinkOptions } from "./share-project";import { useStore } from "@nanostores/react";import { $permissions, $purchases } from "../nano-states";+import { toast } from "@webstudio-is/design-system";++const normalizeLinks = (links: LinkOptions[]) =>+ links.map((link) => ({+ ...link,+ canUseApi: link.canUseApi === true,+ }));const useShareProjectContainer = (projectId: string) => {const {@@ -16,15 +23,19 @@ const useShareProjectContainer = (projectId: string) => {trpcClient.authorizationToken.create.useMutation();const { send: removeToken, state: removeState } =trpcClient.authorizationToken.remove.useMutation();- const { send: updateToken, state: updateState } =- trpcClient.authorizationToken.update.useMutation();- const [links, setLinks] = useState(data ?? []);+ const {+ send: updateToken,+ state: updateState,+ error: updateError,+ } = trpcClient.authorizationToken.update.useMutation();+ const [links, setLinks] = useState(normalizeLinks(data ?? []));const [isChangingLink, setIsChangingLink] = useState(false);const deletingLinks = useRef(new Set<string>());+ const lastUpdateError = useRef<string | undefined>(undefined);useEffect(() => {load({ projectId }, (data) => {- setLinks(data ?? []);+ setLinks(normalizeLinks(data ?? []));});}, [load, projectId]);@@ -48,13 +59,30 @@ const useShareProjectContainer = (projectId: string) => {});updateToken(updatedLink, () => {load({ projectId }, (data) => {- setLinks(data ?? []);+ setLinks(normalizeLinks(data ?? []));setIsChangingLink(false);});});}, 100);+ useEffect(() => {+ if (+ updateState !== "idle" ||+ updateError === undefined ||+ updateError === lastUpdateError.current+ ) {+ return;+ }+ lastUpdateError.current = updateError;+ toast.error(updateError);+ setIsChangingLink(false);+ load({ projectId }, (data) => {+ setLinks(normalizeLinks(data ?? []));+ });+ }, [load, projectId, updateError, updateState]);+const handleChange = (link: LinkOptions) => {+ lastUpdateError.current = undefined;setIsChangingLink(true);handleChangeDebounced(link);};@@ -80,7 +108,7 @@ const useShareProjectContainer = (projectId: string) => {},() => {load({ projectId }, (data) => {- setLinks(data ?? []);+ setLinks(normalizeLinks(data ?? []));});});diff --git a/apps/builder/app/shared/share-project/share-project.stories.tsx b/apps/builder/app/shared/share-project/share-project.stories.tsxindex 89bc1c380d..2ad148996a 100644--- a/apps/builder/app/shared/share-project/share-project.stories.tsx+++ b/apps/builder/app/shared/share-project/share-project.stories.tsx@@ -26,6 +26,7 @@ const initialLinks: Array<LinkOptions> = [canClone: false,canCopy: false,canPublish: false,+ canUseApi: false,},{token: nanoid(),@@ -34,6 +35,7 @@ const initialLinks: Array<LinkOptions> = [canClone: false,canCopy: false,canPublish: false,+ canUseApi: false,},{token: nanoid(),@@ -42,6 +44,7 @@ const initialLinks: Array<LinkOptions> = [canClone: false,canCopy: false,canPublish: false,+ canUseApi: false,},];@@ -73,6 +76,7 @@ const useShareProject = (canClone: false,canCopy: false,canPublish: false,+ canUseApi: false,},]);};diff --git a/apps/builder/app/shared/share-project/share-project.test.tsx b/apps/builder/app/shared/share-project/share-project.test.tsxindex 42309f62fd..197516d7d7 100644--- a/apps/builder/app/shared/share-project/share-project.test.tsx+++ b/apps/builder/app/shared/share-project/share-project.test.tsx@@ -3,7 +3,9 @@ import { createRoot, type Root } from "react-dom/client";import { act } from "react-dom/test-utils";import { afterEach, describe, expect, test, vi } from "vitest";import { TooltipProvider } from "@webstudio-is/design-system";-import { ShareProject, type LinkOptions } from "./share-project";+import { ShareProject, __testing__, type LinkOptions } from "./share-project";++const { getApiPermissionDescription } = __testing__;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }@@ -18,6 +20,7 @@ const link: LinkOptions = {canCopy: false,canClone: false,canPublish: false,+ canUseApi: false,};const getElement = <ElementType extends Element>(selector: string) => {@@ -42,6 +45,18 @@ const getControlByLabel = <ElementType extends HTMLElement>(text: string) => {return control as ElementType;};+const hasLabel = (text: string) => {+ return Array.from(document.querySelectorAll("label")).some(+ (label) => label.textContent === text+ );+};++const countLabels = (text: string) => {+ return Array.from(document.querySelectorAll("label")).filter(+ (label) => label.textContent === text+ ).length;+};+const click = (element: Element) => {act(() => {element.dispatchEvent(new MouseEvent("click", { bubbles: true }));@@ -67,9 +82,19 @@ const focusOut = (element: Element, relatedTarget: EventTarget) => {});};+const keyDown = (element: Element, key: string) => {+ act(() => {+ element.dispatchEvent(new KeyboardEvent("keydown", { bubbles: true, key }));+ });+};+const renderShareProject = ({+ allowAdditionalPermissions = true,+ linkOptions = link,onChange,}: {+ allowAdditionalPermissions?: boolean;+ linkOptions?: LinkOptions;onChange: (value: LinkOptions) => void;}) => {const container = document.createElement("div");@@ -80,15 +105,15 @@ const renderShareProject = ({root?.render(createElement(TooltipProvider, {children: createElement(ShareProject, {- links: [link],+ links: [linkOptions],onChange,onDelete: vi.fn(),onCreate: vi.fn(),builderUrl: ({ authToken }) =>`https://example.com?token=${authToken}`,isPending: false,- allowAdditionalPermissions: true,- isFreePlan: false,+ allowAdditionalPermissions,+ isFreePlan: allowAdditionalPermissions === false,}),}));@@ -104,12 +129,58 @@ afterEach(() => {});describe("ShareProject", () => {+ test("documents api permissions per role", () => {+ expect(+ getApiPermissionDescription({+ role: "viewers",+ canPublish: false,+ })+ ).toBe(+ "Allows read-only API access: inspect permissions, project/build snapshots, pages, folders, instances, text, styles, variables, resources, assets, publish history, domains, and asset usage."+ );+ expect(+ getApiPermissionDescription({+ role: "editors",+ canPublish: false,+ })+ ).toBe(+ "Allows viewer API access and content-mode text and prop changes. Enable Can publish to allow publishing and unpublishing. It cannot change pages, design data, assets, variables, resources, or domains."+ );+ expect(+ getApiPermissionDescription({+ role: "editors",+ canPublish: true,+ })+ ).toBe(+ "Allows viewer API access, content-mode text and prop changes, plus publishing and unpublishing project and custom domains. It cannot change pages, design data, assets, variables, resources, or domains."+ );+ expect(+ getApiPermissionDescription({+ role: "builders",+ canPublish: false,+ })+ ).toBe(+ "Allows read and build API access: pages, folders, instances, text, props, styles, design tokens, CSS variables, data variables, resources, assets, patches, and project-domain publish/unpublish."+ );+ expect(+ getApiPermissionDescription({+ role: "administrators",+ canPublish: true,+ })+ ).toBe(+ "Allows full project API access: all read, content, build, asset, publish/unpublish, and domain management operations."+ );+ });+test("saves share link permission changes when link options close", () => {const onChange = vi.fn();renderShareProject({ onChange });const optionsButton = getElement('[aria-label="Menu Button for options"]');click(optionsButton);++ expect(hasLabel("Can publish")).toBe(false);+click(getControlByLabel("Editor"));const publishCheckbox = getControlByLabel<HTMLButtonElement>("Can publish");@@ -128,6 +199,134 @@ describe("ShareProject", () => {});});+ test("shows advanced permissions only for the selected permission", () => {+ const onChange = vi.fn();+ renderShareProject({ onChange });++ click(getElement('[aria-label="Menu Button for options"]'));++ expect(getControlByLabel<HTMLButtonElement>("Can clone")).toBeInstanceOf(+ HTMLButtonElement+ );+ expect(getControlByLabel<HTMLButtonElement>("Can copy")).toBeInstanceOf(+ HTMLButtonElement+ );+ expect(hasLabel("Can publish")).toBe(false);+ expect(countLabels("API")).toBe(1);++ click(getControlByLabel("Builder"));++ expect(hasLabel("Can clone")).toBe(false);+ expect(hasLabel("Can copy")).toBe(false);+ expect(hasLabel("Can publish")).toBe(false);+ expect(countLabels("API")).toBe(1);+ });++ test("saves api permission as an additive capability", () => {+ const onChange = vi.fn();+ renderShareProject({ onChange });++ const optionsButton = getElement('[aria-label="Menu Button for options"]');+ click(optionsButton);++ const apiCheckbox = getControlByLabel<HTMLButtonElement>("API");+ expect(apiCheckbox.disabled).toBe(false);+ click(apiCheckbox);+ click(optionsButton);++ expect(onChange).toHaveBeenCalledWith({+ ...link,+ canUseApi: true,+ });+ });++ test("disables api permission when it requires an upgrade", () => {+ const onChange = vi.fn();+ renderShareProject({+ allowAdditionalPermissions: false,+ onChange,+ });++ const optionsButton = getElement('[aria-label="Menu Button for options"]');+ click(optionsButton);++ const apiCheckbox = getControlByLabel<HTMLButtonElement>("API");+ expect(apiCheckbox.disabled).toBe(true);+ click(apiCheckbox);+ click(optionsButton);++ expect(onChange).not.toHaveBeenCalled();+ });++ test("disables missing api permission when it requires an upgrade", () => {+ const onChange = vi.fn();+ renderShareProject({+ allowAdditionalPermissions: false,+ linkOptions: {+ ...link,+ canUseApi: undefined as unknown as boolean,+ },+ onChange,+ });++ const optionsButton = getElement('[aria-label="Menu Button for options"]');+ click(optionsButton);++ const apiCheckbox = getControlByLabel<HTMLButtonElement>("API");+ expect(apiCheckbox.disabled).toBe(true);+ click(apiCheckbox);+ click(optionsButton);++ expect(onChange).not.toHaveBeenCalled();+ });++ test("allows removing existing api permission without an upgrade", () => {+ const onChange = vi.fn();+ renderShareProject({+ allowAdditionalPermissions: false,+ linkOptions: {+ ...link,+ canUseApi: true,+ },+ onChange,+ });++ const optionsButton = getElement('[aria-label="Menu Button for options"]');+ click(optionsButton);++ const apiCheckbox = getControlByLabel<HTMLButtonElement>("API");+ expect(apiCheckbox.disabled).toBe(false);+ click(apiCheckbox);+ click(optionsButton);++ expect(onChange).toHaveBeenCalledWith({+ ...link,+ canUseApi: false,+ });+ });++ test("keeps api permission when changing high-level permission", () => {+ const onChange = vi.fn();+ renderShareProject({+ linkOptions: {+ ...link,+ canUseApi: true,+ },+ onChange,+ });++ const optionsButton = getElement('[aria-label="Menu Button for options"]');+ click(optionsButton);+ click(getControlByLabel("Builder"));+ click(optionsButton);++ expect(onChange).toHaveBeenCalledWith({+ ...link,+ relation: "builders",+ canUseApi: true,+ });+ });+test("does not save link name while link options remain open", () => {const onChange = vi.fn();renderShareProject({ onChange });@@ -158,4 +357,20 @@ describe("ShareProject", () => {name: "Renamed link",});});++ test("saves current link name when pressing enter immediately after typing", () => {+ const onChange = vi.fn();+ renderShareProject({ onChange });++ click(getElement('[aria-label="Menu Button for options"]'));++ const nameInput = getElement<HTMLInputElement>('input[name="Name"]');+ input(nameInput, "Renamed link");+ keyDown(nameInput, "Enter");++ expect(onChange).toHaveBeenCalledWith({+ ...link,+ name: "Renamed link",+ });+ });});diff --git a/apps/builder/app/shared/share-project/share-project.tsx b/apps/builder/app/shared/share-project/share-project.tsxindex a5378d049c..69557872b4 100644--- a/apps/builder/app/shared/share-project/share-project.tsx+++ b/apps/builder/app/shared/share-project/share-project.tsx@@ -29,7 +29,6 @@ import {Text,InputField,Link,- buttonStyle,IconButton,Checkbox,Grid,@@ -55,20 +54,13 @@ const Item = (props: ComponentProps<typeof Flex>) => (/>);-const PricingUpgradeLink = ({- children = "Upgrade",-}: {- children?: string;-}) => (- <Link- className={buttonStyle({ color: "gradient" })}- color="contrast"- underline="none"- href="https://webstudio.is/pricing"- target="_blank"- >- {children}- </Link>+const UpgradeLink = () => (+ <Flex align="center" gap={1}>+ <UpgradeIcon />+ <Link color="inherit" target="_blank" href="https://webstudio.is/pricing">+ Upgrade+ </Link>+ </Flex>);export const ShareLinkSecurityNotice = () => (@@ -77,40 +69,90 @@ export const ShareLinkSecurityNotice = () => (Sharing links over insecure channels can expose project access. Upgrade tothe Team plan for safer collaboration.</Text>- <Flex align="center" gap={1}>- <UpgradeIcon />- <Link color="inherit" target="_blank" href="https://webstudio.is/pricing">- Upgrade- </Link>- </Flex>+ <UpgradeLink /></PanelBanner>);+const PermissionTooltip = ({+ title,+ children,+}: {+ title: string;+ children: ReactNode;+}) => (+ <Tooltip+ content={+ <Flex direction="column" gap="2" css={{ maxWidth: theme.spacing[28] }}>+ <Text variant="titles">{title}</Text>+ <Text>{children}</Text>+ </Flex>+ }+ variant="wrapped"+ >+ <InfoCircleIcon color={rawTheme.colors.foregroundSubtle} tabIndex={0} />+ </Tooltip>+);++const PermissionTooltipContent = ({+ children,+ upgrade = false,+}: {+ children: ReactNode;+ upgrade?: boolean;+}) => (+ <Flex direction="column">+ {children}+ {upgrade && (+ <Box css={{ mt: theme.spacing[2] }}>+ <UpgradeLink />+ </Box>+ )}+ </Flex>+);++const getApiPermissionDescription = ({+ canPublish,+ role,+}: {+ canPublish: boolean;+ role: Role;+}) => {+ const descriptions: Record<Role, string> = {+ viewers:+ "Allows read-only API access: inspect permissions, project/build snapshots, pages, folders, instances, text, styles, variables, resources, assets, publish history, domains, and asset usage.",+ editors: canPublish+ ? "Allows viewer API access, content-mode text and prop changes, plus publishing and unpublishing project and custom domains. It cannot change pages, design data, assets, variables, resources, or domains."+ : "Allows viewer API access and content-mode text and prop changes. Enable Can publish to allow publishing and unpublishing. It cannot change pages, design data, assets, variables, resources, or domains.",+ builders:+ "Allows read and build API access: pages, folders, instances, text, props, styles, design tokens, CSS variables, data variables, resources, assets, patches, and project-domain publish/unpublish.",+ administrators:+ "Allows full project API access: all read, content, build, asset, publish/unpublish, and domain management operations.",+ };+ return descriptions[role];+};++export const __testing__ = { getApiPermissionDescription };+type PermissionProps = {title: string;- info: ReactNode;+ description: ReactNode;+ upgrade?: boolean;checked: boolean;disabled?: boolean;onCheckedChange: (checked: boolean) => void;};const Permission = ({title,- info,+ description,+ upgrade = false,checked,disabled = false,onCheckedChange,}: PermissionProps) => {const id = useId();- const tooltipContent = (- <Flex direction="column" gap="2" css={{ maxWidth: theme.spacing[28] }}>- <Text variant="titles">{title}</Text>- <Text>{info}</Text>- </Flex>- );-return (- <Flex align="center" gap="1">+ <Flex align="center" gap="1" css={{ whiteSpace: "nowrap" }}><Switchdisabled={disabled}checked={checked}@@ -120,13 +162,61 @@ const Permission = ({<Label disabled={disabled} htmlFor={id}>{title}</Label>- <Tooltip content={tooltipContent} variant="wrapped">- <InfoCircleIcon color={rawTheme.colors.foregroundSubtle} tabIndex={0} />- </Tooltip>+ <PermissionTooltip title={title}>+ <PermissionTooltipContent upgrade={upgrade}>+ {description}+ </PermissionTooltipContent>+ </PermissionTooltip></Flex>);};+type CapabilityProps = {+ id: string;+ title: string;+ description: ReactNode;+ checked: boolean;+ disabled?: boolean;+ onCheckedChange: (checked: boolean) => void;+};++const Capability = ({+ id,+ title,+ description,+ checked,+ disabled = false,+ onCheckedChange,+}: CapabilityProps) => {+ return (+ <Grid+ gap={1}+ flow="column"+ css={{+ alignItems: "center",+ justifyContent: "start",+ whiteSpace: "nowrap",+ }}+ >+ <Checkbox+ disabled={disabled}+ checked={checked}+ onCheckedChange={(value) => {+ if (disabled) {+ return;+ }+ onCheckedChange(Boolean(value));+ }}+ id={id}+ />+ <Label htmlFor={id} disabled={disabled}>+ {title}+ </Label>+ <PermissionTooltip title={title}>{description}</PermissionTooltip>+ </Grid>+ );+};+type MenuProps = {name: string;value: LinkOptions;@@ -142,15 +232,22 @@ const Menu = ({onChange,onDelete,}: MenuProps) => {- const ids = useIds(["name", "canClone", "canCopy", "canPublish"]);+ const ids = useIds([+ "name",+ "canClone",+ "canCopy",+ "canPublish",+ "canUseApi",+ ]);const [isOpen, setIsOpen] = useState(false);const [draftLink, setDraftLink] = useState(value);const draftLinkRef = useRef(value);+ const nameInputRef = useRef<HTMLInputElement>(null);const updateDraftLink = (update: LinkOptionsUpdate) => {- const nextLink = { ...draftLinkRef.current, ...update };- draftLinkRef.current = nextLink;- setDraftLink(nextLink);+ const nextDraftLink = { ...draftLinkRef.current, ...update };+ draftLinkRef.current = nextDraftLink;+ setDraftLink(nextDraftLink);};const handleCheckedChange = (role: Role) => (checked: boolean) => {@@ -159,13 +256,44 @@ const Menu = ({}};- const saveDraftLink = () => {- const draft = draftLinkRef.current;- const nextName = draft.name.trim();+ const renderAdvanced = (role: Role, children: ReactNode) =>+ draftLink.relation === role ? (+ <Grid gap={1} css={{ ml: theme.spacing[6] }}>+ {children}+ </Grid>+ ) : undefined;++ const renderApiCapability = (role: Role) => {+ const canUseApi = draftLink.canUseApi === true;+ const isApiForbidden = !allowAdditionalPermissions && canUseApi === false;+ const description = (+ <PermissionTooltipContent upgrade={!allowAdditionalPermissions}>+ {getApiPermissionDescription({+ canPublish: draftLink.canPublish,+ role,+ })}+ </PermissionTooltipContent>+ );++ return (+ <Capability+ id={ids.canUseApi}+ title="API"+ checked={canUseApi}+ disabled={isApiForbidden}+ onCheckedChange={(canUseApi) => updateDraftLink({ canUseApi })}+ description={description}+ />+ );+ };++ const saveDraftLink = (name = draftLinkRef.current.name) => {+ const nextName = name.trim();const nextLink = {- ...draft,+ ...draftLinkRef.current,name: nextName.length === 0 ? value.name : nextName,};+ draftLinkRef.current = nextLink;if (shallowEqual(getComparableLinkOptions(nextLink),@@ -183,7 +311,7 @@ const Menu = ({open={isOpen}onOpenChange={(open) => {if (open === false) {- saveDraftLink();+ saveDraftLink(nameInputRef.current?.value);} else {draftLinkRef.current = value;setDraftLink(value);@@ -201,8 +329,7 @@ const Menu = ({<PopoverContentaria-label={`Share link options ${name}`}css={{- //padding: 0,- width: theme.spacing[24],+ width: theme.spacing[28],}}sideOffset={0}>@@ -210,12 +337,16 @@ const Menu = ({<Label htmlFor={ids.name}>Name</Label><InputFieldid={ids.name}+ inputRef={nameInputRef}color={draftLink.name.length === 0 ? "error" : undefined}value={draftLink.name}onChange={(event) => updateDraftLink({ name: event.target.value })}+ onInput={(event) =>+ updateDraftLink({ name: event.currentTarget.value })+ }onKeyDown={(event) => {if (event.key === "Enter") {- saveDraftLink();+ saveDraftLink(event.currentTarget.value);setIsOpen(false);}}}@@ -231,182 +362,103 @@ const Menu = ({checked={draftLink.relation === "viewers"}onCheckedChange={handleCheckedChange("viewers")}title={roleLabels.viewers}- info={- <Flex direction="column">- {roleDescriptions.viewers}- {!allowAdditionalPermissions && (- <>- <br />- <br />- Upgrade to a Pro account to set additional permissions.- <br /> <br />- <PricingUpgradeLink />- </>- )}- </Flex>- }+ description={roleDescriptions.viewers}/>-- <Grid- css={{- ml: theme.spacing[6],- }}- >- <Grid- gap={1}- flow={"column"}- css={{- alignItems: "center",- justifyContent: "start",- }}- >- <Checkbox- disabled={- !allowAdditionalPermissions ||- draftLink.relation !== "viewers"- }- checked={draftLink.canClone}- onCheckedChange={(canClone) => {- updateDraftLink({ canClone: Boolean(canClone) });- }}+ {renderAdvanced(+ "viewers",+ <>+ <Capabilityid={ids.canClone}- />- <Label- htmlFor={ids.canClone}- disabled={- !allowAdditionalPermissions ||- draftLink.relation !== "viewers"- }- >- Can clone- </Label>- </Grid>- <Grid- gap={1}- flow={"column"}- css={{- alignItems: "center",- justifyContent: "start",- }}- >- <Checkbox- disabled={- !allowAdditionalPermissions ||- draftLink.relation !== "viewers"+ title="Can clone"+ checked={draftLink.canClone}+ disabled={!allowAdditionalPermissions}+ onCheckedChange={(canClone) => updateDraftLink({ canClone })}+ description={+ <PermissionTooltipContent+ upgrade={!allowAdditionalPermissions}+ >+ Allows viewers to clone the project from this share link.+ </PermissionTooltipContent>}- checked={draftLink.canCopy}- onCheckedChange={(canCopy) => {- updateDraftLink({ canCopy: Boolean(canCopy) });- }}- id={ids.canCopy}/>- <Label- htmlFor={ids.canCopy}- disabled={- !allowAdditionalPermissions ||- draftLink.relation !== "viewers"+ <Capability+ id={ids.canCopy}+ title="Can copy"+ checked={draftLink.canCopy}+ disabled={!allowAdditionalPermissions}+ onCheckedChange={(canCopy) => updateDraftLink({ canCopy })}+ description={+ <PermissionTooltipContent+ upgrade={!allowAdditionalPermissions}+ >+ Allows viewers to copy project content from this share link.+ </PermissionTooltipContent>}- >- Can copy- </Label>- </Grid>- </Grid>+ />+ {renderApiCapability("viewers")}+ </>+ )}<Permissiondisabled={!allowAdditionalPermissions}onCheckedChange={handleCheckedChange("editors")}checked={draftLink.relation === "editors"}title={roleLabels.editors}- info={- <Flex direction="column">- {roleDescriptions.editors}- {!allowAdditionalPermissions && (- <>- <br />- <br />- Upgrade to a Pro account to share with Content Edit- permissions.- <br /> <br />- <PricingUpgradeLink />- </>- )}- </Flex>- }+ description={roleDescriptions.editors}+ upgrade={!allowAdditionalPermissions}/>- <Grid- css={{- ml: theme.spacing[6],- }}- >- <Grid- gap={1}- flow={"column"}- css={{- alignItems: "center",- justifyContent: "start",- }}- >- <Checkbox- disabled={- !allowAdditionalPermissions ||- draftLink.relation !== "editors"- }- checked={draftLink.canPublish}- onCheckedChange={(canPublish) => {- updateDraftLink({ canPublish: Boolean(canPublish) });- }}+ {renderAdvanced(+ "editors",+ <>+ <Capabilityid={ids.canPublish}- />- <Label- htmlFor={ids.canPublish}- disabled={- !allowAdditionalPermissions ||- draftLink.relation !== "editors"+ title="Can publish"+ checked={draftLink.canPublish}+ disabled={!allowAdditionalPermissions}+ onCheckedChange={(canPublish) =>+ updateDraftLink({ canPublish })}- >- Can publish- </Label>- </Grid>- </Grid>-+ description={+ <PermissionTooltipContent+ upgrade={!allowAdditionalPermissions}+ >+ Allows editors to publish from this share link.+ </PermissionTooltipContent>+ }+ />+ {renderApiCapability("editors")}+ </>+ )}<PermissiononCheckedChange={handleCheckedChange("builders")}checked={draftLink.relation === "builders"}title={roleLabels.builders}- info={roleDescriptions.builders}+ description={roleDescriptions.builders}/>+ {renderAdvanced("builders", renderApiCapability("builders"))}<Permissiondisabled={!allowAdditionalPermissions}onCheckedChange={handleCheckedChange("administrators")}checked={draftLink.relation === "administrators"}title={roleLabels.administrators}- info={- <Flex direction="column">- {roleDescriptions.administrators}- {!allowAdditionalPermissions && (- <>- <br />- <br />- Upgrade to a Pro account to share with Admin permissions.- <br /> <br />- <PricingUpgradeLink />- </>- )}- </Flex>- }+ description={roleDescriptions.administrators}+ upgrade={!allowAdditionalPermissions}/>+ {renderAdvanced(+ "administrators",+ renderApiCapability("administrators")+ )}</Item><Separator /><Item>- {/* @todo need a menu item that looks like one from dropdown but without DropdownMenu */}<Buttoncolor="neutral-destructive"onClick={() => {onDelete();}}>- Delete Link+ Delete</Button></Item></PopoverContent>@@ -429,6 +481,7 @@ export type LinkOptions = {canCopy: boolean;canClone: boolean;canPublish: boolean;+ canUseApi: boolean;};type LinkOptionsUpdate = Partial<Omit<LinkOptions, "token">>;diff --git a/apps/builder/app/shared/style-source-utils.test.tsx b/apps/builder/app/shared/style-source-utils.test.tsxdeleted file mode 100644index 47848fa9cb..0000000000--- a/apps/builder/app/shared/style-source-utils.test.tsx+++ /dev/null@@ -1,3414 +0,0 @@-import { enableMapSet } from "immer";-import { describe, test, expect } from "vitest";-import type {- Breakpoint,- StyleDecl,- StyleSource,- StyleSources,- StyleSourceSelection,- StyleSourceSelections,- Styles,-} from "@webstudio-is/sdk";-import type { StyleProperty, StyleValue } from "@webstudio-is/css-engine";-import {- getStyleSourceStylesSignature,- insertStyleSources,- insertTokenStyleSources,- insertPortalLocalStyleSources,- insertLocalStyleSourcesWithNewIds,- deleteStyleSourceMutable,- findUnusedTokens,- deleteStyleSourcesMutable,- validateAndRenameStyleSource,- renameStyleSourceMutable,- toggleStyleSourceLockMutable,- isStyleSourceLocked,- deleteLocalStyleSourcesMutable,- collectStyleSourcesFromInstances,- findDuplicateTokens,- findTokenWithMatchingStyles,- detectTokenConflicts,-} from "./style-source-utils";--enableMapSet();--const getIdValuePair = <T extends { id: string }>(item: T) =>- [item.id, item] as const;--const toMap = <T extends { id: string }>(list: T[]) =>- new Map(list.map(getIdValuePair));--const createStyleDecl = (- styleSourceId: string,- breakpointId: string,- property: StyleProperty,- value: StyleValue | string-): StyleDecl => ({- styleSourceId,- breakpointId,- property,- value: typeof value === "string" ? { type: "unparsed", value } : value,-});--describe("getStyleSourceStylesSignature", () => {- test("generates consistent signature for token styles", () => {- const breakpoints = toMap<Breakpoint>([{ id: "base", label: "base" }]);- const styles: StyleDecl[] = [- createStyleDecl("token1", "base", "color", {- type: "keyword",- value: "red",- }),- createStyleDecl("token1", "base", "fontSize", {- type: "unit",- value: 16,- unit: "px",- }),- ];-- const signature = getStyleSourceStylesSignature(- "token1",- styles,- breakpoints,- new Map()- );-- expect(signature).toBeTruthy();- expect(typeof signature).toBe("string");- });-- test("generates same signature for same styles in different order", () => {- const breakpoints = toMap<Breakpoint>([{ id: "base", label: "base" }]);- const styles1: StyleDecl[] = [- createStyleDecl("token1", "base", "color", {- type: "keyword",- value: "red",- }),- createStyleDecl("token1", "base", "fontSize", {- type: "unit",- value: 16,- unit: "px",- }),- ];- const styles2: StyleDecl[] = [- createStyleDecl("token1", "base", "fontSize", {- type: "unit",- value: 16,- unit: "px",- }),- createStyleDecl("token1", "base", "color", {- type: "keyword",- value: "red",- }),- ];-- const signature1 = getStyleSourceStylesSignature(- "token1",- styles1,- breakpoints,- new Map()- );- const signature2 = getStyleSourceStylesSignature(- "token1",- styles2,- breakpoints,- new Map()- );-- expect(signature1).toBe(signature2);- });-- test("generates different signature for different styles", () => {- const breakpoints = toMap<Breakpoint>([{ id: "base", label: "base" }]);- const styles1: StyleDecl[] = [- createStyleDecl("token1", "base", "color", {- type: "keyword",- value: "red",- }),- ];- const styles2: StyleDecl[] = [- createStyleDecl("token2", "base", "color", {- type: "keyword",- value: "blue",- }),- ];-- const signature1 = getStyleSourceStylesSignature(- "token1",- styles1,- breakpoints,- new Map()- );- const signature2 = getStyleSourceStylesSignature(- "token2",- styles2,- breakpoints,- new Map()- );-- expect(signature1).not.toBe(signature2);- });-- test("handles different breakpoints correctly", () => {- const breakpoints = toMap<Breakpoint>([- { id: "base", label: "base" },- { id: "tablet", label: "tablet", minWidth: 768 },- ]);- const styles1: StyleDecl[] = [- createStyleDecl("token1", "base", "color", {- type: "keyword",- value: "red",- }),- ];- const styles2: StyleDecl[] = [- createStyleDecl("token2", "tablet", "color", {- type: "keyword",- value: "red",- }),- ];-- const signature1 = getStyleSourceStylesSignature(- "token1",- styles1,- breakpoints,- new Map()- );- const signature2 = getStyleSourceStylesSignature(- "token2",- styles2,- breakpoints,- new Map()- );-- expect(signature1).not.toBe(signature2);- });-- test("handles pseudo states correctly", () => {- const breakpoints = toMap<Breakpoint>([{ id: "base", label: "base" }]);- const styles1: StyleDecl[] = [- {- styleSourceId: "token1",- breakpointId: "base",- property: "color" as StyleProperty,- value: { type: "keyword", value: "red" },- },- ];- const styles2: StyleDecl[] = [- {- styleSourceId: "token2",- breakpointId: "base",- property: "color" as StyleProperty,- state: ":hover",- value: { type: "keyword", value: "red" },- },- ];-- const signature1 = getStyleSourceStylesSignature(- "token1",- styles1,- breakpoints,- new Map()- );- const signature2 = getStyleSourceStylesSignature(- "token2",- styles2,- breakpoints,- new Map()- );-- expect(signature1).not.toBe(signature2);- });-- test("handles merged breakpoints correctly", () => {- const breakpoints = toMap<Breakpoint>([{ id: "existing", label: "base" }]);- const mergedBreakpointIds = new Map([["fragment", "existing"]]);- const styles1: StyleDecl[] = [- createStyleDecl("token1", "existing", "color", {- type: "keyword",- value: "red",- }),- ];- const styles2: StyleDecl[] = [- createStyleDecl("token2", "fragment", "color", {- type: "keyword",- value: "red",- }),- ];-- const signature1 = getStyleSourceStylesSignature(- "token1",- styles1,- breakpoints,- new Map()- );- const signature2 = getStyleSourceStylesSignature(- "token2",- styles2,- breakpoints,- mergedBreakpointIds- );-- // Should be the same because fragment breakpoint maps to existing- expect(signature1).toBe(signature2);- });-- test("handles complex multi-property multi-breakpoint styles", () => {- const breakpoints = toMap<Breakpoint>([- { id: "base", label: "base" },- { id: "tablet", label: "tablet", minWidth: 768 },- { id: "desktop", label: "desktop", minWidth: 1200 },- ]);- const styles1: StyleDecl[] = [- createStyleDecl("token1", "base", "color", {- type: "keyword",- value: "red",- }),- createStyleDecl("token1", "tablet", "color", {- type: "keyword",- value: "blue",- }),- createStyleDecl("token1", "desktop", "fontSize", {- type: "unit",- value: 20,- unit: "px",- }),- ];- // Same styles but in different order- const styles2: StyleDecl[] = [- createStyleDecl("token2", "desktop", "fontSize", {- type: "unit",- value: 20,- unit: "px",- }),- createStyleDecl("token2", "base", "color", {- type: "keyword",- value: "red",- }),- createStyleDecl("token2", "tablet", "color", {- type: "keyword",- value: "blue",- }),- ];-- const signature1 = getStyleSourceStylesSignature(- "token1",- styles1,- breakpoints,- new Map()- );- const signature2 = getStyleSourceStylesSignature(- "token2",- styles2,- breakpoints,- new Map()- );-- expect(signature1).toBe(signature2);- });-});--describe("insertStyleSources", () => {- // Case 2: Same styles AND same name -> reuse existing token- test("token with same styles and same name reuses existing token", () => {- const breakpoints = toMap<Breakpoint>([{ id: "base", label: "base" }]);- const existingStyleSources = toMap<StyleSource>([- { id: "existingToken", type: "token", name: "primaryColor" },- ]);- const existingStyles = new Map<string, StyleDecl>([- [- "existingToken:base:color:",- createStyleDecl("existingToken", "base", "color", {- type: "keyword",- value: "red",- }),- ],- [- "existingToken:base:fontSize:",- createStyleDecl("existingToken", "base", "fontSize", {- type: "unit",- value: 16,- unit: "px",- }),- ],- ]);-- const fragmentStyleSources: StyleSource[] = [- { id: "newToken", type: "token", name: "primaryColor" },- ];- const fragmentStyles: StyleDecl[] = [- createStyleDecl("newToken", "base", "color", {- type: "keyword",- value: "red",- }),- createStyleDecl("newToken", "base", "fontSize", {- type: "unit",- value: 16,- unit: "px",- }),- ];-- const { styleSourceIdMap, updatedStyleSources } = insertStyleSources({- fragmentStyleSources,- fragmentStyles,- existingStyleSources,- existingStyles,- breakpoints,- mergedBreakpointIds: new Map(),- });-- // Should reuse existing token, not create a new one- expect(Array.from(updatedStyleSources.values())).toEqual([- { id: "existingToken", type: "token", name: "primaryColor" },- ]);- // Should map newToken -> existingToken- expect(styleSourceIdMap.get("newToken")).toBe("existingToken");- });-- // Case 3: Same styles but different name -> insert new token with original name- test("token with same styles but different name inserts new token", () => {- const breakpoints = toMap<Breakpoint>([{ id: "base", label: "base" }]);- const existingStyleSources = toMap<StyleSource>([- { id: "token1", type: "token", name: "primaryColor" },- ]);- const existingStyles = new Map<string, StyleDecl>([- [- "token1:base:color:",- createStyleDecl("token1", "base", "color", {- type: "keyword",- value: "red",- }),- ],- ]);-- const fragmentStyleSources: StyleSource[] = [- { id: "token2", type: "token", name: "accentColor" },- ];- const fragmentStyles: StyleDecl[] = [- createStyleDecl("token2", "base", "color", {- type: "keyword",- value: "red",- }),- ];-- const { styleSourceIds, styleSourceIdMap, updatedStyleSources } =- insertStyleSources({- fragmentStyleSources,- fragmentStyles,- existingStyleSources,- existingStyles,- breakpoints,- mergedBreakpointIds: new Map(),- });-- // Should insert new token with its original name- const tokens = Array.from(updatedStyleSources.values());- expect(tokens).toHaveLength(2);- expect(tokens[0]).toEqual({- id: "token1",- type: "token",- name: "primaryColor",- });- expect(tokens[1]).toMatchObject({ type: "token", name: "accentColor" });- expect(tokens[1].id).not.toBe("token2"); // Should have new ID- expect(styleSourceIds.has("token2")).toBe(true);- expect(styleSourceIdMap.get("token2")).toBe(tokens[1].id);- });-- // Case 4: Different styles but same name -> add counter suffix- test("token with different styles but same name adds counter suffix", () => {- const breakpoints = toMap<Breakpoint>([{ id: "base", label: "base" }]);- const existingStyleSources = toMap<StyleSource>([- { id: "token1", type: "token", name: "myToken" },- ]);- const existingStyles = new Map<string, StyleDecl>([- [- "token1:base:color:",- createStyleDecl("token1", "base", "color", {- type: "keyword",- value: "blue",- }),- ],- ]);-- const fragmentStyleSources: StyleSource[] = [- { id: "token2", type: "token", name: "myToken" },- ];- const fragmentStyles: StyleDecl[] = [- createStyleDecl("token2", "base", "color", {- type: "keyword",- value: "red",- }),- ];-- const { styleSourceIds, styleSourceIdMap, updatedStyleSources } =- insertStyleSources({- fragmentStyleSources,- fragmentStyles,- existingStyleSources,- existingStyles,- breakpoints,- mergedBreakpointIds: new Map(),- });-- // Should add counter suffix to the new token- const tokens = Array.from(updatedStyleSources.values());- expect(tokens).toHaveLength(2);- expect(tokens[0]).toEqual({ id: "token1", type: "token", name: "myToken" });- expect(tokens[1]).toMatchObject({ type: "token", name: "myToken-1" });- expect(tokens[1].id).not.toBe("token2"); // Should have new ID- expect(styleSourceIds.has("token2")).toBe(true);- expect(styleSourceIdMap.get("token2")).toBe(tokens[1].id);- });-- // Case 4b: Multiple counter suffixes- test("token with name conflict increments counter correctly", () => {- const breakpoints = toMap<Breakpoint>([{ id: "base", label: "base" }]);- const existingStyleSources = toMap<StyleSource>([- { id: "token1", type: "token", name: "myToken" },- { id: "token2", type: "token", name: "myToken-1" },- { id: "token3", type: "token", name: "myToken-2" },- ]);- const existingStyles = new Map<string, StyleDecl>([- [- "token1:base:color:",- createStyleDecl("token1", "base", "color", {- type: "keyword",- value: "blue",- }),- ],- [- "token2:base:color:",- createStyleDecl("token2", "base", "color", {- type: "keyword",- value: "green",- }),- ],- [- "token3:base:color:",- createStyleDecl("token3", "base", "color", {- type: "keyword",- value: "yellow",- }),- ],- ]);-- const fragmentStyleSources: StyleSource[] = [- { id: "token4", type: "token", name: "myToken" },- ];- const fragmentStyles: StyleDecl[] = [- createStyleDecl("token4", "base", "color", {- type: "keyword",- value: "red",- }),- ];-- const { updatedStyleSources } = insertStyleSources({- fragmentStyleSources,- fragmentStyles,- existingStyleSources,- existingStyles,- breakpoints,- mergedBreakpointIds: new Map(),- });-- // Should use counter 3- const tokens = Array.from(updatedStyleSources.values());- expect(tokens).toHaveLength(4);- expect(tokens[0]).toEqual({ id: "token1", type: "token", name: "myToken" });- expect(tokens[1]).toEqual({- id: "token2",- type: "token",- name: "myToken-1",- });- expect(tokens[2]).toEqual({- id: "token3",- type: "token",- name: "myToken-2",- });- expect(tokens[3]).toMatchObject({ type: "token", name: "myToken-3" });- expect(tokens[3].id).not.toBe("token4"); // Should have new ID- });-- // Case 6: Different styles and different name -> insert as-is- test("token with different styles and different name inserts normally", () => {- const breakpoints = toMap<Breakpoint>([{ id: "base", label: "base" }]);- const existingStyleSources = toMap<StyleSource>([- { id: "token1", type: "token", name: "primaryColor" },- ]);- const existingStyles = new Map<string, StyleDecl>([- [- "token1:base:color:",- createStyleDecl("token1", "base", "color", {- type: "keyword",- value: "blue",- }),- ],- ]);-- const fragmentStyleSources: StyleSource[] = [- { id: "token2", type: "token", name: "secondaryColor" },- ];- const fragmentStyles: StyleDecl[] = [- createStyleDecl("token2", "base", "color", {- type: "keyword",- value: "red",- }),- ];-- const { styleSourceIds, styleSourceIdMap, updatedStyleSources } =- insertStyleSources({- fragmentStyleSources,- fragmentStyles,- existingStyleSources,- existingStyles,- breakpoints,- mergedBreakpointIds: new Map(),- });-- // Should insert new token normally- const tokens = Array.from(updatedStyleSources.values());- expect(tokens).toHaveLength(2);- expect(tokens[0]).toEqual({- id: "token1",- type: "token",- name: "primaryColor",- });- expect(tokens[1]).toMatchObject({ type: "token", name: "secondaryColor" });- expect(tokens[1].id).not.toBe("token2"); // Should have new ID- expect(styleSourceIds.has("token2")).toBe(true);- expect(styleSourceIdMap.get("token2")).toBe(tokens[1].id);- });-- // Case 3 safeguard: Same styles but different name gets suffix when name conflicts- test("token with same styles but different name adds suffix when name already exists", () => {- const breakpoints = toMap<Breakpoint>([{ id: "base", label: "base" }]);- const existingStyleSources = toMap<StyleSource>([- { id: "token1", type: "token", name: "primaryColor" },- { id: "token2", type: "token", name: "accentColor" }, // This name is taken- ]);- const existingStyles = new Map<string, StyleDecl>([- [- "token1:base:color:",- createStyleDecl("token1", "base", "color", {- type: "keyword",- value: "red",- }),- ],- [- "token2:base:fontSize:",- createStyleDecl("token2", "base", "fontSize", {- type: "unit",- value: 16,- unit: "px",- }),- ],- ]);-- const fragmentStyleSources: StyleSource[] = [- { id: "token3", type: "token", name: "accentColor" },- ];- const fragmentStyles: StyleDecl[] = [- createStyleDecl("token3", "base", "color", {- type: "keyword",- value: "red",- }),- ];-- const { updatedStyleSources } = insertStyleSources({- fragmentStyleSources,- fragmentStyles,- existingStyleSources,- existingStyles,- breakpoints,- mergedBreakpointIds: new Map(),- });-- // Should add counter suffix to prevent duplicate name- const tokens = Array.from(updatedStyleSources.values());- expect(tokens).toHaveLength(3);- expect(tokens[0]).toEqual({- id: "token1",- type: "token",- name: "primaryColor",- });- expect(tokens[1]).toEqual({- id: "token2",- type: "token",- name: "accentColor",- });- expect(tokens[2]).toMatchObject({ type: "token", name: "accentColor-1" });- expect(tokens[2].id).not.toBe("token3"); // Should have new ID- });-- // Case 6 safeguard: Different styles and different name gets suffix when name conflicts- test("token with different styles and name adds suffix when name already exists", () => {- const breakpoints = toMap<Breakpoint>([{ id: "base", label: "base" }]);- const existingStyleSources = toMap<StyleSource>([- { id: "token1", type: "token", name: "primaryColor" },- { id: "token2", type: "token", name: "secondaryColor" }, // This name is taken- ]);- const existingStyles = new Map<string, StyleDecl>([- [- "token1:base:color:",- createStyleDecl("token1", "base", "color", {- type: "keyword",- value: "blue",- }),- ],- [- "token2:base:color:",- createStyleDecl("token2", "base", "color", {- type: "keyword",- value: "green",- }),- ],- ]);-- const fragmentStyleSources: StyleSource[] = [- { id: "token3", type: "token", name: "secondaryColor" },- ];- const fragmentStyles: StyleDecl[] = [- createStyleDecl("token3", "base", "color", {- type: "keyword",- value: "red",- }),- ];-- const { updatedStyleSources } = insertStyleSources({- fragmentStyleSources,- fragmentStyles,- existingStyleSources,- existingStyles,- breakpoints,- mergedBreakpointIds: new Map(),- });-- // Should add counter suffix to prevent duplicate name- const tokens = Array.from(updatedStyleSources.values());- expect(tokens).toHaveLength(3);- expect(tokens[0]).toEqual({- id: "token1",- type: "token",- name: "primaryColor",- });- expect(tokens[1]).toEqual({- id: "token2",- type: "token",- name: "secondaryColor",- });- expect(tokens[2]).toMatchObject({- type: "token",- name: "secondaryColor-1",- });- expect(tokens[2].id).not.toBe("token3"); // Should have new ID- });-- // Test that existing token with same styles but different name stays untouched- test("existing token with matching styles but different name stays untouched when inserting new token", () => {- const breakpoints = toMap<Breakpoint>([{ id: "base", label: "base" }]);- const existingStyleSources = toMap<StyleSource>([- { id: "existingToken", type: "token", name: "primaryColor" },- ]);- const existingStyles = new Map<string, StyleDecl>([- [- "existingToken:base:color:",- createStyleDecl("existingToken", "base", "color", {- type: "keyword",- value: "red",- }),- ],- [- "existingToken:base:fontSize:",- createStyleDecl("existingToken", "base", "fontSize", {- type: "unit",- value: 16,- unit: "px",- }),- ],- ]);-- const fragmentStyleSources: StyleSource[] = [- { id: "newToken", type: "token", name: "accentColor" },- ];- const fragmentStyles: StyleDecl[] = [- createStyleDecl("newToken", "base", "color", {- type: "keyword",- value: "red",- }),- createStyleDecl("newToken", "base", "fontSize", {- type: "unit",- value: 16,- unit: "px",- }),- ];-- const { updatedStyleSources } = insertStyleSources({- fragmentStyleSources,- fragmentStyles,- existingStyleSources,- existingStyles,- breakpoints,- mergedBreakpointIds: new Map(),- });-- // Should insert new token with its own name, leaving existing one untouched- const tokens = Array.from(updatedStyleSources.values());- expect(tokens).toHaveLength(2);- expect(tokens[0]).toEqual({- id: "existingToken",- type: "token",- name: "primaryColor",- });- expect(tokens[1]).toMatchObject({ type: "token", name: "accentColor" });- expect(tokens[1].id).not.toBe("newToken"); // Should have new ID- });-- // Critical test: inserting base name when suffixed version exists- test("inserting token 'bbb' when 'bbb-1' with same styles exists inserts both tokens", () => {- const breakpoints = toMap<Breakpoint>([{ id: "base", label: "base" }]);- const existingStyleSources = toMap<StyleSource>([- { id: "existingToken", type: "token", name: "bbb-1" },- ]);- const existingStyles = new Map<string, StyleDecl>([- [- "existingToken:base:color:",- createStyleDecl("existingToken", "base", "color", {- type: "keyword",- value: "blue",- }),- ],- ]);-- const fragmentStyleSources: StyleSource[] = [- { id: "newToken", type: "token", name: "bbb" },- ];- const fragmentStyles: StyleDecl[] = [- createStyleDecl("newToken", "base", "color", {- type: "keyword",- value: "blue",- }),- ];-- const { styleSourceIdMap, updatedStyleSources } = insertStyleSources({- fragmentStyleSources,- fragmentStyles,- existingStyleSources,- existingStyles,- breakpoints,- mergedBreakpointIds: new Map(),- });-- // Both tokens should exist- const tokens = Array.from(updatedStyleSources.values());- expect(tokens).toHaveLength(2);- expect(tokens[0]).toEqual({- id: "existingToken",- type: "token",- name: "bbb-1",- });- expect(tokens[1]).toMatchObject({ type: "token", name: "bbb" }); // Different name, so inserted as-is- expect(tokens[1].id).not.toBe("newToken"); // Should have new ID- expect(styleSourceIdMap.get("newToken")).toBe(tokens[1].id);- });-- // Test merge conflict resolution- test('token with different styles and same name merges when conflictResolution="merge"', () => {- const breakpoints = toMap<Breakpoint>([{ id: "base", label: "base" }]);- const existingStyleSources = toMap<StyleSource>([- { id: "existingToken", type: "token", name: "primaryColor" },- ]);- const existingStyles = new Map<string, StyleDecl>([- [- "existingToken:base:color:",- createStyleDecl("existingToken", "base", "color", {- type: "keyword",- value: "blue",- }),- ],- [- "existingToken:base:fontSize:",- createStyleDecl("existingToken", "base", "fontSize", {- type: "unit",- value: 16,- unit: "px",- }),- ],- ]);-- const fragmentStyleSources: StyleSource[] = [- { id: "newToken", type: "token", name: "primaryColor" },- ];- const fragmentStyles: StyleDecl[] = [- createStyleDecl("newToken", "base", "color", {- type: "keyword",- value: "red", // Different color - should override- }),- createStyleDecl("newToken", "base", "fontWeight", {- type: "keyword",- value: "bold", // Additional property - should be added- }),- ];-- const { styleSourceIds, styleSourceIdMap, updatedStyleSources } =- insertStyleSources({- fragmentStyleSources,- fragmentStyles,- existingStyleSources,- existingStyles,- breakpoints,- mergedBreakpointIds: new Map(),- conflictResolution: "merge",- });-- // Should keep existing token (no new token created)- const tokens = Array.from(updatedStyleSources.values());- expect(tokens).toHaveLength(1);- expect(tokens[0]).toEqual({- id: "existingToken",- type: "token",- name: "primaryColor",- });-- // Should map the fragment token to the existing token- expect(styleSourceIdMap.get("newToken")).toBe("existingToken");-- // Should mark the fragment token for style insertion- // This tells insertWebstudioFragment to insert these styles, which will:- // - Override existing "color" from blue to red- // - Keep existing "fontSize" at 16px- // - Add new "fontWeight" bold- expect(styleSourceIds.has("newToken")).toBe(true);- });-});--// Tests for insertPortalLocalStyleSources--describe("insertPortalLocalStyleSources", () => {- test("inserts local style sources and styles for portal content", () => {- const fragmentStyleSources: StyleSource[] = [- { type: "local", id: "local1" },- { type: "token", id: "token1", name: "myToken" },- ];- const fragmentStyleSourceSelections: StyleSourceSelection[] = [- { instanceId: "instance1", values: ["local1", "token1"] },- { instanceId: "instance2", values: ["local1"] },- ];- const fragmentStyles: StyleDecl[] = [- {- breakpointId: "bp1",- styleSourceId: "local1",- property: "width",- value: { type: "unit", value: 100, unit: "px" },- },- {- breakpointId: "bp2",- styleSourceId: "local1",- property: "height",- value: { type: "unit", value: 50, unit: "px" },- },- ];- const instanceIds = new Set(["instance1"]);- const styleSources: StyleSources = new Map();- const styleSourceSelections: StyleSourceSelections = new Map();- const styles: Styles = new Map();- const mergedBreakpointIds = new Map([["bp2", "bp2-merged"]]);-- insertPortalLocalStyleSources({- fragmentStyleSources,- fragmentStyleSourceSelections,- fragmentStyles,- instanceIds,- styleSources,- styleSourceSelections,- styles,- mergedBreakpointIds,- });-- // Should only insert for instance1 (in instanceIds set)- expect(styleSourceSelections.has("instance1")).toBe(true);- expect(styleSourceSelections.has("instance2")).toBe(false);-- // Should insert local style source- expect(styleSources.get("local1")).toEqual({ type: "local", id: "local1" });-- // Should insert styles with merged breakpoint IDs- expect(styles.size).toBe(2);- const stylesArray = Array.from(styles.values());- expect(stylesArray).toContainEqual({- breakpointId: "bp1",- styleSourceId: "local1",- property: "width",- value: { type: "unit", value: 100, unit: "px" },- });- expect(stylesArray).toContainEqual({- breakpointId: "bp2-merged",- styleSourceId: "local1",- property: "height",- value: { type: "unit", value: 50, unit: "px" },- });- });-- test("preserves original IDs for portal content", () => {- const fragmentStyleSources: StyleSource[] = [- { type: "local", id: "portal-local-123" },- ];- const fragmentStyleSourceSelections: StyleSourceSelection[] = [- { instanceId: "portal-instance", values: ["portal-local-123"] },- ];- const fragmentStyles: StyleDecl[] = [- {- breakpointId: "bp1",- styleSourceId: "portal-local-123",- property: "color",- value: { type: "keyword", value: "red" },- },- ];- const instanceIds = new Set(["portal-instance"]);- const styleSources: StyleSources = new Map();- const styleSourceSelections: StyleSourceSelections = new Map();- const styles: Styles = new Map();- const mergedBreakpointIds = new Map();-- insertPortalLocalStyleSources({- fragmentStyleSources,- fragmentStyleSourceSelections,- fragmentStyles,- instanceIds,- styleSources,- styleSourceSelections,- styles,- mergedBreakpointIds,- });-- // IDs should be preserved exactly- expect(styleSources.get("portal-local-123")).toEqual({- type: "local",- id: "portal-local-123",- });- expect(styleSourceSelections.get("portal-instance")).toEqual({- instanceId: "portal-instance",- values: ["portal-local-123"],- });- });-- test("skips instances not in instanceIds set", () => {- const fragmentStyleSources: StyleSource[] = [- { type: "local", id: "local1" },- ];- const fragmentStyleSourceSelections: StyleSourceSelection[] = [- { instanceId: "included", values: ["local1"] },- { instanceId: "excluded", values: ["local1"] },- ];- const fragmentStyles: StyleDecl[] = [- {- breakpointId: "bp1",- styleSourceId: "local1",- property: "width",- value: { type: "unit", value: 100, unit: "px" },- },- ];- const instanceIds = new Set(["included"]);- const styleSources: StyleSources = new Map();- const styleSourceSelections: StyleSourceSelections = new Map();- const styles: Styles = new Map();- const mergedBreakpointIds = new Map();-- insertPortalLocalStyleSources({- fragmentStyleSources,- fragmentStyleSourceSelections,- fragmentStyles,- instanceIds,- styleSources,- styleSourceSelections,- styles,- mergedBreakpointIds,- });-- expect(styleSourceSelections.has("included")).toBe(true);- expect(styleSourceSelections.has("excluded")).toBe(false);- });-});--// Tests for insertLocalStyleSourcesWithNewIds--describe("insertLocalStyleSourcesWithNewIds", () => {- test("generates new IDs for local style sources", () => {- const fragmentStyleSources: StyleSource[] = [- { type: "local", id: "old-local-1" },- ];- const fragmentStyleSourceSelections: StyleSourceSelection[] = [- { instanceId: "old-instance", values: ["old-local-1"] },- ];- const fragmentStyles: StyleDecl[] = [- {- breakpointId: "bp1",- styleSourceId: "old-local-1",- property: "marginTop" as StyleProperty,- value: { type: "unit", value: 10, unit: "px" },- },- ];- const fragmentInstanceIds = new Set(["old-instance"]);- const newInstanceIds = new Map([["old-instance", "new-instance"]]);- const styleSourceIdMap = new Map();- const styleSources: StyleSources = new Map();- const styleSourceSelections: StyleSourceSelections = new Map();- const styles: Styles = new Map();- const mergedBreakpointIds = new Map();-- insertLocalStyleSourcesWithNewIds({- fragmentStyleSources,- fragmentStyleSourceSelections,- fragmentStyles,- fragmentInstanceIds,- newInstanceIds,- styleSourceIdMap,- styleSources,- styleSourceSelections,- styles,- mergedBreakpointIds,- });-- // Should create new local style source with different ID- expect(styleSources.size).toBe(1);- const newLocalStyleSource = Array.from(styleSources.values())[0];- expect(newLocalStyleSource.type).toBe("local");- expect(newLocalStyleSource.id).not.toBe("old-local-1");-- // Should map to new instance ID- expect(styleSourceSelections.has("new-instance")).toBe(true);- expect(styleSourceSelections.has("old-instance")).toBe(false);-- // Should create style with new style source ID- expect(styles.size).toBe(1);- const newStyle = Array.from(styles.values())[0];- expect(newStyle.styleSourceId).toBe(newLocalStyleSource.id);- });-- test("merges local styles into existing ROOT_INSTANCE_ID local source", async () => {- const { ROOT_INSTANCE_ID } = await import("@webstudio-is/sdk");-- const fragmentStyleSources: StyleSource[] = [- { type: "local", id: "fragment-local" },- ];- const fragmentStyleSourceSelections: StyleSourceSelection[] = [- { instanceId: ROOT_INSTANCE_ID, values: ["fragment-local"] },- ];- const fragmentStyles: StyleDecl[] = [- {- breakpointId: "bp1",- styleSourceId: "fragment-local",- property: "fontFamily",- value: { type: "fontFamily", value: ["Arial"] },- },- ];- const fragmentInstanceIds = new Set([ROOT_INSTANCE_ID]);- const newInstanceIds = new Map();- const styleSourceIdMap = new Map();-- // Existing ROOT local style source- const existingRootLocal: StyleSource = {- type: "local",- id: "existing-root-local",- };- const styleSources: StyleSources = new Map([- ["existing-root-local", existingRootLocal],- ]);- const styleSourceSelections: StyleSourceSelections = new Map([- [- ROOT_INSTANCE_ID,- { instanceId: ROOT_INSTANCE_ID, values: ["existing-root-local"] },- ],- ]);- const styles: Styles = new Map();- const mergedBreakpointIds = new Map();-- insertLocalStyleSourcesWithNewIds({- fragmentStyleSources,- fragmentStyleSourceSelections,- fragmentStyles,- fragmentInstanceIds,- newInstanceIds,- styleSourceIdMap,- styleSources,- styleSourceSelections,- styles,- mergedBreakpointIds,- });-- // Should reuse existing ROOT local style source, not create new one- expect(styleSources.size).toBe(1);- expect(styleSources.get("existing-root-local")).toBe(existingRootLocal);-- // Style should use existing local style source ID- expect(styles.size).toBe(1);- const style = Array.from(styles.values())[0];- expect(style.styleSourceId).toBe("existing-root-local");- });-- test("creates new local source for non-ROOT instances even if local exists", () => {- const fragmentStyleSources: StyleSource[] = [- { type: "local", id: "fragment-local" },- ];- const fragmentStyleSourceSelections: StyleSourceSelection[] = [- { instanceId: "regular-instance", values: ["fragment-local"] },- ];- const fragmentStyles: StyleDecl[] = [- {- breakpointId: "bp1",- styleSourceId: "fragment-local",- property: "paddingTop" as StyleProperty,- value: { type: "unit", value: 20, unit: "px" },- },- ];- const fragmentInstanceIds = new Set(["regular-instance"]);- const newInstanceIds = new Map();- const styleSourceIdMap = new Map();-- // Existing local style source for this instance- const existingLocal: StyleSource = { type: "local", id: "existing-local" };- const styleSources: StyleSources = new Map([- ["existing-local", existingLocal],- ]);- const styleSourceSelections: StyleSourceSelections = new Map([- [- "regular-instance",- { instanceId: "regular-instance", values: ["existing-local"] },- ],- ]);- const styles: Styles = new Map();- const mergedBreakpointIds = new Map();-- insertLocalStyleSourcesWithNewIds({- fragmentStyleSources,- fragmentStyleSourceSelections,- fragmentStyles,- fragmentInstanceIds,- newInstanceIds,- styleSourceIdMap,- styleSources,- styleSourceSelections,- styles,- mergedBreakpointIds,- });-- // Should create NEW local style source (not merge)- expect(styleSources.size).toBe(2);- const newLocalId = Array.from(styleSources.keys()).find(- (id) => id !== "existing-local"- );- expect(newLocalId).toBeDefined();-- // Style should use new local style source ID- const style = Array.from(styles.values())[0];- expect(style.styleSourceId).toBe(newLocalId);- });-- test("handles token remapping in styleSourceIdMap", () => {- const fragmentStyleSources: StyleSource[] = [- { type: "local", id: "local1" },- { type: "token", id: "old-token", name: "oldToken" },- ];- const fragmentStyleSourceSelections: StyleSourceSelection[] = [- { instanceId: "instance1", values: ["local1", "old-token"] },- ];- const fragmentStyles: StyleDecl[] = [- {- breakpointId: "bp1",- styleSourceId: "local1",- property: "color",- value: { type: "keyword", value: "blue" },- },- ];- const fragmentInstanceIds = new Set(["instance1"]);- const newInstanceIds = new Map();-- // Token was already mapped to existing token- const styleSourceIdMap = new Map([["old-token", "existing-token"]]);-- const styleSources: StyleSources = new Map();- const styleSourceSelections: StyleSourceSelections = new Map();- const styles: Styles = new Map();- const mergedBreakpointIds = new Map();-- insertLocalStyleSourcesWithNewIds({- fragmentStyleSources,- fragmentStyleSourceSelections,- fragmentStyles,- fragmentInstanceIds,- newInstanceIds,- styleSourceIdMap,- styleSources,- styleSourceSelections,- styles,- mergedBreakpointIds,- });-- // styleSourceSelection should reference the mapped token ID- const selection = styleSourceSelections.get("instance1");- expect(selection?.values).toContain("existing-token");- expect(selection?.values).not.toContain("old-token");- });-- test("applies merged breakpoint IDs to styles", () => {- const fragmentStyleSources: StyleSource[] = [- { type: "local", id: "local1" },- ];- const fragmentStyleSourceSelections: StyleSourceSelection[] = [- { instanceId: "instance1", values: ["local1"] },- ];- const fragmentStyles: StyleDecl[] = [- {- breakpointId: "old-bp",- styleSourceId: "local1",- property: "display",- value: { type: "keyword", value: "flex" },- },- ];- const fragmentInstanceIds = new Set(["instance1"]);- const newInstanceIds = new Map();- const styleSourceIdMap = new Map();- const styleSources: StyleSources = new Map();- const styleSourceSelections: StyleSourceSelections = new Map();- const styles: Styles = new Map();- const mergedBreakpointIds = new Map([["old-bp", "merged-bp"]]);-- insertLocalStyleSourcesWithNewIds({- fragmentStyleSources,- fragmentStyleSourceSelections,- fragmentStyles,- fragmentInstanceIds,- newInstanceIds,- styleSourceIdMap,- styleSources,- styleSourceSelections,- styles,- mergedBreakpointIds,- });-- // Style should use merged breakpoint ID- const style = Array.from(styles.values())[0];- expect(style.breakpointId).toBe("merged-bp");- });-});--describe("insertLocalStyleSourcesWithNewIds in content mode", () => {- test("copies local styles for existing breakpoints and reuses token ids", () => {- const fragmentStyleSources: StyleSource[] = [- { type: "local", id: "fragment-local" },- { type: "token", id: "existing-token", name: "Existing" },- ];- const fragmentStyleSourceSelections: StyleSourceSelection[] = [- { instanceId: "fragment-instance", values: ["fragment-local"] },- {- instanceId: "fragment-instance-with-token",- values: ["fragment-local", "existing-token"],- },- ];- const fragmentStyles: StyleDecl[] = [- createStyleDecl("fragment-local", "base", "color", {- type: "keyword",- value: "red",- }),- createStyleDecl("fragment-local", "missing", "fontSize", {- type: "unit",- value: 16,- unit: "px",- }),- ];- const fragmentInstanceIds = new Set([- "fragment-instance",- "fragment-instance-with-token",- ]);- const newInstanceIds = new Map([- ["fragment-instance", "new-instance"],- ["fragment-instance-with-token", "new-instance-with-token"],- ]);- const styleSources: StyleSources = new Map([- [- "existing-token",- { type: "token", id: "existing-token", name: "Existing" },- ],- ]);- const styleSourceSelections: StyleSourceSelections = new Map();- const styles: Styles = new Map();- const breakpoints = toMap<Breakpoint>([{ id: "base", label: "Base" }]);-- insertLocalStyleSourcesWithNewIds({- fragmentStyleSources,- fragmentStyleSourceSelections,- fragmentStyles,- fragmentInstanceIds,- newInstanceIds,- styleSources,- styleSourceSelections,- styles,- breakpoints,- contentMode: true,- });-- const copiedLocalIds = Array.from(styleSources.keys()).filter(- (styleSourceId) => styleSourceId !== "existing-token"- );- expect(copiedLocalIds).toHaveLength(1);- const [copiedLocalId] = copiedLocalIds;- expect(styleSources.get(copiedLocalId)).toMatchObject({ type: "local" });- expect(styleSourceSelections.get("new-instance")).toEqual({- instanceId: "new-instance",- values: [copiedLocalId],- });- expect(styleSourceSelections.get("new-instance-with-token")).toEqual({- instanceId: "new-instance-with-token",- values: [copiedLocalId, "existing-token"],- });- expect(Array.from(styles.values())).toEqual([- {- ...fragmentStyles[0],- styleSourceId: copiedLocalId,- },- ]);- });-- test("skips selections with no copyable content-mode style sources", () => {- const fragmentStyleSources: StyleSource[] = [- { type: "local", id: "fragment-local" },- { type: "token", id: "missing-token", name: "Missing" },- ];- const fragmentStyleSourceSelections: StyleSourceSelection[] = [- { instanceId: "fragment-instance", values: ["fragment-local"] },- { instanceId: "fragment-instance-with-token", values: ["missing-token"] },- ];- const fragmentStyles: StyleDecl[] = [- createStyleDecl("fragment-local", "missing", "color", {- type: "keyword",- value: "red",- }),- ];- const styleSources: StyleSources = new Map();- const styleSourceSelections: StyleSourceSelections = new Map();- const styles: Styles = new Map();-- insertLocalStyleSourcesWithNewIds({- fragmentStyleSources,- fragmentStyleSourceSelections,- fragmentStyles,- fragmentInstanceIds: new Set([- "fragment-instance",- "fragment-instance-with-token",- ]),- newInstanceIds: new Map([- ["fragment-instance", "new-instance"],- ["fragment-instance-with-token", "new-instance-with-token"],- ]),- styleSources,- styleSourceSelections,- styles,- breakpoints: toMap<Breakpoint>([{ id: "base", label: "Base" }]),- contentMode: true,- });-- expect(styleSources).toEqual(new Map());- expect(styleSourceSelections).toEqual(new Map());- expect(styles).toEqual(new Map());- });-- test("does not reuse target local style source ids", () => {- const fragmentStyleSourceSelections: StyleSourceSelection[] = [- { instanceId: "fragment-instance", values: ["existing-local"] },- {- instanceId: "fragment-instance-with-token",- values: ["existing-token"],- },- ];- const styleSources: StyleSources = new Map([- ["existing-local", { type: "local", id: "existing-local" }],- [- "existing-token",- { type: "token", id: "existing-token", name: "Existing" },- ],- ]);- const styleSourceSelections: StyleSourceSelections = new Map();- const styles: Styles = new Map();-- insertLocalStyleSourcesWithNewIds({- fragmentStyleSources: [],- fragmentStyleSourceSelections,- fragmentStyles: [],- fragmentInstanceIds: new Set([- "fragment-instance",- "fragment-instance-with-token",- ]),- newInstanceIds: new Map([- ["fragment-instance", "new-instance"],- ["fragment-instance-with-token", "new-instance-with-token"],- ]),- styleSources,- styleSourceSelections,- styles,- breakpoints: toMap<Breakpoint>([{ id: "base", label: "Base" }]),- contentMode: true,- });-- expect(styleSourceSelections.get("new-instance")).toBeUndefined();- expect(styleSourceSelections.get("new-instance-with-token")).toEqual({- instanceId: "new-instance-with-token",- values: ["existing-token"],- });- });-- test("copies fragment local style sources even when ids already exist in target", () => {- const fragmentStyleSources: StyleSource[] = [- { type: "local", id: "local" },- ];- const fragmentStyleSourceSelections: StyleSourceSelection[] = [- { instanceId: "fragment-instance", values: ["local"] },- ];- const fragmentStyles: StyleDecl[] = [- createStyleDecl("local", "base", "color", {- type: "keyword",- value: "red",- }),- ];- const styleSources: StyleSources = new Map([- ["local", { type: "local", id: "local" }],- ]);- const styleSourceSelections: StyleSourceSelections = new Map();- const styles: Styles = new Map();-- insertLocalStyleSourcesWithNewIds({- fragmentStyleSources,- fragmentStyleSourceSelections,- fragmentStyles,- fragmentInstanceIds: new Set(["fragment-instance"]),- newInstanceIds: new Map([["fragment-instance", "new-instance"]]),- styleSources,- styleSourceSelections,- styles,- breakpoints: toMap<Breakpoint>([{ id: "base", label: "Base" }]),- contentMode: true,- });-- const copiedLocalId = styleSourceSelections.get("new-instance")?.values[0];-- expect(copiedLocalId).toBeDefined();- expect(copiedLocalId).not.toBe("local");- expect(styleSources.get("local")).toEqual({ type: "local", id: "local" });- expect(styleSources.get(copiedLocalId ?? "")).toMatchObject({- type: "local",- });- expect(Array.from(styles.values())).toEqual([- {- ...fragmentStyles[0],- styleSourceId: copiedLocalId,- },- ]);- });-});--describe("insertTokenStyleSources", () => {- test("inserts token sources and remaps their styles", () => {- const breakpoints = toMap<Breakpoint>([- { id: "base", label: "base" },- { id: "desktop", label: "Desktop", minWidth: 1280 },- ]);- const styleSources: StyleSources = new Map([- ["existing-token", { id: "existing-token", type: "token", name: "Old" }],- ]);- const styles: Styles = new Map();- const fragmentStyleSources: StyleSource[] = [- { id: "token", type: "token", name: "Primary" },- ];- const fragmentStyles: StyleDecl[] = [- createStyleDecl("token", "old-desktop", "color", {- type: "keyword",- value: "red",- }),- ];-- const styleSourceIdMap = insertTokenStyleSources({- fragmentStyleSources,- fragmentStyles,- styleSources,- styles,- breakpoints,- mergedBreakpointIds: new Map([["old-desktop", "desktop"]]),- });-- const newTokenId = styleSourceIdMap.get("token");- expect(newTokenId).toBeDefined();- expect(newTokenId).not.toBe("token");- expect(styleSources.get(newTokenId ?? "")).toMatchObject({- type: "token",- name: "Primary",- });- expect(Array.from(styles.values())).toEqual([- {- ...fragmentStyles[0],- breakpointId: "desktop",- styleSourceId: newTokenId,- },- ]);- });-});--describe("deleteStyleSourceMutable", () => {- test("deletes style source from styleSources map", () => {- const styleSources: StyleSources = new Map([- [- "token1",- { type: "token", id: "token1", name: "Primary Color" } as StyleSource,- ],- [- "token2",- { type: "token", id: "token2", name: "Secondary Color" } as StyleSource,- ],- ]);- const styleSourceSelections: StyleSourceSelections = new Map();- const styles: Styles = new Map();-- deleteStyleSourceMutable({- styleSourceId: "token1",- styleSources,- styleSourceSelections,- styles,- });-- expect(styleSources.has("token1")).toBe(false);- expect(styleSources.has("token2")).toBe(true);- });-- test("removes style source from style source selections", () => {- const styleSources: StyleSources = new Map([- [- "token1",- { type: "token", id: "token1", name: "Primary Color" } as StyleSource,- ],- ]);- const styleSourceSelections: StyleSourceSelections = new Map([- ["instance1", { instanceId: "instance1", values: ["token1", "local1"] }],- ["instance2", { instanceId: "instance2", values: ["token1"] }],- ["instance3", { instanceId: "instance3", values: ["local2"] }],- ]);- const styles: Styles = new Map();-- deleteStyleSourceMutable({- styleSourceId: "token1",- styleSources,- styleSourceSelections,- styles,- });-- const selection1 = styleSourceSelections.get("instance1");- expect(selection1?.values).toEqual(["local1"]);-- const selection2 = styleSourceSelections.get("instance2");- expect(selection2?.values).toEqual([]);-- const selection3 = styleSourceSelections.get("instance3");- expect(selection3?.values).toEqual(["local2"]);- });-- test("deletes all styles associated with the style source", () => {- const styleSources: StyleSources = new Map([- [- "token1",- { type: "token", id: "token1", name: "Primary Color" } as StyleSource,- ],- ]);- const styleSourceSelections: StyleSourceSelections = new Map();- const styles: Styles = new Map([- [- "token1:base:color",- {- breakpointId: "base",- styleSourceId: "token1",- property: "color",- value: { type: "keyword", value: "red" },- },- ],- [- "token1:base:fontSize",- {- breakpointId: "base",- styleSourceId: "token1",- property: "fontSize",- value: { type: "unit", value: 16, unit: "px" },- },- ],- [- "local1:base:display",- {- breakpointId: "base",- styleSourceId: "local1",- property: "display",- value: { type: "keyword", value: "flex" },- },- ],- ]);-- deleteStyleSourceMutable({- styleSourceId: "token1",- styleSources,- styleSourceSelections,- styles,- });-- expect(styles.has("token1:base:color")).toBe(false);- expect(styles.has("token1:base:fontSize")).toBe(false);- expect(styles.has("local1:base:display")).toBe(true);- expect(styles.size).toBe(1);- });-- test("handles deletion of non-existent style source gracefully", () => {- const styleSources: StyleSources = new Map();- const styleSourceSelections: StyleSourceSelections = new Map();- const styles: Styles = new Map();-- expect(() => {- deleteStyleSourceMutable({- styleSourceId: "non-existent",- styleSources,- styleSourceSelections,- styles,- });- }).not.toThrow();- });-});--describe("findUnusedTokens", () => {- test("identifies tokens with no usages", () => {- const styleSources: StyleSources = new Map([- [- "token1",- { type: "token", id: "token1", name: "Used Token" } as StyleSource,- ],- [- "token2",- { type: "token", id: "token2", name: "Unused Token" } as StyleSource,- ],- [- "token3",- { type: "token", id: "token3", name: "Another Unused" } as StyleSource,- ],- ["local1", { type: "local", id: "local1" } as StyleSource],- ]);- const styleSourceUsages = new Map<string, Set<string>>([- ["token1", new Set(["instance1", "instance2"])],- ["token2", new Set()],- ["local1", new Set(["instance3"])],- ]);-- const unusedTokens = findUnusedTokens({ styleSources, styleSourceUsages });-- expect(unusedTokens).toContain("token2");- expect(unusedTokens).toContain("token3");- expect(unusedTokens).not.toContain("token1");- expect(unusedTokens).not.toContain("local1");- expect(unusedTokens.length).toBe(2);- });-- test("returns empty array when all tokens are used", () => {- const styleSources: StyleSources = new Map([- [- "token1",- { type: "token", id: "token1", name: "Used Token 1" } as StyleSource,- ],- [- "token2",- { type: "token", id: "token2", name: "Used Token 2" } as StyleSource,- ],- ]);- const styleSourceUsages = new Map([- ["token1", new Set(["instance1"])],- ["token2", new Set(["instance2"])],- ]);-- const unusedTokens = findUnusedTokens({ styleSources, styleSourceUsages });-- expect(unusedTokens).toEqual([]);- });-- test("ignores local style sources", () => {- const styleSources: StyleSources = new Map([- ["local1", { type: "local", id: "local1" } as StyleSource],- ["local2", { type: "local", id: "local2" } as StyleSource],- ]);- const styleSourceUsages = new Map();-- const unusedTokens = findUnusedTokens({ styleSources, styleSourceUsages });-- expect(unusedTokens).toEqual([]);- });-- test("treats undefined usages as unused", () => {- const styleSources: StyleSources = new Map([- [- "token1",- { type: "token", id: "token1", name: "Unused Token" } as StyleSource,- ],- ]);- const styleSourceUsages = new Map();-- const unusedTokens = findUnusedTokens({ styleSources, styleSourceUsages });-- expect(unusedTokens).toEqual(["token1"]);- });-});--describe("deleteStyleSourcesMutable", () => {- test("deletes multiple style sources", () => {- const styleSources: StyleSources = new Map([- [- "token1",- { type: "token", id: "token1", name: "Token 1" } as StyleSource,- ],- [- "token2",- { type: "token", id: "token2", name: "Token 2" } as StyleSource,- ],- [- "token3",- { type: "token", id: "token3", name: "Token 3" } as StyleSource,- ],- ]);- const styleSourceSelections: StyleSourceSelections = new Map();- const styles: Styles = new Map();-- deleteStyleSourcesMutable({- styleSourceIds: ["token1", "token3"],- styleSources,- styleSourceSelections,- styles,- });-- expect(styleSources.has("token1")).toBe(false);- expect(styleSources.has("token2")).toBe(true);- expect(styleSources.has("token3")).toBe(false);- });-- test("removes deleted style sources from all selections", () => {- const styleSources: StyleSources = new Map([- [- "token1",- { type: "token", id: "token1", name: "Token 1" } as StyleSource,- ],- [- "token2",- { type: "token", id: "token2", name: "Token 2" } as StyleSource,- ],- ]);- const styleSourceSelections: StyleSourceSelections = new Map([- [- "instance1",- { instanceId: "instance1", values: ["token1", "token2", "local1"] },- ],- ["instance2", { instanceId: "instance2", values: ["token1"] }],- ]);- const styles: Styles = new Map();-- deleteStyleSourcesMutable({- styleSourceIds: ["token1", "token2"],- styleSources,- styleSourceSelections,- styles,- });-- const selection1 = styleSourceSelections.get("instance1");- expect(selection1?.values).toEqual(["local1"]);-- const selection2 = styleSourceSelections.get("instance2");- expect(selection2?.values).toEqual([]);- });-- test("deletes all associated styles", () => {- const styleSources: StyleSources = new Map([- [- "token1",- { type: "token", id: "token1", name: "Token 1" } as StyleSource,- ],- [- "token2",- { type: "token", id: "token2", name: "Token 2" } as StyleSource,- ],- ]);- const styleSourceSelections: StyleSourceSelections = new Map();- const styles: Styles = new Map([- [- "token1:base:color",- {- breakpointId: "base",- styleSourceId: "token1",- property: "color",- value: { type: "keyword", value: "red" },- },- ],- [- "token2:base:fontSize",- {- breakpointId: "base",- styleSourceId: "token2",- property: "fontSize",- value: { type: "unit", value: 16, unit: "px" },- },- ],- [- "local1:base:display",- {- breakpointId: "base",- styleSourceId: "local1",- property: "display",- value: { type: "keyword", value: "flex" },- },- ],- ]);-- deleteStyleSourcesMutable({- styleSourceIds: ["token1", "token2"],- styleSources,- styleSourceSelections,- styles,- });-- expect(styles.has("token1:base:color")).toBe(false);- expect(styles.has("token2:base:fontSize")).toBe(false);- expect(styles.has("local1:base:display")).toBe(true);- expect(styles.size).toBe(1);- });-- test("handles empty array of style source IDs", () => {- const styleSources: StyleSources = new Map([- [- "token1",- { type: "token", id: "token1", name: "Token 1" } as StyleSource,- ],- ]);- const styleSourceSelections: StyleSourceSelections = new Map();- const styles: Styles = new Map();-- deleteStyleSourcesMutable({- styleSourceIds: [],- styleSources,- styleSourceSelections,- styles,- });-- expect(styleSources.has("token1")).toBe(true);- });-});--describe("validateAndRenameStyleSource", () => {- test("returns undefined for valid rename", () => {- const styleSources: StyleSources = new Map([- [- "token1",- { type: "token", id: "token1", name: "Old Name" } as StyleSource,- ],- [- "token2",- { type: "token", id: "token2", name: "Other Token" } as StyleSource,- ],- ]);-- const error = validateAndRenameStyleSource({- id: "token1",- name: "New Name",- styleSources,- });-- expect(error).toBeUndefined();- });-- test("returns minlength error for empty name", () => {- const styleSources: StyleSources = new Map([- [- "token1",- { type: "token", id: "token1", name: "Old Name" } as StyleSource,- ],- ]);-- const error = validateAndRenameStyleSource({- id: "token1",- name: "",- styleSources,- });-- expect(error).toEqual({ type: "minlength", id: "token1" });- });-- test("returns minlength error for whitespace-only name", () => {- const styleSources: StyleSources = new Map([- [- "token1",- { type: "token", id: "token1", name: "Old Name" } as StyleSource,- ],- ]);-- const error = validateAndRenameStyleSource({- id: "token1",- name: " ",- styleSources,- });-- expect(error).toEqual({ type: "minlength", id: "token1" });- });-- test("returns duplicate error when name already exists", () => {- const styleSources: StyleSources = new Map([- [- "token1",- { type: "token", id: "token1", name: "Primary Color" } as StyleSource,- ],- [- "token2",- {- type: "token",- id: "token2",- name: "Secondary Color",- } as StyleSource,- ],- ]);-- const error = validateAndRenameStyleSource({- id: "token1",- name: "Secondary Color",- styleSources,- });-- expect(error).toEqual({ type: "duplicate", id: "token1" });- });-- test("allows renaming to same name (no change)", () => {- const styleSources: StyleSources = new Map([- [- "token1",- { type: "token", id: "token1", name: "Primary Color" } as StyleSource,- ],- ]);-- const error = validateAndRenameStyleSource({- id: "token1",- name: "Primary Color",- styleSources,- });-- expect(error).toBeUndefined();- });-- test("ignores local style sources when checking duplicates", () => {- const styleSources: StyleSources = new Map([- [- "token1",- { type: "token", id: "token1", name: "Primary Color" } as StyleSource,- ],- ["local1", { type: "local", id: "local1" } as StyleSource],- ]);-- const error = validateAndRenameStyleSource({- id: "token1",- name: "Some Name",- styleSources,- });-- expect(error).toBeUndefined();- });-});--describe("renameStyleSourceMutable", () => {- test("renames a token style source", () => {- const styleSources: StyleSources = new Map([- [- "token1",- { type: "token", id: "token1", name: "Old Name" } as StyleSource,- ],- ]);-- renameStyleSourceMutable({- id: "token1",- name: "New Name",- styleSources,- });-- const styleSource = styleSources.get("token1");- expect(styleSource?.type).toBe("token");- if (styleSource?.type === "token") {- expect(styleSource.name).toBe("New Name");- }- });-- test("does not rename local style source", () => {- const styleSources: StyleSources = new Map([- ["local1", { type: "local", id: "local1" } as StyleSource],- ]);-- renameStyleSourceMutable({- id: "local1",- name: "New Name",- styleSources,- });-- const styleSource = styleSources.get("local1");- expect(styleSource?.type).toBe("local");- });-- test("handles non-existent style source gracefully", () => {- const styleSources: StyleSources = new Map();-- expect(() => {- renameStyleSourceMutable({- id: "non-existent",- name: "New Name",- styleSources,- });- }).not.toThrow();- });-- test("preserves other properties of the style source", () => {- const styleSources: StyleSources = new Map([- [- "token1",- { type: "token", id: "token1", name: "Old Name" } as StyleSource,- ],- ]);-- renameStyleSourceMutable({- id: "token1",- name: "New Name",- styleSources,- });-- const styleSource = styleSources.get("token1");- expect(styleSource?.id).toBe("token1");- expect(styleSource?.type).toBe("token");- });-});--describe("toggleStyleSourceLockMutable", () => {- test("locks a token style source", () => {- const styleSources: StyleSources = new Map([- ["token1", { type: "token", id: "token1", name: "Token" } as StyleSource],- ]);-- toggleStyleSourceLockMutable({- id: "token1",- locked: true,- styleSources,- });-- expect(styleSources.get("token1")).toEqual({- type: "token",- id: "token1",- name: "Token",- locked: true,- });- });-- test("unlocks a token style source by removing the locked field", () => {- const styleSources: StyleSources = new Map([- [- "token1",- {- type: "token",- id: "token1",- name: "Token",- locked: true,- } as StyleSource,- ],- ]);-- toggleStyleSourceLockMutable({- id: "token1",- locked: false,- styleSources,- });-- expect(styleSources.get("token1")).toEqual({- type: "token",- id: "token1",- name: "Token",- });- });-- test("does not lock local style sources", () => {- const styleSources: StyleSources = new Map([- ["local1", { type: "local", id: "local1" } as StyleSource],- ]);-- toggleStyleSourceLockMutable({- id: "local1",- locked: true,- styleSources,- });-- expect(styleSources.get("local1")).toEqual({- type: "local",- id: "local1",- });- });-});--describe("isStyleSourceLocked", () => {- test("returns true only for locked tokens", () => {- expect(- isStyleSourceLocked({- type: "token",- id: "token1",- name: "Token",- locked: true,- })- ).toBe(true);- expect(- isStyleSourceLocked({- type: "token",- id: "token1",- name: "Token",- })- ).toBe(false);- expect(isStyleSourceLocked({ type: "local", id: "local1" })).toBe(false);- expect(isStyleSourceLocked(undefined)).toBe(false);- });-});--describe("deleteLocalStyleSourcesMutable", () => {- test("deletes local style sources from styleSources map", () => {- const localStyleSourceIds = new Set(["local1", "local2"]);- const styleSources: StyleSources = new Map([- ["local1", { type: "local", id: "local1" } as StyleSource],- ["local2", { type: "local", id: "local2" } as StyleSource],- ["local3", { type: "local", id: "local3" } as StyleSource],- ["token1", { type: "token", id: "token1", name: "Token" } as StyleSource],- ]);- const styles: Styles = new Map();-- deleteLocalStyleSourcesMutable({- localStyleSourceIds,- styleSources,- styles,- });-- expect(styleSources.has("local1")).toBe(false);- expect(styleSources.has("local2")).toBe(false);- expect(styleSources.has("local3")).toBe(true);- expect(styleSources.has("token1")).toBe(true);- });-- test("deletes styles associated with local style sources", () => {- const localStyleSourceIds = new Set(["local1", "local2"]);- const styleSources: StyleSources = new Map([- ["local1", { type: "local", id: "local1" } as StyleSource],- ["local2", { type: "local", id: "local2" } as StyleSource],- ]);- const styles: Styles = new Map([- [- "local1:base:color",- {- breakpointId: "base",- styleSourceId: "local1",- property: "color",- value: { type: "keyword", value: "red" },- },- ],- [- "local2:base:fontSize",- {- breakpointId: "base",- styleSourceId: "local2",- property: "fontSize",- value: { type: "unit", value: 16, unit: "px" },- },- ],- [- "local3:base:display",- {- breakpointId: "base",- styleSourceId: "local3",- property: "display",- value: { type: "keyword", value: "flex" },- },- ],- ]);-- deleteLocalStyleSourcesMutable({- localStyleSourceIds,- styleSources,- styles,- });-- expect(styles.has("local1:base:color")).toBe(false);- expect(styles.has("local2:base:fontSize")).toBe(false);- expect(styles.has("local3:base:display")).toBe(true);- expect(styles.size).toBe(1);- });-- test("handles empty set of local style source IDs", () => {- const localStyleSourceIds = new Set<string>();- const styleSources: StyleSources = new Map([- ["local1", { type: "local", id: "local1" } as StyleSource],- ]);- const styles: Styles = new Map();-- deleteLocalStyleSourcesMutable({- localStyleSourceIds,- styleSources,- styles,- });-- expect(styleSources.has("local1")).toBe(true);- });-});--describe("collectStyleSourcesFromInstances", () => {- test("collects style sources and selections from instances", () => {- const instanceIds = new Set(["instance1", "instance2"]);- const styleSourceSelections: StyleSourceSelections = new Map([- ["instance1", { instanceId: "instance1", values: ["local1", "token1"] }],- ["instance2", { instanceId: "instance2", values: ["local2"] }],- ["instance3", { instanceId: "instance3", values: ["local3"] }],- ]);- const styleSources: StyleSources = new Map([- ["local1", { type: "local", id: "local1" } as StyleSource],- ["local2", { type: "local", id: "local2" } as StyleSource],- ["local3", { type: "local", id: "local3" } as StyleSource],- [- "token1",- { type: "token", id: "token1", name: "Token 1" } as StyleSource,- ],- ]);- const styles: Styles = new Map([- [- "local1:base:color",- {- breakpointId: "base",- styleSourceId: "local1",- property: "color",- value: { type: "keyword", value: "red" },- },- ],- [- "local2:base:fontSize",- {- breakpointId: "base",- styleSourceId: "local2",- property: "fontSize",- value: { type: "unit", value: 16, unit: "px" },- },- ],- [- "local3:base:display",- {- breakpointId: "base",- styleSourceId: "local3",- property: "display",- value: { type: "keyword", value: "flex" },- },- ],- [- "token1:base:backgroundColor",- {- breakpointId: "base",- styleSourceId: "token1",- property: "backgroundColor",- value: { type: "keyword", value: "blue" },- },- ],- ]);-- const result = collectStyleSourcesFromInstances({- instanceIds,- styleSourceSelections,- styleSources,- styles,- });-- expect(result.styleSourceSelectionsArray).toHaveLength(2);- expect(result.styleSourceSelectionsArray[0].instanceId).toBe("instance1");- expect(result.styleSourceSelectionsArray[1].instanceId).toBe("instance2");-- expect(result.styleSourcesMap.size).toBe(3);- expect(result.styleSourcesMap.has("local1")).toBe(true);- expect(result.styleSourcesMap.has("local2")).toBe(true);- expect(result.styleSourcesMap.has("token1")).toBe(true);- expect(result.styleSourcesMap.has("local3")).toBe(false);-- expect(result.stylesArray).toHaveLength(3);- expect(- result.stylesArray.find((s) => s.styleSourceId === "local1")- ).toBeDefined();- expect(- result.stylesArray.find((s) => s.styleSourceId === "local2")- ).toBeDefined();- expect(- result.stylesArray.find((s) => s.styleSourceId === "token1")- ).toBeDefined();- expect(- result.stylesArray.find((s) => s.styleSourceId === "local3")- ).toBeUndefined();- });-- test("returns empty arrays when instances have no style sources", () => {- const instanceIds = new Set(["instance1", "instance2"]);- const styleSourceSelections: StyleSourceSelections = new Map();- const styleSources: StyleSources = new Map();- const styles: Styles = new Map();-- const result = collectStyleSourcesFromInstances({- instanceIds,- styleSourceSelections,- styleSources,- styles,- });-- expect(result.styleSourceSelectionsArray).toHaveLength(0);- expect(result.styleSourcesMap.size).toBe(0);- expect(result.stylesArray).toHaveLength(0);- });-- test("handles missing style sources gracefully", () => {- const instanceIds = new Set(["instance1"]);- const styleSourceSelections: StyleSourceSelections = new Map([- [- "instance1",- { instanceId: "instance1", values: ["local1", "missing-source"] },- ],- ]);- const styleSources: StyleSources = new Map([- ["local1", { type: "local", id: "local1" } as StyleSource],- ]);- const styles: Styles = new Map([- [- "local1:base:color",- {- breakpointId: "base",- styleSourceId: "local1",- property: "color",- value: { type: "keyword", value: "red" },- },- ],- ]);-- const result = collectStyleSourcesFromInstances({- instanceIds,- styleSourceSelections,- styleSources,- styles,- });-- expect(result.styleSourceSelectionsArray).toHaveLength(1);- expect(result.styleSourcesMap.size).toBe(1);- expect(result.styleSourcesMap.has("local1")).toBe(true);- expect(result.styleSourcesMap.has("missing-source")).toBe(false);- });-- test("deduplicates style sources from multiple instances", () => {- const instanceIds = new Set(["instance1", "instance2"]);- const styleSourceSelections: StyleSourceSelections = new Map([- ["instance1", { instanceId: "instance1", values: ["token1"] }],- ["instance2", { instanceId: "instance2", values: ["token1"] }],- ]);- const styleSources: StyleSources = new Map([- [- "token1",- { type: "token", id: "token1", name: "Shared Token" } as StyleSource,- ],- ]);- const styles: Styles = new Map([- [- "token1:base:color",- {- breakpointId: "base",- styleSourceId: "token1",- property: "color",- value: { type: "keyword", value: "red" },- },- ],- ]);-- const result = collectStyleSourcesFromInstances({- instanceIds,- styleSourceSelections,- styleSources,- styles,- });-- expect(result.styleSourceSelectionsArray).toHaveLength(2);- expect(result.styleSourcesMap.size).toBe(1);- expect(result.stylesArray).toHaveLength(1);- });-});--describe("findDuplicateTokens", () => {- test("finds tokens with identical styles", () => {- const breakpoints = toMap<Breakpoint>([{ id: "base", label: "base" }]);- const styleSources: StyleSources = new Map([- [- "token1",- { type: "token", id: "token1", name: "Primary Red" } as StyleSource,- ],- [- "token2",- { type: "token", id: "token2", name: "Accent Red" } as StyleSource,- ],- ["token3", { type: "token", id: "token3", name: "Blue" } as StyleSource],- ["local1", { type: "local", id: "local1" } as StyleSource],- ]);- const styles: Styles = new Map([- [- "token1:base:color",- createStyleDecl("token1", "base", "color", {- type: "keyword",- value: "red",- }),- ],- [- "token2:base:color",- createStyleDecl("token2", "base", "color", {- type: "keyword",- value: "red",- }),- ],- [- "token3:base:color",- createStyleDecl("token3", "base", "color", {- type: "keyword",- value: "blue",- }),- ],- ]);-- const duplicates = findDuplicateTokens({- styleSources,- styles,- breakpoints,- });-- expect(duplicates.size).toBe(2);- expect(duplicates.get("token1")).toEqual(["token2"]);- expect(duplicates.get("token2")).toEqual(["token1"]);- expect(duplicates.has("token3")).toBe(false);- expect(duplicates.has("local1")).toBe(false);- });-- test("finds tokens with same name", () => {- const breakpoints = toMap<Breakpoint>([{ id: "base", label: "base" }]);- const styleSources: StyleSources = new Map([- [- "token1",- { type: "token", id: "token1", name: "Primary" } as StyleSource,- ],- [- "token2",- { type: "token", id: "token2", name: "Primary" } as StyleSource,- ],- [- "token3",- { type: "token", id: "token3", name: "Secondary" } as StyleSource,- ],- ]);- const styles: Styles = new Map([- [- "token1:base:color",- createStyleDecl("token1", "base", "color", {- type: "keyword",- value: "red",- }),- ],- [- "token2:base:color",- createStyleDecl("token2", "base", "color", {- type: "keyword",- value: "blue",- }),- ],- [- "token3:base:color",- createStyleDecl("token3", "base", "color", {- type: "keyword",- value: "green",- }),- ],- ]);-- const duplicates = findDuplicateTokens({- styleSources,- styles,- breakpoints,- });-- expect(duplicates.size).toBe(2);- expect(duplicates.get("token1")).toEqual(["token2"]);- expect(duplicates.get("token2")).toEqual(["token1"]);- expect(duplicates.has("token3")).toBe(false);- });-- test("finds tokens with same name AND same styles without duplicating", () => {- const breakpoints = toMap<Breakpoint>([{ id: "base", label: "base" }]);- const styleSources: StyleSources = new Map([- [- "token1",- { type: "token", id: "token1", name: "Primary" } as StyleSource,- ],- [- "token2",- { type: "token", id: "token2", name: "Primary" } as StyleSource,- ],- ]);- const styles: Styles = new Map([- [- "token1:base:color",- createStyleDecl("token1", "base", "color", {- type: "keyword",- value: "red",- }),- ],- [- "token2:base:color",- createStyleDecl("token2", "base", "color", {- type: "keyword",- value: "red",- }),- ],- ]);-- const duplicates = findDuplicateTokens({- styleSources,- styles,- breakpoints,- });-- expect(duplicates.size).toBe(2);- // Should list each token only once, not twice (once for name, once for styles)- expect(duplicates.get("token1")).toEqual(["token2"]);- expect(duplicates.get("token2")).toEqual(["token1"]);- });-- test("finds mixed duplicates: some by style, some by name", () => {- const breakpoints = toMap<Breakpoint>([{ id: "base", label: "base" }]);- const styleSources: StyleSources = new Map([- ["token1", { type: "token", id: "token1", name: "Red A" } as StyleSource],- ["token2", { type: "token", id: "token2", name: "Red B" } as StyleSource],- [- "token3",- { type: "token", id: "token3", name: "Duplicate Name" } as StyleSource,- ],- [- "token4",- { type: "token", id: "token4", name: "Duplicate Name" } as StyleSource,- ],- ]);- const styles: Styles = new Map([- [- "token1:base:color",- createStyleDecl("token1", "base", "color", {- type: "keyword",- value: "red",- }),- ],- [- "token2:base:color",- createStyleDecl("token2", "base", "color", {- type: "keyword",- value: "red",- }),- ],- [- "token3:base:color",- createStyleDecl("token3", "base", "color", {- type: "keyword",- value: "blue",- }),- ],- [- "token4:base:color",- createStyleDecl("token4", "base", "color", {- type: "keyword",- value: "green",- }),- ],- ]);-- const duplicates = findDuplicateTokens({- styleSources,- styles,- breakpoints,- });-- expect(duplicates.size).toBe(4);- expect(duplicates.get("token1")).toEqual(["token2"]);- expect(duplicates.get("token2")).toEqual(["token1"]);- expect(duplicates.get("token3")).toEqual(["token4"]);- expect(duplicates.get("token4")).toEqual(["token3"]);- });-- test("finds multiple groups of duplicates", () => {- const breakpoints = toMap<Breakpoint>([{ id: "base", label: "base" }]);- const styleSources: StyleSources = new Map([- ["token1", { type: "token", id: "token1", name: "Red 1" } as StyleSource],- ["token2", { type: "token", id: "token2", name: "Red 2" } as StyleSource],- [- "token3",- { type: "token", id: "token3", name: "Blue 1" } as StyleSource,- ],- [- "token4",- { type: "token", id: "token4", name: "Blue 2" } as StyleSource,- ],- [- "token5",- { type: "token", id: "token5", name: "Blue 3" } as StyleSource,- ],- ]);- const styles: Styles = new Map([- [- "token1:base:color",- createStyleDecl("token1", "base", "color", {- type: "keyword",- value: "red",- }),- ],- [- "token2:base:color",- createStyleDecl("token2", "base", "color", {- type: "keyword",- value: "red",- }),- ],- [- "token3:base:color",- createStyleDecl("token3", "base", "color", {- type: "keyword",- value: "blue",- }),- ],- [- "token4:base:color",- createStyleDecl("token4", "base", "color", {- type: "keyword",- value: "blue",- }),- ],- [- "token5:base:color",- createStyleDecl("token5", "base", "color", {- type: "keyword",- value: "blue",- }),- ],- ]);-- const duplicates = findDuplicateTokens({- styleSources,- styles,- breakpoints,- });-- expect(duplicates.size).toBe(5);- expect(duplicates.get("token1")).toEqual(["token2"]);- expect(duplicates.get("token2")).toEqual(["token1"]);- expect(duplicates.get("token3")).toEqual(["token4", "token5"]);- expect(duplicates.get("token4")).toEqual(["token3", "token5"]);- expect(duplicates.get("token5")).toEqual(["token3", "token4"]);- });-- test("returns empty map when no duplicates exist", () => {- const breakpoints = toMap<Breakpoint>([{ id: "base", label: "base" }]);- const styleSources: StyleSources = new Map([- ["token1", { type: "token", id: "token1", name: "Red" } as StyleSource],- ["token2", { type: "token", id: "token2", name: "Blue" } as StyleSource],- ]);- const styles: Styles = new Map([- [- "token1:base:color",- createStyleDecl("token1", "base", "color", {- type: "keyword",- value: "red",- }),- ],- [- "token2:base:color",- createStyleDecl("token2", "base", "color", {- type: "keyword",- value: "blue",- }),- ],- ]);-- const duplicates = findDuplicateTokens({- styleSources,- styles,- breakpoints,- });-- expect(duplicates.size).toBe(0);- });-- test("compares tokens across breakpoints and states", () => {- const breakpoints = toMap<Breakpoint>([- { id: "base", label: "base" },- { id: "tablet", label: "tablet", minWidth: 768 },- ]);- const styleSources: StyleSources = new Map([- [- "token1",- { type: "token", id: "token1", name: "Token 1" } as StyleSource,- ],- [- "token2",- { type: "token", id: "token2", name: "Token 2" } as StyleSource,- ],- ]);- const styles: Styles = new Map([- [- "token1:base:color",- createStyleDecl("token1", "base", "color", {- type: "keyword",- value: "red",- }),- ],- [- "token1:tablet:color",- {- ...createStyleDecl("token1", "tablet", "color", {- type: "keyword",- value: "blue",- }),- state: ":hover",- },- ],- [- "token2:base:color",- createStyleDecl("token2", "base", "color", {- type: "keyword",- value: "red",- }),- ],- [- "token2:tablet:color",- {- ...createStyleDecl("token2", "tablet", "color", {- type: "keyword",- value: "blue",- }),- state: ":hover",- },- ],- ]);-- const duplicates = findDuplicateTokens({- styleSources,- styles,- breakpoints,- });-- expect(duplicates.size).toBe(2);- expect(duplicates.get("token1")).toEqual(["token2"]);- expect(duplicates.get("token2")).toEqual(["token1"]);- });-- test("ignores local style sources", () => {- const breakpoints = toMap<Breakpoint>([{ id: "base", label: "base" }]);- const styleSources: StyleSources = new Map([- ["local1", { type: "local", id: "local1" } as StyleSource],- ["local2", { type: "local", id: "local2" } as StyleSource],- ]);- const styles: Styles = new Map([- [- "local1:base:color",- createStyleDecl("local1", "base", "color", {- type: "keyword",- value: "red",- }),- ],- [- "local2:base:color",- createStyleDecl("local2", "base", "color", {- type: "keyword",- value: "red",- }),- ],- ]);-- const duplicates = findDuplicateTokens({- styleSources,- styles,- breakpoints,- });-- expect(duplicates.size).toBe(0);- });-- test("handles tokens with no styles", () => {- const breakpoints = toMap<Breakpoint>([{ id: "base", label: "base" }]);- const styleSources: StyleSources = new Map([- [- "token1",- { type: "token", id: "token1", name: "Empty 1" } as StyleSource,- ],- [- "token2",- { type: "token", id: "token2", name: "Empty 2" } as StyleSource,- ],- [- "token3",- { type: "token", id: "token3", name: "With Styles" } as StyleSource,- ],- ]);- const styles: Styles = new Map([- [- "token3:base:color",- createStyleDecl("token3", "base", "color", {- type: "keyword",- value: "red",- }),- ],- ]);-- const duplicates = findDuplicateTokens({- styleSources,- styles,- breakpoints,- });-- // Empty tokens should be considered duplicates of each other- expect(duplicates.size).toBe(2);- expect(duplicates.get("token1")).toEqual(["token2"]);- expect(duplicates.get("token2")).toEqual(["token1"]);- expect(duplicates.has("token3")).toBe(false);- });-});--describe("findTokenWithMatchingStyles", () => {- const breakpoints = new Map<Breakpoint["id"], Breakpoint>([- ["base", { id: "base", label: "Base" }],- ]);-- test("returns no conflict when token name doesn't exist", () => {- const existingTokens: StyleSource[] = [- { type: "token", id: "existing1", name: "PrimaryColor" },- ];-- const result = findTokenWithMatchingStyles({- tokenName: "SecondaryColor",- tokenStyles: [],- existingTokens,- existingStyles: [],- breakpoints,- mergedBreakpointIds: new Map(),- });-- expect(result.hasConflict).toBe(false);- expect(result.matchingToken).toBeUndefined();- });-- test("returns matching token when name and styles match", () => {- const existingToken: Extract<StyleSource, { type: "token" }> = {- type: "token",- id: "existing1",- name: "PrimaryColor",- };-- const existingStyles: StyleDecl[] = [- {- breakpointId: "base",- styleSourceId: "existing1",- property: "color",- value: { type: "keyword", value: "red" },- },- ];-- const tokenStyles: StyleDecl[] = [- {- breakpointId: "base",- styleSourceId: "fragment1",- property: "color",- value: { type: "keyword", value: "red" },- },- ];-- const result = findTokenWithMatchingStyles({- tokenName: "PrimaryColor",- tokenStyles,- existingTokens: [existingToken],- existingStyles,- breakpoints,- mergedBreakpointIds: new Map(),- });-- expect(result.hasConflict).toBe(false);- expect(result.matchingToken).toBeDefined();- expect(result.matchingToken?.id).toBe("existing1");- });-- test("returns conflict when name matches but styles differ", () => {- const existingToken: Extract<StyleSource, { type: "token" }> = {- type: "token",- id: "existing1",- name: "PrimaryColor",- };-- const existingStyles: StyleDecl[] = [- {- breakpointId: "base",- styleSourceId: "existing1",- property: "color",- value: { type: "keyword", value: "red" },- },- ];-- const tokenStyles: StyleDecl[] = [- {- breakpointId: "base",- styleSourceId: "fragment1",- property: "color",- value: { type: "keyword", value: "blue" }, // Different color- },- ];-- const result = findTokenWithMatchingStyles({- tokenName: "PrimaryColor",- tokenStyles,- existingTokens: [existingToken],- existingStyles,- breakpoints,- mergedBreakpointIds: new Map(),- });-- expect(result.hasConflict).toBe(true);- expect(result.matchingToken).toBeUndefined();- });-- test("matches token with multiple style properties", () => {- const existingToken: Extract<StyleSource, { type: "token" }> = {- type: "token",- id: "existing1",- name: "ButtonStyle",- };-- const existingStyles: StyleDecl[] = [- {- breakpointId: "base",- styleSourceId: "existing1",- property: "color",- value: { type: "keyword", value: "white" },- },- {- breakpointId: "base",- styleSourceId: "existing1",- property: "backgroundColor",- value: { type: "keyword", value: "blue" },- },- {- breakpointId: "base",- styleSourceId: "existing1",- property: "paddingTop",- value: { type: "unit", value: 10, unit: "px" },- },- ];-- const tokenStyles: StyleDecl[] = [- {- breakpointId: "base",- styleSourceId: "fragment1",- property: "paddingTop",- value: { type: "unit", value: 10, unit: "px" },- },- {- breakpointId: "base",- styleSourceId: "fragment1",- property: "backgroundColor",- value: { type: "keyword", value: "blue" },- },- {- breakpointId: "base",- styleSourceId: "fragment1",- property: "color",- value: { type: "keyword", value: "white" },- },- ];-- const result = findTokenWithMatchingStyles({- tokenName: "ButtonStyle",- tokenStyles,- existingTokens: [existingToken],- existingStyles,- breakpoints,- mergedBreakpointIds: new Map(),- });-- expect(result.hasConflict).toBe(false);- expect(result.matchingToken?.id).toBe("existing1");- });-- test("detects conflict when one style property differs", () => {- const existingToken: Extract<StyleSource, { type: "token" }> = {- type: "token",- id: "existing1",- name: "ButtonStyle",- };-- const existingStyles: StyleDecl[] = [- {- breakpointId: "base",- styleSourceId: "existing1",- property: "color",- value: { type: "keyword", value: "white" },- },- {- breakpointId: "base",- styleSourceId: "existing1",- property: "backgroundColor",- value: { type: "keyword", value: "blue" },- },- ];-- const tokenStyles: StyleDecl[] = [- {- breakpointId: "base",- styleSourceId: "fragment1",- property: "color",- value: { type: "keyword", value: "white" },- },- {- breakpointId: "base",- styleSourceId: "fragment1",- property: "backgroundColor",- value: { type: "keyword", value: "red" }, // Different!- },- ];-- const result = findTokenWithMatchingStyles({- tokenName: "ButtonStyle",- tokenStyles,- existingTokens: [existingToken],- existingStyles,- breakpoints,- mergedBreakpointIds: new Map(),- });-- expect(result.hasConflict).toBe(true);- expect(result.matchingToken).toBeUndefined();- });-- test("handles empty token styles", () => {- const existingToken: Extract<StyleSource, { type: "token" }> = {- type: "token",- id: "existing1",- name: "EmptyToken",- };-- const result = findTokenWithMatchingStyles({- tokenName: "EmptyToken",- tokenStyles: [],- existingTokens: [existingToken],- existingStyles: [],- breakpoints,- mergedBreakpointIds: new Map(),- });-- expect(result.hasConflict).toBe(false);- expect(result.matchingToken?.id).toBe("existing1");- });-});--describe("detectTokenConflicts", () => {- const breakpoints = new Map<Breakpoint["id"], Breakpoint>([- ["base", { id: "base", label: "Base" }],- ]);-- test("returns empty array when no conflicts exist", () => {- const fragmentStyleSources: StyleSource[] = [- { type: "token", id: "frag1", name: "NewToken" },- ];-- const fragmentStyles: StyleDecl[] = [- {- breakpointId: "base",- styleSourceId: "frag1",- property: "color",- value: { type: "keyword", value: "red" },- },- ];-- const existingStyleSources = new Map<string, StyleSource>([- ["exist1", { type: "token", id: "exist1", name: "ExistingToken" }],- ]);-- const existingStyles = new Map<string, StyleDecl>([- [- "exist1:base:color",- {- breakpointId: "base",- styleSourceId: "exist1",- property: "color",- value: { type: "keyword", value: "blue" },- },- ],- ]);-- const conflicts = detectTokenConflicts({- fragmentStyleSources,- fragmentStyles,- existingStyleSources,- existingStyles,- breakpoints,- mergedBreakpointIds: new Map(),- });-- expect(conflicts).toHaveLength(0);- });-- test("detects conflict when token name exists with different styles", () => {- const fragmentStyleSources: StyleSource[] = [- { type: "token", id: "frag1", name: "PrimaryColor" },- ];-- const fragmentStyles: StyleDecl[] = [- {- breakpointId: "base",- styleSourceId: "frag1",- property: "color",- value: { type: "keyword", value: "red" },- },- ];-- const existingStyleSources = new Map<string, StyleSource>([- ["exist1", { type: "token", id: "exist1", name: "PrimaryColor" }],- ]);-- const existingStyles = new Map<string, StyleDecl>([- [- "exist1:base:color",- {- breakpointId: "base",- styleSourceId: "exist1",- property: "color",- value: { type: "keyword", value: "blue" }, // Different color- },- ],- ]);-- const conflicts = detectTokenConflicts({- fragmentStyleSources,- fragmentStyles,- existingStyleSources,- existingStyles,- breakpoints,- mergedBreakpointIds: new Map(),- });-- expect(conflicts).toHaveLength(1);- expect(conflicts[0].tokenName).toBe("PrimaryColor");- expect(conflicts[0].fragmentTokenId).toBe("frag1");- expect(conflicts[0].existingToken.id).toBe("exist1");- });-- test("detects multiple conflicts", () => {- const fragmentStyleSources: StyleSource[] = [- { type: "token", id: "frag1", name: "PrimaryColor" },- { type: "token", id: "frag2", name: "SecondaryColor" },- ];-- const fragmentStyles: StyleDecl[] = [- {- breakpointId: "base",- styleSourceId: "frag1",- property: "color",- value: { type: "keyword", value: "red" },- },- {- breakpointId: "base",- styleSourceId: "frag2",- property: "color",- value: { type: "keyword", value: "green" },- },- ];-- const existingStyleSources = new Map<string, StyleSource>([- ["exist1", { type: "token", id: "exist1", name: "PrimaryColor" }],- ["exist2", { type: "token", id: "exist2", name: "SecondaryColor" }],- ]);-- const existingStyles = new Map<string, StyleDecl>([- [- "exist1:base:color",- {- breakpointId: "base",- styleSourceId: "exist1",- property: "color",- value: { type: "keyword", value: "blue" },- },- ],- [- "exist2:base:color",- {- breakpointId: "base",- styleSourceId: "exist2",- property: "color",- value: { type: "keyword", value: "yellow" },- },- ],- ]);-- const conflicts = detectTokenConflicts({- fragmentStyleSources,- fragmentStyles,- existingStyleSources,- existingStyles,- breakpoints,- mergedBreakpointIds: new Map(),- });-- expect(conflicts).toHaveLength(2);- expect(conflicts[0].tokenName).toBe("PrimaryColor");- expect(conflicts[1].tokenName).toBe("SecondaryColor");- });-- test("ignores local style sources", () => {- const fragmentStyleSources: StyleSource[] = [- { type: "local", id: "frag1" },- { type: "token", id: "frag2", name: "SomeToken" },- ];-- const fragmentStyles: StyleDecl[] = [- {- breakpointId: "base",- styleSourceId: "frag1",- property: "color",- value: { type: "keyword", value: "red" },- },- {- breakpointId: "base",- styleSourceId: "frag2",- property: "color",- value: { type: "keyword", value: "blue" },- },- ];-- const existingStyleSources = new Map<string, StyleSource>();- const existingStyles = new Map<string, StyleDecl>();-- const conflicts = detectTokenConflicts({- fragmentStyleSources,- fragmentStyles,- existingStyleSources,- existingStyles,- breakpoints,- mergedBreakpointIds: new Map(),- });-- expect(conflicts).toHaveLength(0);- });-- test("no conflict when token name matches and styles match", () => {- const fragmentStyleSources: StyleSource[] = [- { type: "token", id: "frag1", name: "SharedToken" },- ];-- const fragmentStyles: StyleDecl[] = [- {- breakpointId: "base",- styleSourceId: "frag1",- property: "color",- value: { type: "keyword", value: "red" },- },- ];-- const existingStyleSources = new Map<string, StyleSource>([- ["exist1", { type: "token", id: "exist1", name: "SharedToken" }],- ]);-- const existingStyles = new Map<string, StyleDecl>([- [- "exist1:base:color",- {- breakpointId: "base",- styleSourceId: "exist1",- property: "color",- value: { type: "keyword", value: "red" }, // Same color- },- ],- ]);-- const conflicts = detectTokenConflicts({- fragmentStyleSources,- fragmentStyles,- existingStyleSources,- existingStyles,- breakpoints,- mergedBreakpointIds: new Map(),- });-- expect(conflicts).toHaveLength(0);- });-- test("handles tokens with no styles", () => {- const fragmentStyleSources: StyleSource[] = [- { type: "token", id: "frag1", name: "EmptyToken" },- ];-- const fragmentStyles: StyleDecl[] = [];-- const existingStyleSources = new Map<string, StyleSource>([- ["exist1", { type: "token", id: "exist1", name: "EmptyToken" }],- ]);-- const existingStyles = new Map<string, StyleDecl>();-- const conflicts = detectTokenConflicts({- fragmentStyleSources,- fragmentStyles,- existingStyleSources,- existingStyles,- breakpoints,- mergedBreakpointIds: new Map(),- });-- expect(conflicts).toHaveLength(0);- });-- test("uses merged breakpoint IDs when comparing", () => {- const fragmentStyleSources: StyleSource[] = [- { type: "token", id: "frag1", name: "ResponsiveToken" },- ];-- const fragmentStyles: StyleDecl[] = [- {- breakpointId: "tablet-frag",- styleSourceId: "frag1",- property: "fontSize",- value: { type: "unit", value: 18, unit: "px" },- },- ];-- const breakpointsMap = new Map<Breakpoint["id"], Breakpoint>([- ["base", { id: "base", label: "Base" }],- ["tablet-exist", { id: "tablet-exist", minWidth: 768, label: "Tablet" }],- ]);-- const mergedBreakpointIds = new Map([["tablet-frag", "tablet-exist"]]);-- const existingStyleSources = new Map<string, StyleSource>([- ["exist1", { type: "token", id: "exist1", name: "ResponsiveToken" }],- ]);-- const existingStyles = new Map<string, StyleDecl>([- [- "exist1:tablet-exist:fontSize",- {- breakpointId: "tablet-exist",- styleSourceId: "exist1",- property: "fontSize",- value: { type: "unit", value: 18, unit: "px" },- },- ],- ]);-- const conflicts = detectTokenConflicts({- fragmentStyleSources,- fragmentStyles,- existingStyleSources,- existingStyles,- breakpoints: breakpointsMap,- mergedBreakpointIds,- });-- // Should be no conflict since the breakpoints are merged and styles match- expect(conflicts).toHaveLength(0);- });-});diff --git a/apps/builder/app/shared/sync/command-queue.test.ts b/apps/builder/app/shared/sync/command-queue.test.tsindex 54207df2db..df7ac326e4 100644--- a/apps/builder/app/shared/sync/command-queue.test.ts+++ b/apps/builder/app/shared/sync/command-queue.test.ts@@ -1,10 +1,12 @@import { describe, test, expect, beforeEach } from "vitest";+import type { BuilderPatchChange } from "@webstudio-is/project-build/contracts/patch";+import type { Transaction } from "@webstudio-is/sync-client";import { enqueue, dequeueAll } from "./command-queue";-const makeTx = (id: string) => ({+const makeTx = (id: string): Transaction<BuilderPatchChange[]> => ({id,object: "server",- payload: [{ namespace: "ns", patches: [], revisePatches: [] }],+ payload: [{ namespace: "pages", patches: [] }],});describe("command-queue", () => {diff --git a/apps/builder/app/shared/sync/command-queue.ts b/apps/builder/app/shared/sync/command-queue.tsindex dd632a5690..35e0e9a0c4 100644--- a/apps/builder/app/shared/sync/command-queue.ts+++ b/apps/builder/app/shared/sync/command-queue.ts@@ -1,13 +1,13 @@import type { Project } from "@webstudio-is/project";import type { Build } from "@webstudio-is/project-build";-import type { Change } from "immerhin";+import type { BuilderPatchChange } from "@webstudio-is/project-build/contracts/patch";import type { Transaction } from "@webstudio-is/sync-client";type Command =| {type: "transactions";projectId: Project["id"];- transactions: Transaction<Change[]>[];+ transactions: Transaction<BuilderPatchChange[]>[];}| {type: "setDetails";diff --git a/apps/builder/app/shared/sync/patch/patch-auth.server.ts b/apps/builder/app/shared/sync/patch/patch-auth.server.tsindex a03c670936..cc5f4266c3 100644--- a/apps/builder/app/shared/sync/patch/patch-auth.server.ts+++ b/apps/builder/app/shared/sync/patch/patch-auth.server.ts@@ -9,11 +9,9 @@ import {getContentModeCapabilities,} from "@webstudio-is/project/content-mode-permissions";import {- coreMetas,type Breakpoint,type Prop,type StyleSource,- type WsComponentMeta,} from "@webstudio-is/sdk";import {parseData,@@ -21,25 +19,14 @@ import {} from "@webstudio-is/project-build/build-parser.server";import { parseStyleSourceSelections } from "@webstudio-is/project-build/style-source-selections.server";import { parseStyles } from "@webstudio-is/project-build/styles.server";-import * as baseComponentMetas from "@webstudio-is/sdk-components-react/metas";-import * as animationComponentMetas from "@webstudio-is/sdk-components-animation/metas";-import * as radixComponentMetas from "@webstudio-is/sdk-components-react-radix/metas";import env from "~/env/env.server";import { readAccessToken } from "~/services/token.server";+import { componentMetas } from "~/shared/component-metas.server";import type {NormalizedPatchRequest,PatchEntry,} from "./patch-normalize.server";-const componentMetas = new Map<string, WsComponentMeta>(- Object.entries({- ...coreMetas,- ...baseComponentMetas,- ...animationComponentMetas,- ...radixComponentMetas,- })-);-export type AuthorizedPatchEntry = {entry: PatchEntry;context: AppContext;diff --git a/apps/builder/app/shared/sync/project-queue.test.ts b/apps/builder/app/shared/sync/project-queue.test.tsindex 59ae440164..acdce5c3b4 100644--- a/apps/builder/app/shared/sync/project-queue.test.ts+++ b/apps/builder/app/shared/sync/project-queue.test.ts@@ -46,8 +46,12 @@ vi.mock("~/shared/builder-data", () => ({// Imports (after mocks)-import type { Change } from "immerhin";-import { $hasUnsavedSyncChanges, $syncStatus } from "@webstudio-is/sync-client";+import type { BuilderPatchChange } from "@webstudio-is/project-build/contracts/patch";+import {+ $hasUnsavedSyncChanges,+ $syncStatus,+ type Transaction,+} from "@webstudio-is/sync-client";import { toast } from "@webstudio-is/design-system";import type { ServerSyncState } from "./sync-stores";import {@@ -76,10 +80,10 @@ const MAX_ALLOWED_API_ERRORS = 5;const flush = () => vi.advanceTimersByTimeAsync(0);-const makeTx = (id: string) => ({+const makeTx = (id: string): Transaction<BuilderPatchChange[]> => ({id,object: "server" as const,- payload: [{ namespace: "ns", patches: [], revisePatches: [] }] as Change[],+ payload: [{ namespace: "pages", patches: [] }],});const initialState: ServerSyncState = new Map();@@ -517,7 +521,7 @@ describe("project-queue", () => {storage.sendTransaction({id: "tx-1",object: "server",- payload: [{ namespace: "ns", patches: [], revisePatches: [] }],+ payload: [{ namespace: "pages", patches: [] }],});const commands = commandQueue.dequeueAll();@@ -546,7 +550,7 @@ describe("project-queue", () => {storage.sendTransaction({id: "tx-42",object: "server",- payload: [{ namespace: "ns", patches: [], revisePatches: [] }],+ payload: [{ namespace: "pages", patches: [] }],});expect($lastTransactionId.get()).toBe("tx-42");diff --git a/apps/builder/app/shared/sync/project-queue.ts b/apps/builder/app/shared/sync/project-queue.tsindex 5b86ed0464..ea7b0b257f 100644--- a/apps/builder/app/shared/sync/project-queue.ts+++ b/apps/builder/app/shared/sync/project-queue.ts@@ -1,8 +1,8 @@import { useEffect } from "react";import { atom } from "nanostores";-import type { Change } from "immerhin";import type { Project } from "@webstudio-is/project";import type { Build } from "@webstudio-is/project-build";+import type { BuilderPatchChange } from "@webstudio-is/project-build/contracts/patch";import type { AuthPermit } from "@webstudio-is/trpc-interface/index.server";import { toast } from "@webstudio-is/design-system";import {@@ -10,6 +10,7 @@ import {$syncStatus,createBackoff,createTransactionCompletionStore,+ stripRevisePatchesFromTransaction,type SyncStatus,} from "@webstudio-is/sync-client";import { publicStaticEnv } from "~/env/env.static";@@ -230,14 +231,9 @@ const pollQueue = async (signal: AbortSignal) => {for await (const _ of retry()) {// in case of any error continue retryingtry {- // revise patches are not used on the server and reduce possible patch size- const optimizedTransactions = transactions.map((transaction) => ({- ...transaction,- payload: transaction.payload.map((change) => ({- namespace: change.namespace,- patches: change.patches,- })),- }));+ const optimizedTransactions = transactions.map(+ stripRevisePatchesFromTransaction+ );const patchClient =details.authToken === undefined? nativeClient@@ -344,7 +340,7 @@ export class ServerSyncStorage implements SyncStorage {this.initialState = initialState;}- sendTransaction(transaction: Transaction<Change[]>) {+ sendTransaction(transaction: Transaction<BuilderPatchChange[]>) {if (transaction.object === "server") {$lastTransactionId.set(transaction.id);$syncStatus.set({ status: "syncing" });diff --git a/apps/builder/app/shared/tailwind/tailwind.ts b/apps/builder/app/shared/tailwind/tailwind.tsindex 1537cfe0b5..5dfb6e67c6 100644--- a/apps/builder/app/shared/tailwind/tailwind.ts+++ b/apps/builder/app/shared/tailwind/tailwind.ts@@ -15,7 +15,7 @@ import {type Prop,type WebstudioFragment,} from "@webstudio-is/sdk";-import { isBaseBreakpoint } from "../breakpoints-utils";+import { isBaseBreakpoint } from "@webstudio-is/project-build/runtime/breakpoints";import { preflight } from "./__generated__/preflight";// breakpoints used to map tailwind classes to webstudio breakpointsdiff --git a/apps/builder/app/shared/token-conflict-dialog.tsx b/apps/builder/app/shared/token-conflict-dialog.tsxindex 636e6eefa0..901f012667 100644--- a/apps/builder/app/shared/token-conflict-dialog.tsx+++ b/apps/builder/app/shared/token-conflict-dialog.tsx@@ -15,7 +15,7 @@ import {Radio,Label,} from "@webstudio-is/design-system";-import type { TokenConflict } from "./style-source-utils";+import type { TokenConflict } from "@webstudio-is/project-build/runtime/style-copy";export type ConflictResolution = "ours" | "theirs" | "merge";diff --git a/apps/builder/e2e/flows/share-dialog.ts b/apps/builder/e2e/flows/share-dialog.tsindex d348e1ace0..0e710b53d7 100644--- a/apps/builder/e2e/flows/share-dialog.ts+++ b/apps/builder/e2e/flows/share-dialog.ts@@ -114,12 +114,28 @@ export const createShareLink = async ({page,name: "Custom link",});- await customLinkOptions.getByLabel("Name").fill(name);- await page.keyboard.press("Enter");+ const nameInput = customLinkOptions.getByLabel("Name");+ await nameInput.fill(name);+ await customLink+ .getByRole("button", { name: "Menu Button for options" })+ .click();await waitForShareLinkMutation({ page });const renamedLink = getShareLinkGroup({ page, name });- await renamedLink.waitFor({ state: "visible", timeout: 10_000 });+ try {+ await renamedLink.waitFor({ state: "visible", timeout: 10_000 });+ } catch (error) {+ const shareLinkLabels = await page+ .locator('[role="group"][aria-label^="Share link "]')+ .evaluateAll((elements) =>+ elements.map((element) => element.getAttribute("aria-label"))+ );+ const isBusy = await getShareLinksRegion(page).getAttribute("aria-busy");+ throw new Error(+ `Expected renamed share link "${name}" to be visible. aria-busy=${isBusy}; links=${shareLinkLabels.join(", ")}`,+ { cause: error }+ );+ }await renamedLink.getByRole("button", { name: "Menu Button for options" }).click();diff --git a/apps/builder/e2e/flows/sync-status.ts b/apps/builder/e2e/flows/sync-status.tsindex 095f9aef40..964390cd1f 100644--- a/apps/builder/e2e/flows/sync-status.ts+++ b/apps/builder/e2e/flows/sync-status.ts@@ -44,15 +44,24 @@ export const waitForChangeToBeSaved = async ({timeout,});+ const errorStatus = getSyncStatusDotByStatus({ page, status: "error" })+ .waitFor({ timeout })+ .then(async () => {+ const label =+ (await getSyncStatusDot(page).getAttribute("aria-label")) ??+ "Sync status: error";+ throw new Error(`Expected change to save, received ${label}`);+ });++ await Promise.race([+ getSyncStatusDotByStatus({ page, status: "pending" }).waitFor({+ timeout,+ }),+ errorStatus,+ ]);+await Promise.race([getSyncStatusDotByStatus({ page, status: "saved" }).waitFor({ timeout }),- getSyncStatusDotByStatus({ page, status: "error" })- .waitFor({ timeout })- .then(async () => {- const label =- (await getSyncStatusDot(page).getAttribute("aria-label")) ??- "Sync status: error";- throw new Error(`Expected change to save, received ${label}`);- }),+ errorStatus,]);};diff --git a/apps/builder/e2e/harness.ts b/apps/builder/e2e/harness.tsindex 9733a239dd..cef493f49d 100644--- a/apps/builder/e2e/harness.ts+++ b/apps/builder/e2e/harness.ts@@ -1,4 +1,4 @@-import { parseBuilderUrl } from "@webstudio-is/http-client";+import { parseBuilderUrl } from "@webstudio-is/protocol";import { basename } from "node:path";import {chromium,diff --git a/apps/builder/e2e/schema/current.sql b/apps/builder/e2e/schema/current.sqlindex acecc21214..4c7bdbbf13 100644--- a/apps/builder/e2e/schema/current.sql+++ b/apps/builder/e2e/schema/current.sql@@ -702,7 +702,8 @@ CREATE TABLE public."AuthorizationToken" ("createdAt" timestamp(3) with time zone DEFAULT CURRENT_TIMESTAMP NOT NULL,"canClone" boolean DEFAULT true NOT NULL,"canCopy" boolean DEFAULT true NOT NULL,- "canPublish" boolean DEFAULT false NOT NULL+ "canPublish" boolean DEFAULT false NOT NULL,+ "canUseApi" boolean DEFAULT false NOT NULL);@@ -1458,4 +1459,3 @@ ALTER TABLE ONLY public."latestBuildVirtual"--\unrestrict J29mZQHzSYuDPm8eRJiWoDBJq2TAh0b0ii1URRuunEM0BP9wmmC5I93noDiexdr-diff --git a/apps/builder/vitest.config.ts b/apps/builder/vitest.config.tsindex f9809724ba..39bcbc445b 100644--- a/apps/builder/vitest.config.ts+++ b/apps/builder/vitest.config.ts@@ -10,13 +10,10 @@ export default defineConfig({},],conditions: ["webstudio", "browser", "development|production"],- // conditions: ["webstudio", ...defaultClientConditions],},- // resolve webstudio condition in testsssr: {resolve: {conditions: ["webstudio", "node", "development|production"],- // conditions: ["webstudio", ...defaultServerConditions],},},test: {diff --git a/fixtures/react-router-cloudflare/.webstudio/assets/147-1478573_cat-icon-png-black-cat-png-icon.png_ZJ6-qJjk1RlFzuYwyCXdp.jpeg b/fixtures/react-router-cloudflare/.webstudio/assets/147-1478573_cat-icon-png-black-cat-png-icon.png_ZJ6-qJjk1RlFzuYwyCXdp.jpegnew file mode 100644index 0000000000..9d5e2b8843Binary files /dev/null and b/fixtures/react-router-cloudflare/.webstudio/assets/147-1478573_cat-icon-png-black-cat-png-icon.png_ZJ6-qJjk1RlFzuYwyCXdp.jpeg differdiff --git a/fixtures/react-router-cloudflare/.webstudio/assets/iconly_svg_converted-converted_zMaMiAAutUl8XrITgz7d1.svg b/fixtures/react-router-cloudflare/.webstudio/assets/iconly_svg_converted-converted_zMaMiAAutUl8XrITgz7d1.svgnew file mode 100644index 0000000000..bc70d3a453--- /dev/null+++ b/fixtures/react-router-cloudflare/.webstudio/assets/iconly_svg_converted-converted_zMaMiAAutUl8XrITgz7d1.svg@@ -0,0 +1 @@+<svg width="14" height="16" xmlns="http://www.w3.org/2000/svg"><path d="M4.203.702a.713.713 0 0 0-.366.213c-.124.148-.137.208-.15.672l-.012.431-.443.015c-.481.017-.686.041-.991.117-.651.161-1.273.668-1.586 1.29a2.834 2.834 0 0 0-.252.839c-.038.241-.041.553-.041 4.366 0 4.4-.002 4.323.117 4.784.107.412.325.79.639 1.106.422.426.865.64 1.536.742.255.038.554.041 4.346.041s4.091-.003 4.346-.041c.671-.102 1.114-.316 1.536-.742.314-.316.532-.694.639-1.106.119-.461.117-.384.117-4.784 0-3.813-.003-4.125-.041-4.366a2.834 2.834 0 0 0-.252-.839c-.313-.622-.935-1.129-1.586-1.29-.305-.076-.51-.1-.991-.117l-.443-.015-.012-.431c-.013-.488-.039-.581-.204-.726C9.91.687 9.61.64 9.39.75c-.132.066-.302.249-.339.366a3.432 3.432 0 0 0-.038.5l-.011.414H4.998l-.011-.414a3.432 3.432 0 0 0-.038-.5c-.036-.115-.207-.3-.332-.361a.689.689 0 0 0-.414-.053m2.139 9.442-.007.088-.038-.105a5.451 5.451 0 0 0-.054-.142c-.01-.025.003-.045.039-.061.049-.022.054-.018.06.054a1.15 1.15 0 0 1 0 .166" fill-rule="evenodd"/></svg>\ No newline at end of filediff --git a/fixtures/react-router-docker/.webstudio/assets/147-1478573_cat-icon-png-black-cat-png-icon.png_ZJ6-qJjk1RlFzuYwyCXdp.jpeg b/fixtures/react-router-docker/.webstudio/assets/147-1478573_cat-icon-png-black-cat-png-icon.png_ZJ6-qJjk1RlFzuYwyCXdp.jpegnew file mode 100644index 0000000000..9d5e2b8843Binary files /dev/null and b/fixtures/react-router-docker/.webstudio/assets/147-1478573_cat-icon-png-black-cat-png-icon.png_ZJ6-qJjk1RlFzuYwyCXdp.jpeg differdiff --git a/fixtures/react-router-docker/.webstudio/assets/iconly_svg_converted-converted_zMaMiAAutUl8XrITgz7d1.svg b/fixtures/react-router-docker/.webstudio/assets/iconly_svg_converted-converted_zMaMiAAutUl8XrITgz7d1.svgnew file mode 100644index 0000000000..bc70d3a453--- /dev/null+++ b/fixtures/react-router-docker/.webstudio/assets/iconly_svg_converted-converted_zMaMiAAutUl8XrITgz7d1.svg@@ -0,0 +1 @@+<svg width="14" height="16" xmlns="http://www.w3.org/2000/svg"><path d="M4.203.702a.713.713 0 0 0-.366.213c-.124.148-.137.208-.15.672l-.012.431-.443.015c-.481.017-.686.041-.991.117-.651.161-1.273.668-1.586 1.29a2.834 2.834 0 0 0-.252.839c-.038.241-.041.553-.041 4.366 0 4.4-.002 4.323.117 4.784.107.412.325.79.639 1.106.422.426.865.64 1.536.742.255.038.554.041 4.346.041s4.091-.003 4.346-.041c.671-.102 1.114-.316 1.536-.742.314-.316.532-.694.639-1.106.119-.461.117-.384.117-4.784 0-3.813-.003-4.125-.041-4.366a2.834 2.834 0 0 0-.252-.839c-.313-.622-.935-1.129-1.586-1.29-.305-.076-.51-.1-.991-.117l-.443-.015-.012-.431c-.013-.488-.039-.581-.204-.726C9.91.687 9.61.64 9.39.75c-.132.066-.302.249-.339.366a3.432 3.432 0 0 0-.038.5l-.011.414H4.998l-.011-.414a3.432 3.432 0 0 0-.038-.5c-.036-.115-.207-.3-.332-.361a.689.689 0 0 0-.414-.053m2.139 9.442-.007.088-.038-.105a5.451 5.451 0 0 0-.054-.142c-.01-.025.003-.045.039-.061.049-.022.054-.018.06.054a1.15 1.15 0 0 1 0 .166" fill-rule="evenodd"/></svg>\ No newline at end of filediff --git a/fixtures/react-router-netlify/.webstudio/assets/147-1478573_cat-icon-png-black-cat-png-icon.png_ZJ6-qJjk1RlFzuYwyCXdp.jpeg b/fixtures/react-router-netlify/.webstudio/assets/147-1478573_cat-icon-png-black-cat-png-icon.png_ZJ6-qJjk1RlFzuYwyCXdp.jpegnew file mode 100644index 0000000000..9d5e2b8843Binary files /dev/null and b/fixtures/react-router-netlify/.webstudio/assets/147-1478573_cat-icon-png-black-cat-png-icon.png_ZJ6-qJjk1RlFzuYwyCXdp.jpeg differdiff --git a/fixtures/react-router-netlify/.webstudio/assets/iconly_svg_converted-converted_zMaMiAAutUl8XrITgz7d1.svg b/fixtures/react-router-netlify/.webstudio/assets/iconly_svg_converted-converted_zMaMiAAutUl8XrITgz7d1.svgnew file mode 100644index 0000000000..bc70d3a453--- /dev/null+++ b/fixtures/react-router-netlify/.webstudio/assets/iconly_svg_converted-converted_zMaMiAAutUl8XrITgz7d1.svg@@ -0,0 +1 @@+<svg width="14" height="16" xmlns="http://www.w3.org/2000/svg"><path d="M4.203.702a.713.713 0 0 0-.366.213c-.124.148-.137.208-.15.672l-.012.431-.443.015c-.481.017-.686.041-.991.117-.651.161-1.273.668-1.586 1.29a2.834 2.834 0 0 0-.252.839c-.038.241-.041.553-.041 4.366 0 4.4-.002 4.323.117 4.784.107.412.325.79.639 1.106.422.426.865.64 1.536.742.255.038.554.041 4.346.041s4.091-.003 4.346-.041c.671-.102 1.114-.316 1.536-.742.314-.316.532-.694.639-1.106.119-.461.117-.384.117-4.784 0-3.813-.003-4.125-.041-4.366a2.834 2.834 0 0 0-.252-.839c-.313-.622-.935-1.129-1.586-1.29-.305-.076-.51-.1-.991-.117l-.443-.015-.012-.431c-.013-.488-.039-.581-.204-.726C9.91.687 9.61.64 9.39.75c-.132.066-.302.249-.339.366a3.432 3.432 0 0 0-.038.5l-.011.414H4.998l-.011-.414a3.432 3.432 0 0 0-.038-.5c-.036-.115-.207-.3-.332-.361a.689.689 0 0 0-.414-.053m2.139 9.442-.007.088-.038-.105a5.451 5.451 0 0 0-.054-.142c-.01-.025.003-.045.039-.061.049-.022.054-.018.06.054a1.15 1.15 0 0 1 0 .166" fill-rule="evenodd"/></svg>\ No newline at end of filediff --git a/fixtures/react-router-vercel/.webstudio/assets/147-1478573_cat-icon-png-black-cat-png-icon.png_ZJ6-qJjk1RlFzuYwyCXdp.jpeg b/fixtures/react-router-vercel/.webstudio/assets/147-1478573_cat-icon-png-black-cat-png-icon.png_ZJ6-qJjk1RlFzuYwyCXdp.jpegnew file mode 100644index 0000000000..9d5e2b8843Binary files /dev/null and b/fixtures/react-router-vercel/.webstudio/assets/147-1478573_cat-icon-png-black-cat-png-icon.png_ZJ6-qJjk1RlFzuYwyCXdp.jpeg differdiff --git a/fixtures/react-router-vercel/.webstudio/assets/iconly_svg_converted-converted_zMaMiAAutUl8XrITgz7d1.svg b/fixtures/react-router-vercel/.webstudio/assets/iconly_svg_converted-converted_zMaMiAAutUl8XrITgz7d1.svgnew file mode 100644index 0000000000..bc70d3a453--- /dev/null+++ b/fixtures/react-router-vercel/.webstudio/assets/iconly_svg_converted-converted_zMaMiAAutUl8XrITgz7d1.svg@@ -0,0 +1 @@+<svg width="14" height="16" xmlns="http://www.w3.org/2000/svg"><path d="M4.203.702a.713.713 0 0 0-.366.213c-.124.148-.137.208-.15.672l-.012.431-.443.015c-.481.017-.686.041-.991.117-.651.161-1.273.668-1.586 1.29a2.834 2.834 0 0 0-.252.839c-.038.241-.041.553-.041 4.366 0 4.4-.002 4.323.117 4.784.107.412.325.79.639 1.106.422.426.865.64 1.536.742.255.038.554.041 4.346.041s4.091-.003 4.346-.041c.671-.102 1.114-.316 1.536-.742.314-.316.532-.694.639-1.106.119-.461.117-.384.117-4.784 0-3.813-.003-4.125-.041-4.366a2.834 2.834 0 0 0-.252-.839c-.313-.622-.935-1.129-1.586-1.29-.305-.076-.51-.1-.991-.117l-.443-.015-.012-.431c-.013-.488-.039-.581-.204-.726C9.91.687 9.61.64 9.39.75c-.132.066-.302.249-.339.366a3.432 3.432 0 0 0-.038.5l-.011.414H4.998l-.011-.414a3.432 3.432 0 0 0-.038-.5c-.036-.115-.207-.3-.332-.361a.689.689 0 0 0-.414-.053m2.139 9.442-.007.088-.038-.105a5.451 5.451 0 0 0-.054-.142c-.01-.025.003-.045.039-.061.049-.022.054-.018.06.054a1.15 1.15 0 0 1 0 .166" fill-rule="evenodd"/></svg>\ No newline at end of filediff --git a/fixtures/ssg-cloudflare-pages/.webstudio/assets/147-1478573_cat-icon-png-black-cat-png-icon.png_ZJ6-qJjk1RlFzuYwyCXdp.jpeg b/fixtures/ssg-cloudflare-pages/.webstudio/assets/147-1478573_cat-icon-png-black-cat-png-icon.png_ZJ6-qJjk1RlFzuYwyCXdp.jpegnew file mode 100644index 0000000000..9d5e2b8843Binary files /dev/null and b/fixtures/ssg-cloudflare-pages/.webstudio/assets/147-1478573_cat-icon-png-black-cat-png-icon.png_ZJ6-qJjk1RlFzuYwyCXdp.jpeg differdiff --git a/fixtures/ssg-cloudflare-pages/.webstudio/assets/iconly_svg_converted-converted_zMaMiAAutUl8XrITgz7d1.svg b/fixtures/ssg-cloudflare-pages/.webstudio/assets/iconly_svg_converted-converted_zMaMiAAutUl8XrITgz7d1.svgnew file mode 100644index 0000000000..bc70d3a453--- /dev/null+++ b/fixtures/ssg-cloudflare-pages/.webstudio/assets/iconly_svg_converted-converted_zMaMiAAutUl8XrITgz7d1.svg@@ -0,0 +1 @@+<svg width="14" height="16" xmlns="http://www.w3.org/2000/svg"><path d="M4.203.702a.713.713 0 0 0-.366.213c-.124.148-.137.208-.15.672l-.012.431-.443.015c-.481.017-.686.041-.991.117-.651.161-1.273.668-1.586 1.29a2.834 2.834 0 0 0-.252.839c-.038.241-.041.553-.041 4.366 0 4.4-.002 4.323.117 4.784.107.412.325.79.639 1.106.422.426.865.64 1.536.742.255.038.554.041 4.346.041s4.091-.003 4.346-.041c.671-.102 1.114-.316 1.536-.742.314-.316.532-.694.639-1.106.119-.461.117-.384.117-4.784 0-3.813-.003-4.125-.041-4.366a2.834 2.834 0 0 0-.252-.839c-.313-.622-.935-1.129-1.586-1.29-.305-.076-.51-.1-.991-.117l-.443-.015-.012-.431c-.013-.488-.039-.581-.204-.726C9.91.687 9.61.64 9.39.75c-.132.066-.302.249-.339.366a3.432 3.432 0 0 0-.038.5l-.011.414H4.998l-.011-.414a3.432 3.432 0 0 0-.038-.5c-.036-.115-.207-.3-.332-.361a.689.689 0 0 0-.414-.053m2.139 9.442-.007.088-.038-.105a5.451 5.451 0 0 0-.054-.142c-.01-.025.003-.045.039-.061.049-.022.054-.018.06.054a1.15 1.15 0 0 1 0 .166" fill-rule="evenodd"/></svg>\ No newline at end of filediff --git a/fixtures/webstudio-cloudflare-template/.webstudio/assets/147-1478573_cat-icon-png-black-cat-png-icon.png_ZJ6-qJjk1RlFzuYwyCXdp.jpeg b/fixtures/webstudio-cloudflare-template/.webstudio/assets/147-1478573_cat-icon-png-black-cat-png-icon.png_ZJ6-qJjk1RlFzuYwyCXdp.jpegnew file mode 100644index 0000000000..9d5e2b8843Binary files /dev/null and b/fixtures/webstudio-cloudflare-template/.webstudio/assets/147-1478573_cat-icon-png-black-cat-png-icon.png_ZJ6-qJjk1RlFzuYwyCXdp.jpeg differdiff --git a/fixtures/webstudio-cloudflare-template/.webstudio/assets/iconly_svg_converted-converted_zMaMiAAutUl8XrITgz7d1.svg b/fixtures/webstudio-cloudflare-template/.webstudio/assets/iconly_svg_converted-converted_zMaMiAAutUl8XrITgz7d1.svgnew file mode 100644index 0000000000..bc70d3a453--- /dev/null+++ b/fixtures/webstudio-cloudflare-template/.webstudio/assets/iconly_svg_converted-converted_zMaMiAAutUl8XrITgz7d1.svg@@ -0,0 +1 @@+<svg width="14" height="16" xmlns="http://www.w3.org/2000/svg"><path d="M4.203.702a.713.713 0 0 0-.366.213c-.124.148-.137.208-.15.672l-.012.431-.443.015c-.481.017-.686.041-.991.117-.651.161-1.273.668-1.586 1.29a2.834 2.834 0 0 0-.252.839c-.038.241-.041.553-.041 4.366 0 4.4-.002 4.323.117 4.784.107.412.325.79.639 1.106.422.426.865.64 1.536.742.255.038.554.041 4.346.041s4.091-.003 4.346-.041c.671-.102 1.114-.316 1.536-.742.314-.316.532-.694.639-1.106.119-.461.117-.384.117-4.784 0-3.813-.003-4.125-.041-4.366a2.834 2.834 0 0 0-.252-.839c-.313-.622-.935-1.129-1.586-1.29-.305-.076-.51-.1-.991-.117l-.443-.015-.012-.431c-.013-.488-.039-.581-.204-.726C9.91.687 9.61.64 9.39.75c-.132.066-.302.249-.339.366a3.432 3.432 0 0 0-.038.5l-.011.414H4.998l-.011-.414a3.432 3.432 0 0 0-.038-.5c-.036-.115-.207-.3-.332-.361a.689.689 0 0 0-.414-.053m2.139 9.442-.007.088-.038-.105a5.451 5.451 0 0 0-.054-.142c-.01-.025.003-.045.039-.061.049-.022.054-.018.06.054a1.15 1.15 0 0 1 0 .166" fill-rule="evenodd"/></svg>\ No newline at end of filediff --git a/fixtures/webstudio-cloudflare-template/vite.config.ts b/fixtures/webstudio-cloudflare-template/vite.config.tsindex fa01ca299d..938c8bec6f 100644--- a/fixtures/webstudio-cloudflare-template/vite.config.ts+++ b/fixtures/webstudio-cloudflare-template/vite.config.ts@@ -4,20 +4,21 @@ import {} from "@remix-run/dev";import { defineConfig } from "vite";-import { existsSync } from "node:fs";-// @ts-ignore-import path from "node:path";-// @ts-ignore-import fg from "fast-glob";+import { existsSync, readdirSync } from "node:fs";-const rootDir = ["..", "../..", "../../.."]- .map((dir) => path.join(__dirname, dir))- .find((dir) => existsSync(path.join(dir, ".git")));+const rootDir = ["..", "../..", "../../.."].find((dir) =>+ existsSync(`${dir}/.git`)+);const hasPrivateFolders =- fg.sync([path.join(rootDir ?? "", "packages/*/private-src/*")], {- ignore: ["**/node_modules/**"],- }).length > 0;+ rootDir !== undefined &&+ existsSync(`${rootDir}/packages`) &&+ readdirSync(`${rootDir}/packages`, { withFileTypes: true }).some((entry) => {+ return (+ entry.isDirectory() &&+ existsSync(`${rootDir}/packages/${entry.name}/private-src`)+ );+ });const conditions = hasPrivateFolders? ["webstudio-private", "webstudio"]diff --git a/fixtures/webstudio-features/.webstudio/assets/_937084ed-a798-49fe-8664-df93a2af605e_uiBk3o6UWdqolyakMvQJ9.jpeg b/fixtures/webstudio-features/.webstudio/assets/_937084ed-a798-49fe-8664-df93a2af605e_uiBk3o6UWdqolyakMvQJ9.jpegnew file mode 100644index 0000000000..1c8219b73bBinary files /dev/null and b/fixtures/webstudio-features/.webstudio/assets/_937084ed-a798-49fe-8664-df93a2af605e_uiBk3o6UWdqolyakMvQJ9.jpeg differdiff --git a/fixtures/webstudio-features/.webstudio/assets/cat_silhouette_BDpTbUFSpVbfUWQZNxbBG.png b/fixtures/webstudio-features/.webstudio/assets/cat_silhouette_BDpTbUFSpVbfUWQZNxbBG.pngnew file mode 100644index 0000000000..72c49a3ab2Binary files /dev/null and b/fixtures/webstudio-features/.webstudio/assets/cat_silhouette_BDpTbUFSpVbfUWQZNxbBG.png differdiff --git a/fixtures/webstudio-features/.webstudio/assets/e-mail-39993_vrxyjxQv3j67Krs62Vz7Y.mp3 b/fixtures/webstudio-features/.webstudio/assets/e-mail-39993_vrxyjxQv3j67Krs62Vz7Y.mp3new file mode 100644index 0000000000..e7f4bbf8f9Binary files /dev/null and b/fixtures/webstudio-features/.webstudio/assets/e-mail-39993_vrxyjxQv3j67Krs62Vz7Y.mp3 differdiff --git a/fixtures/webstudio-features/.webstudio/assets/small-avif-kitty_FnabJsioMWpBtXZSGf4DR.webp b/fixtures/webstudio-features/.webstudio/assets/small-avif-kitty_FnabJsioMWpBtXZSGf4DR.webpnew file mode 100644index 0000000000..dcb31617dcBinary files /dev/null and b/fixtures/webstudio-features/.webstudio/assets/small-avif-kitty_FnabJsioMWpBtXZSGf4DR.webp differdiff --git a/fixtures/webstudio-features/.webstudio/assets/video_QamtUWsD-ShifhzZLoNIv_ald_1xtyEb3uHhFb7nCQa.mp4 b/fixtures/webstudio-features/.webstudio/assets/video_QamtUWsD-ShifhzZLoNIv_ald_1xtyEb3uHhFb7nCQa.mp4new file mode 100644index 0000000000..2868ea936eBinary files /dev/null and b/fixtures/webstudio-features/.webstudio/assets/video_QamtUWsD-ShifhzZLoNIv_ald_1xtyEb3uHhFb7nCQa.mp4 differdiff --git a/fixtures/webstudio-features/.webstudio/assets/webm-example_2r_6VmRBjhAy3ldaqz0gk.webm b/fixtures/webstudio-features/.webstudio/assets/webm-example_2r_6VmRBjhAy3ldaqz0gk.webmnew file mode 100644index 0000000000..7456528682Binary files /dev/null and b/fixtures/webstudio-features/.webstudio/assets/webm-example_2r_6VmRBjhAy3ldaqz0gk.webm differdiff --git a/packages/authorization-token/package.json b/packages/authorization-token/package.jsonindex 347fb8d3dc..3b6500b200 100644--- a/packages/authorization-token/package.json+++ b/packages/authorization-token/package.json@@ -12,6 +12,7 @@"dependencies": {"@webstudio-is/postgrest": "workspace:*","@webstudio-is/trpc-interface": "workspace:*",+ "@trpc/server": "^10.45.2","zod": "^3.24.2"},"devDependencies": {diff --git a/packages/authorization-token/src/db/authorization-token.test.ts b/packages/authorization-token/src/db/authorization-token.test.tsindex 6987d50578..b5b48eae50 100644--- a/packages/authorization-token/src/db/authorization-token.test.ts+++ b/packages/authorization-token/src/db/authorization-token.test.ts@@ -6,14 +6,17 @@ import {testContext,} from "@webstudio-is/postgrest/testing";import type { AppContext } from "@webstudio-is/trpc-interface/index.server";+import { PlanRequiredError } from "@webstudio-is/trpc-interface/index.server";import {findMany,getTokenInfo,+ getTokenProjectPermits,create,update,remove,__testing__,} from "./authorization-token";+import { authorizationTokenRouter } from "../trpc/authorization-tokens-router";const { applyTokenPermissions } = __testing__;@@ -30,6 +33,7 @@ const baseToken = {canClone: false,canCopy: false,canPublish: true,+ canUseApi: false,};describe("applyTokenPermissions", () => {@@ -73,6 +77,36 @@ describe("applyTokenPermissions", () => {expect(result.canCopy).toBe(true);expect(result.canPublish).toBe(true);});++ test("preserves explicit API capability", () => {+ const result = applyTokenPermissions({+ ...baseToken,+ relation: "viewers",+ canUseApi: true,+ });+ expect(result.canUseApi).toBe(true);+ });+});++describe("getTokenProjectPermits", () => {+ test("maps token relation to project permits", () => {+ expect(getTokenProjectPermits({ relation: "viewers" })).toEqual(["view"]);+ expect(getTokenProjectPermits({ relation: "editors" })).toEqual([+ "view",+ "edit",+ ]);+ expect(getTokenProjectPermits({ relation: "builders" })).toEqual([+ "view",+ "edit",+ "build",+ ]);+ expect(getTokenProjectPermits({ relation: "administrators" })).toEqual([+ "view",+ "edit",+ "build",+ "admin",+ ]);+ });});// ---------------------------------------------------------------------------@@ -81,10 +115,11 @@ describe("applyTokenPermissions", () => {const server = createTestServer();-const createContext = (): AppContext =>+const createContext = (allowAdditionalPermissions = true): AppContext =>({...testContext,authorization: { type: "user", userId: "user-1" },+ planFeatures: { allowAdditionalPermissions },getOwnerPlanFeatures: () => Promise.resolve({}),}) as unknown as AppContext;@@ -105,6 +140,7 @@ const tokenRow = {canClone: false,canCopy: false,canPublish: true,+ canUseApi: false,createdAt: "2024-01-01T00:00:00.000Z",};@@ -155,37 +191,165 @@ describe("create (msw)", () => {...tokenRow,relation: "viewers" as const,token: "tok-new",+ canUseApi: true,};server.use(projectOwnershipHandler,- db.post("AuthorizationToken", () => json([newRow], { status: 201 }))+ db.post("AuthorizationToken", async ({ request }) => {+ await expect(request.json()).resolves.toMatchObject({+ canUseApi: true,+ });+ return json([newRow], { status: 201 });+ }));const result = await create(- { projectId: "proj-1", relation: "viewers", name: "Viewer Token" },+ {+ projectId: "proj-1",+ relation: "viewers",+ name: "Viewer Token",+ canUseApi: true,+ },createContext());expect(result[0].token).toBe("tok-new");+ expect(result[0].canUseApi).toBe(true);+ });++ test("rejects API capability when plan does not allow it", async () => {+ server.use(projectOwnershipHandler);++ const promise = create(+ {+ projectId: "proj-1",+ relation: "viewers",+ name: "Viewer Token",+ canUseApi: true,+ },+ createContext(false)+ );+ await expect(promise).rejects.toThrow(PlanRequiredError);+ await expect(promise).rejects.toMatchObject({ code: "PLAN_REQUIRED" });+ });++ test("maps API capability plan errors to forbidden tRPC errors", async () => {+ server.use(projectOwnershipHandler);++ const caller = authorizationTokenRouter.createCaller(createContext(false));++ await expect(+ caller.create({+ projectId: "proj-1",+ relation: "viewers",+ name: "Viewer Token",+ canUseApi: true,+ })+ ).rejects.toMatchObject({+ code: "FORBIDDEN",+ message: "API permission requires an upgrade.",+ });});});describe("update (msw)", () => {test("updates token relation and returns updated row", async () => {- const updatedRow = { ...tokenRow, relation: "editors" as const };+ const updatedRow = {+ ...tokenRow,+ relation: "editors" as const,+ canUseApi: true,+ };server.use(projectOwnershipHandler,// previous token fetchdb.get("AuthorizationToken", () => json(tokenRow)),// update- db.patch("AuthorizationToken", () => json(updatedRow))+ db.patch("AuthorizationToken", async ({ request }) => {+ await expect(request.json()).resolves.toMatchObject({+ canUseApi: true,+ });+ return json(updatedRow);+ }));const result = await update("proj-1",- { token: "tok-abc", relation: "editors" },+ { token: "tok-abc", relation: "editors", canUseApi: true },createContext());expect(result.relation).toBe("editors");+ expect(result.canUseApi).toBe(true);+ });++ test("rejects API capability update when plan does not allow it", async () => {+ server.use(+ projectOwnershipHandler,+ db.get("AuthorizationToken", () => json(tokenRow))+ );++ const promise = update(+ "proj-1",+ { token: "tok-abc", relation: "editors", canUseApi: true },+ createContext(false)+ );+ await expect(promise).rejects.toThrow(PlanRequiredError);+ await expect(promise).rejects.toMatchObject({ code: "PLAN_REQUIRED" });+ });++ test("maps API capability update plan errors to forbidden tRPC errors", async () => {+ server.use(+ projectOwnershipHandler,+ db.get("AuthorizationToken", () => json(tokenRow))+ );++ const caller = authorizationTokenRouter.createCaller(createContext(false));++ await expect(+ caller.update({+ projectId: "proj-1",+ token: "tok-abc",+ name: "My Token",+ relation: "editors",+ canClone: false,+ canCopy: true,+ canPublish: false,+ canUseApi: true,+ })+ ).rejects.toMatchObject({+ code: "FORBIDDEN",+ message: "API permission requires an upgrade.",+ });+ });++ test("allows preserving existing API capability when plan no longer allows it", async () => {+ const existingToken = { ...tokenRow, canUseApi: true };+ const updatedRow = {+ ...existingToken,+ name: "Renamed Token",+ };+ server.use(+ projectOwnershipHandler,+ db.get("AuthorizationToken", () => json(existingToken)),+ db.patch("AuthorizationToken", async ({ request }) => {+ await expect(request.json()).resolves.toMatchObject({+ name: "Renamed Token",+ canUseApi: true,+ });+ return json(updatedRow);+ })+ );++ const result = await update(+ "proj-1",+ {+ token: "tok-abc",+ name: "Renamed Token",+ relation: "builders",+ canUseApi: true,+ },+ createContext(false)+ );+ expect(result.name).toBe("Renamed Token");+ expect(result.canUseApi).toBe(true);});});diff --git a/packages/authorization-token/src/db/authorization-token.ts b/packages/authorization-token/src/db/authorization-token.tsindex 50f00f5e2b..c9c26d1dd5 100644--- a/packages/authorization-token/src/db/authorization-token.ts+++ b/packages/authorization-token/src/db/authorization-token.ts@@ -1,8 +1,10 @@import type { Database } from "@webstudio-is/postgrest/index.server";import {type AppContext,+ type AuthPermit,authorizeProject,AuthorizationError,+ PlanRequiredError,} from "@webstudio-is/trpc-interface/index.server";type AuthorizationToken =@@ -96,6 +98,32 @@ export const tokenDefaultPermissions = {export type TokenPermissions = typeof tokenDefaultPermissions;+export const tokenProjectPermits: Record<+ AuthorizationToken["relation"],+ AuthPermit[]+> = {+ viewers: ["view"],+ editors: ["view", "edit"],+ builders: ["view", "edit", "build"],+ administrators: ["view", "edit", "build", "admin"],+};++export const getTokenProjectPermits = (+ token: Pick<AuthorizationToken, "relation">+) => tokenProjectPermits[token.relation];++const assertCanEnableApi = (+ canUseApi: boolean | undefined,+ context: AppContext+) => {+ if (+ canUseApi === true &&+ context.planFeatures.allowAdditionalPermissions !== true+ ) {+ throw new PlanRequiredError("API permission requires an upgrade.");+ }+};+export const getTokenInfo = async (token: AuthorizationToken["token"],context: AppContext@@ -135,6 +163,7 @@ export const create = async (projectId: string;relation: AuthorizationToken["relation"];name: string;+ canUseApi?: boolean;},context: AppContext) => {@@ -151,6 +180,7 @@ export const create = async ("You don't have access to create this project authorization tokens");}+ assertCanEnableApi(props.canUseApi, context);const dbToken = await context.postgrest.client.from("AuthorizationToken")@@ -159,6 +189,7 @@ export const create = async (relation: props.relation,token: tokenId,name: props.name,+ canUseApi: props.canUseApi,}).select();if (dbToken.error) {@@ -198,6 +229,9 @@ export const update = async (if (previousToken.data === null) {throw new AuthorizationError("Authorization token not found");}+ if (previousToken.data.canUseApi !== true) {+ assertCanEnableApi(props.canUseApi, context);+ }const dbToken = await context.postgrest.client.from("AuthorizationToken")@@ -207,6 +241,7 @@ export const update = async (canClone: props.canClone,canCopy: props.canCopy,canPublish: props.canPublish,+ canUseApi: props.canUseApi,}).eq("projectId", projectId).eq("token", props.token)diff --git a/packages/authorization-token/src/trpc/authorization-tokens-router.ts b/packages/authorization-token/src/trpc/authorization-tokens-router.tsindex 86c86bc4fa..2ad9485f2b 100644--- a/packages/authorization-token/src/trpc/authorization-tokens-router.ts+++ b/packages/authorization-token/src/trpc/authorization-tokens-router.ts@@ -1,5 +1,10 @@import { z } from "zod";-import { router, procedure } from "@webstudio-is/trpc-interface/index.server";+import { TRPCError } from "@trpc/server";+import {+ PlanRequiredError,+ router,+ procedure,+} from "@webstudio-is/trpc-interface/index.server";import { db } from "../db";import type { IsEqual } from "type-fest";import type { Database } from "@webstudio-is/postgrest/index.server";@@ -18,6 +23,17 @@ const tokenProjectRelation = z.enum([type TokenRelation = z.infer<typeof tokenProjectRelation>;true satisfies IsEqual<TokenRelation, Relation>;+const toTrpcError = (error: unknown): never => {+ if (error instanceof PlanRequiredError) {+ throw new TRPCError({+ code: "FORBIDDEN",+ message: error.message,+ cause: error,+ });+ }+ throw error;+};+export const authorizationTokenRouter = router({findMany: procedure.input(@@ -26,7 +42,7 @@ export const authorizationTokenRouter = router({})).query(async ({ input, ctx }) => {- return await db.findMany({ projectId: input.projectId }, ctx);+ return await db.findMany(input, ctx);}),create: procedure.input(@@ -34,17 +50,15 @@ export const authorizationTokenRouter = router({projectId: z.string(),relation: tokenProjectRelation,name: z.string(),+ canUseApi: z.boolean().optional(),})).mutation(async ({ input, ctx }) => {- return await db.create(- {- projectId: input.projectId,- relation: input.relation,- name: input.name,- },- ctx- );+ try {+ return await db.create(input, ctx);+ } catch (error) {+ toTrpcError(error);+ }}),remove: procedure.input(@@ -54,10 +68,7 @@ export const authorizationTokenRouter = router({})).mutation(async ({ input, ctx }) => {- return await db.remove(- { projectId: input.projectId, token: input.token },- ctx- );+ return await db.remove(input, ctx);}),update: procedure.input(@@ -69,21 +80,16 @@ export const authorizationTokenRouter = router({canClone: z.boolean(),canCopy: z.boolean(),canPublish: z.boolean(),+ canUseApi: z.boolean().optional(),})).mutation(async ({ input, ctx }) => {- return await db.update(- input.projectId,- {- token: input.token,- name: input.name,- relation: input.relation,- canPublish: input.canPublish,- canClone: input.canClone,- canCopy: input.canCopy,- },- ctx- );+ const { projectId, ...token } = input;+ try {+ return await db.update(projectId, token, ctx);+ } catch (error) {+ toTrpcError(error);+ }}),});diff --git a/packages/cli/package.json b/packages/cli/package.jsonindex 25a885b2b4..1cbc56192c 100644--- a/packages/cli/package.json+++ b/packages/cli/package.json@@ -23,7 +23,8 @@],"scripts": {"typecheck": "tsgo --noEmit",- "build": "rm -rf lib && vite build",+ "generate-docs": "node scripts/generate-docs.mjs",+ "build": "pnpm generate-docs && rm -rf lib && vite build","test": "vitest run"},"license": "AGPL-3.0-or-later",@@ -34,13 +35,18 @@"@clack/prompts": "^0.10.0","@emotion/hash": "^0.9.2","@trpc/client": "^10.45.2",+ "@webstudio-is/http-client": "workspace:*",+ "@webstudio-is/project-build": "workspace:*","@webstudio-is/project-migrations": "workspace:*",- "@webstudio-is/trpc-interface": "workspace:*",+ "@webstudio-is/protocol": "workspace:*","acorn": "^8.14.1","acorn-walk": "^8.3.4","change-case": "^5.4.4",+ "chrome-launcher": "^1.2.1","deepmerge": "^4.3.1","env-paths": "^3.0.0",+ "fast-deep-equal": "^3.1.3",+ "immer": "^10.1.1","nanoid": "^5.1.5","p-limit": "^6.2.0","parse5": "7.3.0",@@ -69,9 +75,7 @@"@vercel/react-router": "^1.1.0","@vitejs/plugin-react": "^4.4.1","@webstudio-is/css-engine": "workspace:*",- "@webstudio-is/http-client": "workspace:*","@webstudio-is/image": "workspace:*",- "@webstudio-is/protocol": "workspace:*","@webstudio-is/react-sdk": "workspace:*","@webstudio-is/sdk": "workspace:*","@webstudio-is/sdk-components-animation": "workspace:*",diff --git a/packages/cli/scripts/generate-docs.mjs b/packages/cli/scripts/generate-docs.mjsnew file mode 100644index 0000000000..bf86ad7413--- /dev/null+++ b/packages/cli/scripts/generate-docs.mjs@@ -0,0 +1,32 @@+import { readdirSync, readFileSync, writeFileSync } from "node:fs";+import { basename, join } from "node:path";+import { format } from "prettier";++const docsDir = new URL("../src/docs", import.meta.url);+const outputFile = new URL("../src/docs.generated.ts", import.meta.url);++const docs = Object.fromEntries(+ readdirSync(docsDir)+ .filter((fileName) => fileName.endsWith(".md"))+ .sort()+ .map((fileName) => [+ basename(fileName, ".md"),+ readFileSync(join(docsDir.pathname, fileName), "utf8"),+ ])+);++const output = await format(+ [+ "// This file is generated by scripts/generate-docs.mjs.",+ "// Edit markdown files in src/docs instead.",+ `export const cliDocs = ${JSON.stringify(docs, null, 2)} as const;`,+ "",+ "export type CliDocName = keyof typeof cliDocs;",+ "",+ ].join("\n"),+ {+ filepath: outputFile.pathname,+ }+);++writeFileSync(outputFile, output, "utf8");diff --git a/packages/cli/src/api-connection.test.ts b/packages/cli/src/api-connection.test.tsnew file mode 100644index 0000000000..a34ad17aa0--- /dev/null+++ b/packages/cli/src/api-connection.test.ts@@ -0,0 +1,64 @@+import { describe, expect, test, vi } from "vitest";+import { GLOBAL_CONFIG_FILE, LOCAL_CONFIG_FILE } from "./config";+import { resolveApiConnection } from "./api-connection";++const createDependencies = ({+ exists = true,+ files = {},+}: {+ exists?: boolean;+ files?: Record<string, string>;+} = {}) => ({+ isFileExists: vi.fn(async (path: string) =>+ path === LOCAL_CONFIG_FILE ? exists : path in files+ ),+ readFile: vi.fn(async (path: string) => {+ const key = path.endsWith(LOCAL_CONFIG_FILE) ? LOCAL_CONFIG_FILE : path;+ const content = files[key];+ if (content === undefined) {+ throw new Error(`Missing test file ${path}`);+ }+ return content;+ }),+});++describe("resolveApiConnection", () => {+ test("reads the configured project connection", async () => {+ const dependencies = createDependencies({+ files: {+ [LOCAL_CONFIG_FILE]: JSON.stringify({ projectId: "project-1" }),+ [GLOBAL_CONFIG_FILE]: JSON.stringify({+ "project-1": {+ origin: "https://example.com",+ token: "token-1",+ },+ }),+ },+ });++ await expect(resolveApiConnection(dependencies)).resolves.toEqual({+ projectId: "project-1",+ origin: "https://example.com",+ authToken: "token-1",+ });+ });++ test("requires a local project config", async () => {+ await expect(+ resolveApiConnection(createDependencies({ exists: false }))+ ).rejects.toThrow("Local config file is not found");+ });++ test("requires a matching global project config", async () => {+ const dependencies = createDependencies({+ files: {+ [LOCAL_CONFIG_FILE]: JSON.stringify({ projectId: "project-1" }),+ [GLOBAL_CONFIG_FILE]: JSON.stringify({}),+ },+ });++ await expect(resolveApiConnection(dependencies)).rejects.toThrow(+ "Project config is not found"+ );+ });+});diff --git a/packages/cli/src/api-connection.ts b/packages/cli/src/api-connection.tsnew file mode 100644index 0000000000..2b40e1fd56--- /dev/null+++ b/packages/cli/src/api-connection.ts@@ -0,0 +1,58 @@+import { readFile } from "node:fs/promises";+import { cwd } from "node:process";+import { join } from "node:path";+import {+ GLOBAL_CONFIG_FILE,+ LOCAL_CONFIG_FILE,+ jsonToGlobalConfig,+ jsonToLocalConfig,+} from "./config";+import { isFileExists } from "./fs-utils";++export type ApiConnection = {+ origin: string;+ authToken: string;+ projectId: string;+ headers?: Record<string, string | undefined>;+};++export type ApiConnectionDependencies = {+ isFileExists: typeof isFileExists;+ readFile: (path: string, encoding: "utf-8") => Promise<string>;+};++export const defaultApiConnectionDependencies: ApiConnectionDependencies = {+ isFileExists,+ readFile,+};++export const resolveApiConnection = async (+ dependencies = defaultApiConnectionDependencies+): Promise<ApiConnection> => {+ if ((await dependencies.isFileExists(LOCAL_CONFIG_FILE)) === false) {+ throw new Error(+ "Local config file is not found. Run webstudio init --link <api-share-link> from a Webstudio project."+ );+ }++ const localConfig = jsonToLocalConfig(+ JSON.parse(+ await dependencies.readFile(join(cwd(), LOCAL_CONFIG_FILE), "utf-8")+ )+ );+ const globalConfig = jsonToGlobalConfig(+ JSON.parse(await dependencies.readFile(GLOBAL_CONFIG_FILE, "utf-8"))+ );+ const projectConfig = globalConfig[localConfig.projectId];+ if (projectConfig === undefined) {+ throw new Error(+ "Project config is not found. Run webstudio init --link <api-share-link>."+ );+ }++ return {+ origin: projectConfig.origin,+ authToken: projectConfig.token,+ projectId: localConfig.projectId,+ };+};diff --git a/packages/cli/src/asset-files.test.ts b/packages/cli/src/asset-files.test.tsindex 1888d98960..1e3d6871bf 100644--- a/packages/cli/src/asset-files.test.ts+++ b/packages/cli/src/asset-files.test.ts@@ -10,11 +10,7 @@ import {import { join } from "node:path";import { tmpdir } from "node:os";import type { Asset } from "@webstudio-is/sdk";-import {- getLocalAssetPath,- materializeAssetFile,- uploadAssetFiles,-} from "./asset-files";+import { getLocalAssetPath, materializeAssetFile } from "./asset-files";const originalCwd = process.cwd();let tempDir: string;@@ -30,12 +26,6 @@ const asset = {meta: { width: 1, height: 1 },} satisfies Asset;-const otherAsset = {- ...asset,- id: "asset-2",- name: "other.png",-} satisfies Asset;-beforeEach(async () => {tempDir = await mkdtemp(join(tmpdir(), "webstudio-assets-"));process.chdir(tempDir);@@ -132,102 +122,3 @@ test("fails clearly when asset download response has no body", async () => {await expect(access("public/assets/image.png")).rejects.toThrow();await expect(access("public/assets/image.png.tmp")).rejects.toThrow();});--test("uploads assets as binary requests", async () => {- await mkdir(".webstudio/assets", { recursive: true });- await writeFile(".webstudio/assets/image.png", "synced", "utf8");- const fetch = vi.fn(- async () =>- new Response(JSON.stringify({ ok: true }), {- headers: { "content-type": "application/json" },- })- );- globalThis.fetch = fetch;-- await uploadAssetFiles({- assets: [asset],- authToken: "token",- origin: "https://apps.webstudio.is",- projectId: "project-1",- });-- expect(fetch).toHaveBeenCalledOnce();- const [, init] = fetch.mock.calls[0] as unknown as [URL, RequestInit];- expect(init.body).toBeInstanceOf(Blob);- await expect((init.body as Blob).text()).resolves.toBe("synced");-});--test("retries failed asset uploads once", async () => {- await mkdir(".webstudio/assets", { recursive: true });- await writeFile(".webstudio/assets/image.png", "synced", "utf8");- const fetch = vi- .fn()- .mockResolvedValueOnce(- new Response(JSON.stringify({ errors: "Temporary failure" }), {- headers: { "content-type": "application/json" },- })- )- .mockResolvedValueOnce(- new Response(JSON.stringify({ ok: true }), {- headers: { "content-type": "application/json" },- })- );- globalThis.fetch = fetch;-- await uploadAssetFiles({- assets: [asset],- authToken: "token",- origin: "https://apps.webstudio.is",- projectId: "project-1",- });-- expect(fetch).toHaveBeenCalledTimes(2);-});--test("reports all asset uploads that fail after retry", async () => {- await mkdir(".webstudio/assets", { recursive: true });- await writeFile(".webstudio/assets/image.png", "synced", "utf8");- await writeFile(".webstudio/assets/other.png", "other", "utf8");- const fetch = vi.fn(- async () =>- new Response(JSON.stringify({ errors: "Upload failed" }), {- headers: { "content-type": "application/json" },- })- );- globalThis.fetch = fetch;-- let message = "";- try {- await uploadAssetFiles({- assets: [asset, otherAsset],- authToken: "token",- origin: "https://apps.webstudio.is",- projectId: "project-1",- });- } catch (error) {- message = error instanceof Error ? error.message : String(error);- }-- expect(message).toContain("Failed to upload assets:");- expect(message).toContain("image.png: Upload failed");- expect(message).toContain("other.png: Upload failed");- expect(fetch).toHaveBeenCalledTimes(4);-});--test("reports missing local asset files with upload failures", async () => {- let message = "";- try {- await uploadAssetFiles({- assets: [asset],- authToken: "token",- origin: "https://apps.webstudio.is",- projectId: "project-1",- });- } catch (error) {- message = error instanceof Error ? error.message : String(error);- }-- expect(message).toContain("Failed to upload assets:");- expect(message).toContain("image.png:");- expect(message).toContain("no such file or directory");-});diff --git a/packages/cli/src/asset-files.ts b/packages/cli/src/asset-files.tsindex 8b9e2ab07f..8cd90c46be 100644--- a/packages/cli/src/asset-files.ts+++ b/packages/cli/src/asset-files.ts@@ -1,11 +1,10 @@import { constants, createWriteStream } from "node:fs";-import { copyFile, readFile, rename, rm } from "node:fs/promises";+import { copyFile, rename, rm } from "node:fs/promises";import { dirname, resolve, sep } from "node:path";import { pipeline } from "node:stream/promises";import pLimit from "p-limit";import { getAssetUrl, type Asset } from "@webstudio-is/sdk";import { createFolderIfNotExists, isFileExists } from "./fs-utils";-import { uploadAsset } from "@webstudio-is/http-client";import { isAssetFileName } from "@webstudio-is/protocol";export const LOCAL_ASSETS_DIR = ".webstudio/assets";@@ -40,17 +39,6 @@ const runAssetTasks = async ({);};-const formatError = (error: unknown) =>- error instanceof Error ? error.message : String(error);--const retryOnce = async (task: () => Promise<void>) => {- try {- await task();- } catch {- await task();- }-};-export const getLocalAssetPath = (assetName: string,assetsDirectory = LOCAL_ASSETS_DIR@@ -193,57 +181,3 @@ export const materializeAssetFiles = async ({}),});};--export const uploadAssetFiles = async ({- assets,- assetsDirectory = LOCAL_ASSETS_DIR,- authToken,- headers,- origin,- projectId,-}: {- assets: Asset[];- assetsDirectory?: string;- authToken: string;- headers?: Record<string, string | undefined>;- origin: string;- projectId: string;-}): Promise<void> => {- const failedUploads: { asset: Asset; error: unknown }[] = [];-- await runAssetTasks({- assets,- operation: "uploading",- task: async (asset) => {- try {- const file = await readFile(- getLocalAssetPath(asset.name, assetsDirectory)- );- const upload = async () => {- await uploadAsset({- authToken,- headers,- origin,- projectId,- upload: {- asset,- data: new Blob([new Uint8Array(file)]),- },- });- };-- await retryOnce(upload);- } catch (error) {- failedUploads.push({ asset, error });- }- },- });-- if (failedUploads.length > 0) {- throw new Error(- `Failed to upload assets: ${failedUploads- .map(({ asset, error }) => `${asset.name}: ${formatError(error)}`)- .join("; ")}`- );- }-};diff --git a/packages/cli/src/cli.test.ts b/packages/cli/src/cli.test.tsnew file mode 100644index 0000000000..a9109ba9b7--- /dev/null+++ b/packages/cli/src/cli.test.ts@@ -0,0 +1,159 @@+import { describe, expect, test, vi } from "vitest";+import makeCLI from "yargs";+import {+ apiCommandMetadata,+ cliCommandMetadata,+} from "./commands/api-command-metadata";+import { registerCommands } from "./cli";+import type { CommonYargsArgv } from "./commands/yargs-types";++type CommandBuilder = (yargs: CommonYargsArgv) => CommonYargsArgv;++const createYargs = () => {+ const commands: { command: string; builder?: CommandBuilder }[] = [];+ const yargs = {+ command: vi.fn(+ (+ command: string | string[],+ _description?: string,+ builder?: unknown+ ) => {+ commands.push({+ command: Array.isArray(command) ? (command[0] ?? "") : command,+ builder:+ typeof builder === "function"+ ? (builder as CommandBuilder)+ : undefined,+ });+ return yargs;+ }+ ),+ demandCommand: vi.fn(() => yargs),+ option: vi.fn(() => yargs),+ example: vi.fn(() => yargs),+ version: vi.fn(() => yargs),+ };+ return { yargs: yargs as unknown as CommonYargsArgv, commands };+};++const runGroupBuilder = (+ commands: { command: string; builder?: CommandBuilder }[],+ group: string+) => {+ const groupCommand = commands.find((command) => command.command === group);+ expect(groupCommand?.builder).toBeDefined();+ const childCommands: string[] = [];+ const childYargs = {+ command: vi.fn((command: string | string[]) => {+ childCommands.push(Array.isArray(command) ? (command[0] ?? "") : command);+ return childYargs;+ }),+ demandCommand: vi.fn(() => childYargs),+ option: vi.fn(() => childYargs),+ example: vi.fn(() => childYargs),+ version: vi.fn(() => childYargs),+ };++ groupCommand?.builder?.(childYargs as unknown as CommonYargsArgv);++ return {+ childCommands,+ demandCommand: childYargs.demandCommand,+ };+};++const commandNames = (commands: { command: string }[]) =>+ commands.map((command) => command.command);++const getHelpOutput = async (args: string[]) => {+ let output = "";+ const yargs = makeCLI(args)+ .scriptName("webstudio")+ .exitProcess(false)+ .wrap(null)+ .fail((message, error) => {+ throw error ?? new Error(message);+ });++ registerCommands(yargs as unknown as CommonYargsArgv);+ await yargs.parseAsync(args, {}, (_error, _argv, helpOutput) => {+ output = helpOutput;+ });+ return output;+};++describe("registerCommands", () => {+ test("registers high-level API commands and mcp command", () => {+ const { yargs, commands } = createYargs();++ registerCommands(yargs);++ expect(commandNames(commands)).toEqual(+ expect.arrayContaining([+ "preview",+ "screenshot <url>",+ "permissions",+ "publish",+ "domains",+ "mcp",+ "$0",+ ])+ );+ expect(commandNames(commands)).not.toEqual(+ expect.arrayContaining(["publish deploy", "domains list"])+ );++ const publish = runGroupBuilder(commands, "publish");+ expect(publish.childCommands).toEqual([+ "deploy",+ "list",+ "status",+ "unpublish",+ ]);+ expect(publish.demandCommand).toHaveBeenCalledWith(+ 1,+ "Specify a publish command."+ );++ const domains = runGroupBuilder(commands, "domains");+ expect(domains.childCommands).toEqual([+ "list",+ "create",+ "update",+ "delete",+ "verify",+ ]);+ expect(domains.demandCommand).toHaveBeenCalledWith(+ 1,+ "Specify a domains command."+ );++ for (const { command } of apiCommandMetadata) {+ if (+ cliCommandMetadata.some(+ (cliCommand) => cliCommand.operation === command+ )+ ) {+ continue;+ }+ expect(commandNames(commands)).not.toContain(command);+ }+ });++ test("keeps grouped subcommands out of top-level help", async () => {+ const rootHelp = await getHelpOutput(["--help"]);++ expect(rootHelp).toContain("webstudio publish");+ expect(rootHelp).toContain("webstudio domains");+ expect(rootHelp).not.toContain("webstudio publish deploy");+ expect(rootHelp).not.toContain("webstudio domains list");++ const publishHelp = await getHelpOutput(["publish", "--help"]);+ expect(publishHelp).toContain("webstudio publish deploy");+ expect(publishHelp).toContain("webstudio publish list");++ const domainsHelp = await getHelpOutput(["domains", "--help"]);+ expect(domainsHelp).toContain("webstudio domains list");+ expect(domainsHelp).toContain("webstudio domains create");+ });+});diff --git a/packages/cli/src/cli.ts b/packages/cli/src/cli.tsindex 5ce8bbee1e..bc1c745413 100644--- a/packages/cli/src/cli.ts+++ b/packages/cli/src/cli.ts@@ -4,14 +4,133 @@ import { GLOBAL_CONFIG_FILE } from "./config";import { createFileIfNotExists } from "./fs-utils";import { link, linkOptions } from "./commands/link";import { sync, syncOptions } from "./commands/sync";-import { importOptions, importProject } from "./commands/import";import { build, buildOptions } from "./commands/build";-import { initFlow } from "./commands/init-flow";+import { man, manOptions } from "./commands/man";+import { mcp, mcpOptions } from "./commands/mcp";+import { screenshot, screenshotOptions } from "./commands/screenshot";+import { preview, previewOptions } from "./commands/preview";+import { apiCommand } from "./commands/api-command";+import {+ cliCommandGroupMetadata,+ cliCommandMetadata,+ getApiCommandOptions,+ type CliCommandMetadata,+} from "./commands/api-command-metadata";+import { schema, schemaOptions } from "./commands/schema";+import { initFlow, initOptions } from "./commands/init-flow";import makeCLI from "yargs";import packageJson from "../package.json" assert { type: "json" };import type { CommonYargsArgv } from "./commands/yargs-types";import { isHandledCliError } from "./errors";+const cliCommandGroupDescriptions = new Map<string, string>(+ cliCommandGroupMetadata.map(({ command, description }) => [+ command,+ description,+ ])+);++const getGroupedCommands = (metadata: readonly CliCommandMetadata[]) => {+ const grouped = new Map<string, CliCommandMetadata[]>();+ const direct: CliCommandMetadata[] = [];++ for (const command of metadata) {+ const [group, action, extra] = command.cliCommand.split(" ");+ if (action === undefined || extra !== undefined) {+ direct.push(command);+ continue;+ }+ const commands = grouped.get(group) ?? [];+ commands.push(command);+ grouped.set(group, commands);+ }++ return { direct, grouped };+};++const registerApiCommand = (+ cmd: CommonYargsArgv,+ cliCommand: string,+ metadata: CliCommandMetadata+) => {+ cmd.command(+ [cliCommand],+ metadata.description,+ getApiCommandOptions(metadata),+ (options) => apiCommand({ ...options, command: metadata.operation })+ );+};++export const registerCommands = (cmd: CommonYargsArgv) => {+ cmd.command(+ ["build"],+ "Build the project",+ (yargs: CommonYargsArgv) => {+ return buildOptions(yargs).demandOption(+ "template",+ "Please specify a template to use for the build"+ );+ },+ build+ );+ cmd.command(["link"], "Link the project with the cloud", linkOptions, link);+ cmd.command(["sync"], "Sync your project", syncOptions, sync);+ cmd.command(+ ["preview"],+ "Run the generated project dev server for visual verification",+ (yargs: CommonYargsArgv) => {+ return previewOptions(yargs).demandOption(+ "template",+ "Please specify a template to use for the preview"+ );+ },+ preview+ );+ cmd.command(+ ["screenshot <url>"],+ "Capture a PNG screenshot of a URL with an installed Chromium-family browser",+ screenshotOptions,+ screenshot+ );+ const { direct, grouped } = getGroupedCommands(cliCommandMetadata);+ for (const metadata of direct) {+ registerApiCommand(cmd, metadata.cliCommand, metadata);+ }+ for (const [group, commands] of grouped) {+ cmd.command(+ [group],+ cliCommandGroupDescriptions.get(group) ?? `Run ${group} commands`,+ (yargs: CommonYargsArgv) => {+ for (const metadata of commands) {+ const action = metadata.cliCommand.slice(group.length + 1);+ registerApiCommand(yargs, action, metadata);+ }+ return yargs.demandCommand(1, `Specify a ${group} command.`);+ },+ () => undefined+ );+ }+ cmd.command(+ ["schema [topic]"],+ "Print machine-readable command and patch schemas",+ schemaOptions,+ schema+ );+ cmd.command(+ ["man [topic]"],+ "Print long-form manuals with workflows and examples",+ manOptions,+ man+ );+ cmd.command(+ ["mcp"],+ "Run an MCP server over stdio for the configured project",+ mcpOptions,+ mcp+ );+ cmd.command(["$0", "init"], "Setup the project", initOptions, initFlow);+};+export const main = async () => {try {await createFileIfNotExists(GLOBAL_CONFIG_FILE, "{}");@@ -41,31 +160,11 @@ export const main = async () => {}).scriptName("webstudio").usage(- `Webstudio CLI (${packageJson.version}) allows you to setup, sync, build and preview your project.`+ `Webstudio CLI (${packageJson.version}) sets up, syncs, builds, publishes, and exposes MCP automation for the configured project.`);cmd.version(packageJson.version).alias("v", "version");-- cmd.command(- ["build"],- "Build the project",- (yargs: CommonYargsArgv) => {- return buildOptions(yargs).demandOption(- "template",- "Please specify a template to use for the build"- );- },- build- );- cmd.command(["link"], "Link the project with the cloud", linkOptions, link);- cmd.command(["sync"], "Sync your project", syncOptions, sync);- cmd.command(- ["import"],- "Import project bundle into another project",- importOptions,- importProject- );- cmd.command(["$0", "init"], "Setup the project", buildOptions, initFlow);+ registerCommands(cmd);await cmd.parse();} catch (error) {diff --git a/packages/cli/src/commands/api-command-docs.test.ts b/packages/cli/src/commands/api-command-docs.test.tsnew file mode 100644index 0000000000..52a42e2310--- /dev/null+++ b/packages/cli/src/commands/api-command-docs.test.ts@@ -0,0 +1,158 @@+import { expect, test } from "vitest";+import { createProjectSessionMcpCore } from "@webstudio-is/project-build/mcp";+import { publicApiOperations } from "@webstudio-is/protocol";+import {+ apiCommandMetadata,+ highLevelCliCommands,+ topLevelCliCommandMetadata,+} from "./api-command-metadata";+import { useCaseScenarios } from "./api-command-docs";+import { readCliDoc } from "../docs";++const removedShellCommands = [+ "whoami",+ "inspect",+ "snapshot",+ "apply-patch",+ "list-pages",+ "get-page",+ "get-page-by-path",+ "create-page",+ "update-page",+ "delete-page",+ "list-assets",+ "upload-asset",+ "replace-asset",+ "delete-asset",+ "list-domains",+ "create-domain",+] as const;++const getDocumentedCommands = () => {+ const knownCliCommands = [+ ...highLevelCliCommands.map(({ command }) => command),+ ...topLevelCliCommandMetadata.map(({ command }) => command),+ ].sort((left, right) => right.length - left.length);+ return new Set(+ useCaseScenarios+ .flatMap(({ commands }) => commands)+ .flatMap((command) => {+ const mcpMatch = command.match(/^MCP tool: ([a-z0-9._-]+)/);+ if (mcpMatch !== null) {+ return [mcpMatch[1]];+ }+ if (command.startsWith("webstudio ") === false) {+ return [];+ }+ const withoutBinary = command.slice("webstudio ".length);+ const cliCommand = knownCliCommands.find(+ (knownCommand) =>+ withoutBinary === knownCommand ||+ withoutBinary.startsWith(`${knownCommand} `)+ );+ return cliCommand === undefined ? [] : [cliCommand];+ })+ );+};++test("documents executable use-case scenarios with current CLI or MCP commands", () => {+ expect(useCaseScenarios.length).toBeGreaterThan(0);++ const names = useCaseScenarios.map(({ useCase }) => useCase);+ expect(new Set(names).size).toBe(names.length);+ for (const scenario of useCaseScenarios) {+ expect(scenario.useCase).not.toBe("");+ expect(scenario.commands.length).toBeGreaterThan(0);+ for (const command of scenario.commands) {+ expect(command).toMatch(/^(webstudio |MCP tool: )/);+ for (const removedCommand of removedShellCommands) {+ expect(command).not.toMatch(+ new RegExp(`^webstudio ${removedCommand}(?:\\\\s|$)`)+ );+ }+ }+ }+});++test("documents every public API operation in use-case scenarios", () => {+ const documentedCommands = getDocumentedCommands();+ const cliCommandByOperation = new Map<string, string>(+ highLevelCliCommands.map(({ command, operation }) => [operation, command])+ );++ for (const { command } of apiCommandMetadata) {+ expect(documentedCommands).toContain(+ cliCommandByOperation.get(command) ?? command+ );+ }+});++test("documents every MCP session and vision tool in use-case scenarios", () => {+ const documentedTools = getDocumentedCommands();++ expect(Array.from(documentedTools)).toEqual(+ expect.arrayContaining([+ "meta.index",+ "meta.guide",+ "meta.get_more_tools",+ "status",+ "refresh",+ "reset-session",+ "preview.start",+ "preview.status",+ "screenshot",+ "screenshot.diff",+ "vision.install-ocr",+ ])+ );+});++test("documents MCP use cases with JSON inputs instead of CLI flags", () => {+ const apiUseCases = readCliDoc("api-use-cases");+ expect(apiUseCases).not.toMatch(/^- MCP tool: .*(?:\(--| --[a-z])/m);+ expect(apiUseCases).not.toMatch(/^- MCP tool: .*\(\{/m);++ for (const line of apiUseCases.match(/^- MCP tool: .+$/gm) ?? []) {+ const match = line.match(/^- MCP tool: [a-z0-9._-]+ (.+)$/);+ expect(match, line).not.toBeNull();+ expect(() => JSON.parse(match?.[1] ?? "")).not.toThrow();+ }+});++test("MCP capability index covers every public API operation", async () => {+ const adapter = createProjectSessionMcpCore({+ operations: publicApiOperations,+ createProjectSession: () => {+ throw new Error("meta.index must not initialize a ProjectSession.");+ },+ executeOperation: async () => {+ throw new Error("meta.index must not execute operations.");+ },+ });+ const index = await adapter.callTool({ name: "meta.index" });+ const capabilities = (+ index.structuredContent.data as {+ capabilities: { tools: string[] }[];+ }+ ).capabilities;+ const indexedTools = new Set(+ capabilities.flatMap((capability) => capability.tools)+ );++ for (const { command } of apiCommandMetadata) {+ expect(indexedTools).toContain(command);+ }+});++test("documents that MCP visual verification requires current generated files", () => {+ expect(+ useCaseScenarios.find(+ (scenario) =>+ scenario.useCase === "Visually verify rendered work with AI vision"+ )?.notes+ ).toEqual(+ expect.arrayContaining([+ expect.stringContaining("generated project files are current"),+ ])+ );+});diff --git a/packages/cli/src/commands/api-command-docs.ts b/packages/cli/src/commands/api-command-docs.tsnew file mode 100644index 0000000000..ebd8c641ed--- /dev/null+++ b/packages/cli/src/commands/api-command-docs.ts@@ -0,0 +1,95 @@+import { readCliDoc } from "../docs";++const apiUseCasesMarkdown = readCliDoc("api-use-cases");++type UseCaseScenario = {+ useCase: string;+ commands: string[];+ notes?: string[];+ patchNamespaces?: string[];+};++type KnownCliGap = {+ capability: string;+ missing: string;+ currentFallback: string;+ suggestedCommands: string[];+};++const getHeadingBlocks = (markdown: string) => {+ const matches = [...markdown.matchAll(/^## (.+)$/gm)];+ return matches.map((match, index) => {+ const start = (match.index ?? 0) + match[0].length;+ const end = matches[index + 1]?.index ?? markdown.length;+ return {+ title: match[1],+ body: markdown.slice(start, end).trim(),+ };+ });+};++const getSectionList = (body: string, label: string) => {+ const lines = body.split(/\r?\n/);+ const labelIndex = lines.findIndex((line) => line === `${label}:`);+ if (labelIndex === -1) {+ return undefined;+ }+ const values: string[] = [];+ for (const line of lines.slice(labelIndex + 1)) {+ if (line.startsWith("- ")) {+ const value = line.slice(2).trim();+ if (value !== "none") {+ values.push(value);+ }+ continue;+ }+ if (line.trim() !== "") {+ break;+ }+ if (values.length > 0) {+ break;+ }+ }+ return values;+};++const getSectionParagraph = (body: string, label: string) => {+ const lines = body.split(/\r?\n/);+ const labelIndex = lines.findIndex((line) => line === `${label}:`);+ if (labelIndex === -1) {+ return "";+ }+ return (+ lines+ .slice(labelIndex + 1)+ .map((line) => line.trim())+ .filter(Boolean)+ .at(0) ?? ""+ );+};++const [useCasesMarkdown, knownGapsMarkdown = ""] = apiUseCasesMarkdown.split(+ "\n# Known CLI Gaps\n"+);++export const useCaseScenarios = getHeadingBlocks(useCasesMarkdown).map(+ ({ title, body }) => {+ const notes = getSectionList(body, "Notes");+ const patchNamespaces = getSectionList(body, "Patch namespaces");+ return {+ useCase: title,+ commands: getSectionList(body, "Commands") ?? [],+ ...(notes === undefined ? {} : { notes }),+ ...(patchNamespaces === undefined ? {} : { patchNamespaces }),+ };+ }+) satisfies UseCaseScenario[];++export const knownCliGaps = getHeadingBlocks(knownGapsMarkdown).map(+ ({ title, body }) => ({+ capability: title,+ missing: getSectionParagraph(body, "Missing"),+ currentFallback: getSectionParagraph(body, "Current fallback"),+ suggestedCommands: getSectionList(body, "Suggested commands") ?? [],+ })+) satisfies KnownCliGap[];diff --git a/packages/cli/src/commands/api-command-metadata.test.ts b/packages/cli/src/commands/api-command-metadata.test.tsnew file mode 100644index 0000000000..6810f0f406--- /dev/null+++ b/packages/cli/src/commands/api-command-metadata.test.ts@@ -0,0 +1,174 @@+import { expect, test, vi } from "vitest";+import {+ apiCommandMetadata,+ cliApiCommandMetadata,+ cliCommandGroupMetadata,+ cliCommandMetadata,+ formatApiUseCaseCommand,+ getApiCommandOptions,+ highLevelApiCommands,+ mcpOnlyApiCommandMetadata,+ topLevelCliCommandMetadata,+} from "./api-command-metadata";++test("exposes command metadata", () => {+ expect(apiCommandMetadata.length).toBeGreaterThan(0);+});++test("exposes only high-level API metadata for top-level CLI registration", () => {+ expect(cliApiCommandMetadata.map((metadata) => metadata.command)).toEqual(+ highLevelApiCommands+ );+ expect(cliCommandMetadata.map((metadata) => metadata.cliCommand)).toEqual([+ "permissions",+ "publish deploy",+ "publish list",+ "publish status",+ "publish unpublish",+ "domains list",+ "domains create",+ "domains update",+ "domains delete",+ "domains verify",+ ]);+ const mcpOnlyCommands = mcpOnlyApiCommandMetadata.map(+ ({ command }) => command+ );+ for (const command of highLevelApiCommands) {+ expect(mcpOnlyCommands).not.toContain(command);+ }+});++test("describes every grouped CLI command", () => {+ const describedGroups = new Set(+ cliCommandGroupMetadata.map(({ command }) => command)+ );+ const groupedCommands = cliCommandMetadata+ .map(({ cliCommand }) => cliCommand.split(" "))+ .filter(([, action, extra]) => action !== undefined && extra === undefined)+ .map(([group]) => group);++ for (const group of groupedCommands) {+ expect(describedGroups).toContain(group);+ }+});++test("describes root CLI commands once for help-oriented docs", () => {+ expect(topLevelCliCommandMetadata.map(({ command }) => command)).toEqual([+ "init",+ "link",+ "sync",+ "build",+ "preview",+ "screenshot",+ "permissions",+ "publish",+ "domains",+ "schema",+ "man",+ "mcp",+ ]);+ expect(topLevelCliCommandMetadata.map(({ command }) => command)).not.toEqual(+ expect.arrayContaining(["publish deploy", "domains list"])+ );+ for (const metadata of topLevelCliCommandMetadata) {+ expect(metadata.description.length).toBeGreaterThan(0);+ expect(metadata.examples.length).toBeGreaterThan(0);+ }+});++test("formats removed shell commands as MCP tools", () => {+ expect(+ formatApiUseCaseCommand("webstudio init --link <api-share-link> --json")+ ).toBe("webstudio init --link <api-share-link> --json");+ expect(formatApiUseCaseCommand("webstudio build --template ssg")).toBe(+ "webstudio build --template ssg"+ );+ expect(formatApiUseCaseCommand("webstudio permissions --json")).toBe(+ "webstudio permissions --json"+ );+ expect(formatApiUseCaseCommand("webstudio list-domains --json")).toBe(+ "webstudio domains list --json"+ );+ expect(+ formatApiUseCaseCommand("webstudio publish --target production --json")+ ).toBe("webstudio publish deploy --target production --json");+ expect(formatApiUseCaseCommand("webstudio publish --help")).toBe(+ "webstudio publish --help"+ );+ expect(+ formatApiUseCaseCommand(+ "webstudio publish deploy --target production --json"+ )+ ).toBe("webstudio publish deploy --target production --json");+ expect(formatApiUseCaseCommand("webstudio list-pages --json")).toBe(+ "MCP tool: list-pages {}"+ );+});++test("returns command-specific options when available", () => {+ const yargs = { option: vi.fn().mockReturnThis() };+ const metadata = apiCommandMetadata.find(+ (item) => item.command === "create-page"+ );++ expect(metadata).toBeDefined();+ getApiCommandOptions(metadata!)(yargs as never);++ expect(yargs.option).toHaveBeenCalledWith(+ "name",+ expect.objectContaining({ type: "string" })+ );+});++test("parses redirect status as a string option", () => {+ const yargs = { option: vi.fn().mockReturnThis() };+ const metadata = apiCommandMetadata.find(+ (item) => item.command === "create-redirect"+ );++ expect(metadata).toBeDefined();+ getApiCommandOptions(metadata!)(yargs as never);++ expect(yargs.option).toHaveBeenCalledWith(+ "status",+ expect.objectContaining({ type: "string", choices: ["301", "302"] })+ );+});++test("describes list-folders include-pages response shape", () => {+ const yargs = { option: vi.fn().mockReturnThis() };+ const metadata = apiCommandMetadata.find(+ (item) => item.command === "list-folders"+ );++ expect(metadata).toBeDefined();+ getApiCommandOptions(metadata!)(yargs as never);++ expect(yargs.option).toHaveBeenCalledWith(+ "include-pages",+ expect.objectContaining({+ describe: "Include a top-level pages array with page summaries",+ })+ );+});++test("registers every catalog required option", () => {+ for (const metadata of apiCommandMetadata) {+ const registeredOptions = new Set<string>();+ const yargs = {+ option: vi.fn((name: string) => {+ registeredOptions.add(name);+ return yargs;+ }),+ example: vi.fn(() => yargs),+ version: vi.fn(() => yargs),+ };++ getApiCommandOptions(metadata)(yargs as never);++ for (const option of metadata.requiredOptions ?? ["json"]) {+ expect(registeredOptions, metadata.command).toContain(option);+ }+ }+});diff --git a/packages/cli/src/commands/api-command-metadata.ts b/packages/cli/src/commands/api-command-metadata.tsnew file mode 100644index 0000000000..2e59d3c4fc--- /dev/null+++ b/packages/cli/src/commands/api-command-metadata.ts@@ -0,0 +1,279 @@+import {+ publicApiOperations,+ type PublicApiOperationMethod,+ type PublicApiOperationPermit,+} from "@webstudio-is/protocol";+import type { CommonYargsArgv } from "./yargs-types";+import * as apiCommand from "./api-command";+import type { ApiCommandName } from "./api-command";++type ApiCommandOptions = (yargs: CommonYargsArgv) => CommonYargsArgv;++type ApiCommandMetadata = {+ command: ApiCommandName;+ description: string;+ method: PublicApiOperationMethod;+ permit: PublicApiOperationPermit;+ requiredOptions?: readonly string[];+ examples: readonly string[];+};++export type CliCommandMetadata = ApiCommandMetadata & {+ cliCommand: string;+ operation: ApiCommandName;+};++export const cliCommandGroupMetadata = [+ {+ command: "publish",+ description: "Publish, unpublish, and inspect publish jobs",+ examples: ["webstudio publish --help"],+ },+ {+ command: "domains",+ description: "List and manage custom domains",+ examples: ["webstudio domains --help"],+ },+] as const;++export const topLevelCliCommandMetadata = [+ {+ command: "init",+ description:+ "Create/link a Webstudio project; with --link, stores the configured project id, origin, and token",+ examples: ["webstudio init --link <api-share-link> --json"],+ },+ {+ command: "link",+ description: "Link the current directory to one Builder share link",+ examples: ["webstudio link --link <api-share-link>"],+ },+ {+ command: "sync",+ description:+ "Download the configured project bundle and asset files into .webstudio",+ examples: ["webstudio sync"],+ },+ {+ command: "build",+ description: "Build the synced project with the selected template",+ examples: ["webstudio build --template ssg"],+ },+ {+ command: "preview",+ description:+ "Regenerate project files and run the generated project dev server for visual verification; dependencies must already be installed",+ examples: ["webstudio preview --template ssg --port 5173"],+ },+ {+ command: "screenshot",+ description:+ "Capture a PNG screenshot of a URL with an installed Chromium-family browser",+ examples: [+ 'webstudio screenshot "https://example.com" --output current.png --width 1440 --height 900',+ ],+ },+ {+ command: "permissions",+ description:+ "Show API, role, publish, and domain capabilities for the configured share-link token",+ examples: ["webstudio permissions --json"],+ },+ ...cliCommandGroupMetadata,+ {+ command: "schema",+ description: "Print machine-readable API command and patch schemas",+ examples: ["webstudio schema api --json"],+ },+ {+ command: "man",+ description: "Print human and LLM manuals for CLI/API/MCP workflows",+ examples: [+ "webstudio man api",+ "webstudio man llm --json",+ "webstudio man mcp",+ ],+ },+ {+ command: "mcp",+ description: "Run an MCP server over stdio for the configured project",+ examples: ["webstudio mcp"],+ },+] as const;++const apiCommandOptionsByCommand: Partial<+ Record<ApiCommandName, ApiCommandOptions>+> = {+ snapshot: apiCommand.snapshotCommandOptions,+ "apply-patch": apiCommand.applyPatchCommandOptions,+ "list-pages": apiCommand.pagesCommandOptions,+ "get-page": apiCommand.pageCommandOptions,+ "get-page-by-path": apiCommand.pathCommandOptions,+ "create-page": apiCommand.createPageCommandOptions,+ "update-page": apiCommand.updatePageCommandOptions,+ "get-project-settings": apiCommand.projectSettingsCommandOptions,+ "update-project-settings": apiCommand.updateProjectSettingsCommandOptions,+ "list-redirects": apiCommand.projectSettingsCommandOptions,+ "create-redirect": apiCommand.createRedirectCommandOptions,+ "update-redirect": apiCommand.updateRedirectCommandOptions,+ "delete-redirect": apiCommand.deleteRedirectCommandOptions,+ "list-breakpoints": apiCommand.breakpointCommandOptions,+ "create-breakpoint": apiCommand.createBreakpointCommandOptions,+ "update-breakpoint": apiCommand.updateBreakpointCommandOptions,+ "delete-breakpoint": apiCommand.deleteBreakpointCommandOptions,+ "delete-page": apiCommand.deletePageCommandOptions,+ "duplicate-page": apiCommand.duplicatePageCommandOptions,+ "list-page-templates": apiCommand.listPageTemplatesCommandOptions,+ "create-page-from-template": apiCommand.createPageFromTemplateCommandOptions,+ "list-folders": apiCommand.foldersCommandOptions,+ "create-folder": apiCommand.createFolderCommandOptions,+ "update-folder": apiCommand.updateFolderCommandOptions,+ "delete-folder": apiCommand.deleteFolderCommandOptions,+ "list-instances": apiCommand.instanceListCommandOptions,+ "inspect-instance": apiCommand.instanceInspectCommandOptions,+ "append-instance": apiCommand.appendInstanceCommandOptions,+ "move-instance": apiCommand.moveInstanceCommandOptions,+ "clone-instance": apiCommand.cloneInstanceCommandOptions,+ "delete-instance": apiCommand.deleteInstanceCommandOptions,+ "update-props": apiCommand.updatePropsCommandOptions,+ "delete-props": apiCommand.deletePropsCommandOptions,+ "bind-props": apiCommand.bindPropsCommandOptions,+ "list-texts": apiCommand.textListCommandOptions,+ "update-text": apiCommand.textUpdateCommandOptions,+ "get-styles": apiCommand.stylesCommandOptions,+ "update-styles": apiCommand.updateStylesCommandOptions,+ "delete-styles": apiCommand.deleteStylesCommandOptions,+ "replace-styles": apiCommand.replaceStylesCommandOptions,+ "list-design-tokens": apiCommand.designTokensCommandOptions,+ "create-design-token": apiCommand.createDesignTokenCommandOptions,+ "update-design-token-styles":+ apiCommand.updateDesignTokenStylesCommandOptions,+ "delete-design-token-styles":+ apiCommand.deleteDesignTokenStylesCommandOptions,+ "attach-design-token": apiCommand.attachDesignTokenCommandOptions,+ "detach-design-token": apiCommand.detachDesignTokenCommandOptions,+ "extract-design-token": apiCommand.extractDesignTokenCommandOptions,+ "list-css-variables": apiCommand.cssVariablesCommandOptions,+ "define-css-variable": apiCommand.defineCssVariableCommandOptions,+ "delete-css-variable": apiCommand.deleteCssVariableCommandOptions,+ "rewrite-css-variable-refs": apiCommand.rewriteCssVariableRefsCommandOptions,+ "list-variables": apiCommand.scopedCommandOptions,+ "create-variable": apiCommand.createVariableCommandOptions,+ "update-variable": apiCommand.updateVariableCommandOptions,+ "delete-variable": apiCommand.deleteVariableCommandOptions,+ "list-resources": apiCommand.scopedCommandOptions,+ "create-resource": apiCommand.createResourceCommandOptions,+ "update-resource": apiCommand.updateResourceCommandOptions,+ "delete-resource": apiCommand.deleteResourceCommandOptions,+ publish: apiCommand.publishCommandOptions,+ "get-publish-job": apiCommand.publishJobCommandOptions,+ unpublish: apiCommand.unpublishCommandOptions,+ "create-domain": apiCommand.createDomainCommandOptions,+ "update-domain": apiCommand.updateDomainCommandOptions,+ "delete-domain": apiCommand.deleteDomainCommandOptions,+ "verify-domain": apiCommand.verifyDomainCommandOptions,+ "list-assets": apiCommand.assetsCommandOptions,+ "upload-asset": apiCommand.uploadAssetCommandOptions,+ "upload-assets": apiCommand.uploadAssetsCommandOptions,+ "find-asset-usage": apiCommand.assetCommandOptions,+ "replace-asset": apiCommand.replaceAssetCommandOptions,+ "delete-asset": apiCommand.deleteAssetCommandOptions,+};++export const apiCommandMetadata = publicApiOperations.map((operation) => ({+ command: operation.command,+ description: operation.description,+ method: operation.method,+ permit: operation.permit,+ requiredOptions: operation.requiredOptions,+ examples: operation.examples,+})) satisfies ApiCommandMetadata[];++export const highLevelCliCommands = [+ { command: "permissions", operation: "permissions" },+ { command: "publish deploy", operation: "publish" },+ { command: "publish list", operation: "list-publishes" },+ { command: "publish status", operation: "get-publish-job" },+ { command: "publish unpublish", operation: "unpublish" },+ { command: "domains list", operation: "list-domains" },+ { command: "domains create", operation: "create-domain" },+ { command: "domains update", operation: "update-domain" },+ { command: "domains delete", operation: "delete-domain" },+ { command: "domains verify", operation: "verify-domain" },+] as const satisfies readonly {+ command: string;+ operation: ApiCommandName;+}[];++export const highLevelApiCommands = highLevelCliCommands.map(+ ({ operation }) => operation+) satisfies readonly ApiCommandName[];++const highLevelApiCommandSet = new Set<ApiCommandName>(highLevelApiCommands);++const topLevelCliCommandSet = new Set<string>(+ topLevelCliCommandMetadata.map(({ command }) => command)+);++const highLevelCliCommandByOperation = new Map<ApiCommandName, string>(+ highLevelCliCommands.map(({ command, operation }) => [operation, command])+);+const highLevelCliCommandSet = new Set<string>(+ highLevelCliCommands.map(({ command }) => command)+);++export const cliApiCommandMetadata = apiCommandMetadata.filter((metadata) =>+ highLevelApiCommandSet.has(metadata.command)+);++export const cliCommandMetadata = highLevelCliCommands.map(+ ({ command, operation }) => {+ const metadata = apiCommandMetadata.find(+ (metadata) => metadata.command === operation+ );+ if (metadata === undefined) {+ throw new Error(`Missing API command metadata for "${operation}".`);+ }+ return {+ ...metadata,+ cliCommand: command,+ operation,+ };+ }+) satisfies CliCommandMetadata[];++export const mcpOnlyApiCommandMetadata = apiCommandMetadata.filter(+ (metadata) => highLevelApiCommandSet.has(metadata.command) === false+);++export const formatApiUseCaseCommand = (command: string) => {+ const match = command.match(/^webstudio ([a-z-]+)(.*)$/);+ if (match === null) {+ return command;+ }+ const [, name, rest = ""] = match;+ const detail = rest.trim();+ if (+ topLevelCliCommandSet.has(name) &&+ (detail.length === 0 || detail === "--help" || detail === "-h")+ ) {+ return command;+ }+ const existingGroupedCommand = `${name} ${detail.split(/\s+/)[0] ?? ""}`;+ if (highLevelCliCommandSet.has(existingGroupedCommand)) {+ return command;+ }+ const cliCommand = highLevelCliCommandByOperation.get(name as ApiCommandName);+ if (cliCommand !== undefined && cliCommand !== name) {+ return `webstudio ${cliCommand}${rest}`;+ }+ if (topLevelCliCommandSet.has(name)) {+ return command;+ }+ return `MCP tool: ${name} {}`;+};++export const getApiCommandOptions = (+ metadata: ApiCommandMetadata+): ApiCommandOptions =>+ apiCommandOptionsByCommand[metadata.command] ?? apiCommand.apiCommandOptions;diff --git a/packages/cli/src/commands/api-command.test.ts b/packages/cli/src/commands/api-command.test.tsnew file mode 100644index 0000000000..2818898cbb--- /dev/null+++ b/packages/cli/src/commands/api-command.test.ts@@ -0,0 +1,1729 @@+import { afterEach, beforeEach, expect, test, vi } from "vitest";+import {+ getPublicApiOperation,+ publicApiOperations,+} from "@webstudio-is/protocol";+import { apiCompatibilityHeaders } from "./api";+import { apiCommand } from "./api-command";+import { apiCommandMetadata } from "./api-command-metadata";++const apiCalls = new Proxy({} as Record<string, ReturnType<typeof vi.fn>>, {+ get(target, property: string) {+ target[property] ??= vi.fn().mockResolvedValue({ ok: true });+ return target[property];+ },+});+const isFileExists = vi.fn();+const readFile = vi.fn();+const apiClientByOperationId = new Map(+ publicApiOperations.map((operation) => [operation.id, operation.client])+);+const createSessionEnvelope = ({+ operationId,+ projectId,+ result,+ source,+}: {+ operationId: string;+ projectId: string;+ result: unknown;+ source: "local" | "remote" | "server";+}) => ({+ operationId,+ projectId,+ buildId: "build-1",+ version: 1,+ source,+ result,+ state: { committed: source !== "local", freshness: {} },+ namespaces: { read: [], write: [], invalidated: [], missing: [] },+ diagnostics: [],+});+const createCliProjectSession = vi.fn(({ connection }) => ({+ initialize: vi.fn(async () => ({ result: { loaded: true } })),+ refresh: vi.fn(async () => ({ result: { refreshedNamespaces: [] } })),+ executeServerOperation: vi.fn(+ async ({ id }: { id: string }, input: unknown) =>+ createSessionEnvelope({+ operationId: id,+ projectId: connection.projectId,+ source: "server",+ result: await apiCalls[apiClientByOperationId.get(id) ?? ""]({+ ...connection,+ ...(input as Record<string, unknown>),+ }),+ })+ ),+ read: vi.fn(async (operationId: string, input: unknown) =>+ createSessionEnvelope({+ operationId,+ projectId: connection.projectId,+ source: "local",+ result: await apiCalls[apiClientByOperationId.get(operationId) ?? ""]({+ ...connection,+ ...(input as Record<string, unknown>),+ }),+ })+ ),+ mutate: vi.fn(async (operationId: string, input: unknown) =>+ createSessionEnvelope({+ operationId,+ projectId: connection.projectId,+ source: "remote",+ result: await apiCalls[apiClientByOperationId.get(operationId) ?? ""]({+ ...connection,+ ...(input as Record<string, unknown>),+ }),+ })+ ),+}));+const dependencies = new Proxy(+ {+ isFileExists,+ readFile,+ createCliProjectSession,+ } as typeof apiCalls & {+ isFileExists: typeof isFileExists;+ readFile: typeof readFile;+ createCliProjectSession: typeof createCliProjectSession;+ },+ {+ get(target, property: string) {+ if (property in target) {+ return target[property];+ }+ return apiCalls[property];+ },+ }+) as unknown as Parameters<typeof apiCommand>[1];++const expectJsonOutput = (command: string) => {+ expect(getLastJsonOutput()).toEqual({+ ok: true,+ data: { ok: true },+ meta: {+ command,+ projectId: "project-1",+ durationMs: expect.any(Number),+ session: {+ operationId: expect.any(String),+ projectId: "project-1",+ buildId: "build-1",+ version: 1,+ source: expect.any(String),+ committed: expect.any(Boolean),+ namespaces: { read: [], write: [], invalidated: [], missing: [] },+ diagnostics: [],+ },+ },+ });+};++const getLastJsonOutput = () =>+ JSON.parse(vi.mocked(console.info).mock.calls.at(-1)?.[0]);++const expectJsonErrorOutput = ({+ command,+ code,+ message,+ projectId = "project-1",+ retry,+}: {+ command: string;+ code: string;+ message: string;+ projectId?: string | false;+ retry?: string;+}) => {+ expect(getLastJsonOutput()).toEqual({+ ok: false,+ error: { code, message, ...(retry === undefined ? {} : { retry }) },+ meta: {+ command,+ ...(projectId === false ? {} : { projectId }),+ durationMs: expect.any(Number),+ },+ });+};++const expectConnection = (extra = {}) =>+ expect.objectContaining({+ origin: "https://example.com",+ authToken: "token-1",+ projectId: "project-1",+ headers: apiCompatibilityHeaders,+ ...extra,+ });++const expectCommandCall = async ({+ options,+ call,+ connection = {},+ inputJson,+}: {+ options: Parameters<typeof apiCommand>[0];+ call: ReturnType<typeof vi.fn>;+ connection?: Record<string, unknown>;+ inputJson?: unknown;+}) => {+ mockConfig();+ if (inputJson !== undefined) {+ readFile.mockResolvedValueOnce(JSON.stringify(inputJson));+ }++ await apiCommand({ ...options, json: true }, dependencies);++ expect(call).toHaveBeenCalledWith(expectConnection(connection));+ expectJsonOutput(options.command);+};++const patchTransactions = [+ {+ id: "tx-1",+ payload: [+ {+ namespace: "pages",+ patches: [{ op: "replace", path: ["meta", "siteName"], value: "Site" }],+ },+ ],+ },+];++const mockConfig = ({+ origin = "https://example.com",+ token = "token-1",+ projectId = "project-1",+ useLegacyHost = false,+} = {}) => {+ isFileExists.mockResolvedValue(true);+ readFile+ .mockResolvedValueOnce(JSON.stringify({ projectId }))+ .mockResolvedValueOnce(+ JSON.stringify({+ [projectId]: useLegacyHost+ ? { host: origin, token }+ : { origin, token },+ })+ );+};++beforeEach(() => {+ for (const call of Object.values(apiCalls)) {+ call.mockReset();+ call.mockResolvedValue({ ok: true });+ }+ isFileExists.mockReset();+ isFileExists.mockResolvedValue(false);+ readFile.mockReset();+ createCliProjectSession.mockClear();+ vi.spyOn(console, "info").mockImplementation(() => undefined);+ vi.spyOn(console, "error").mockImplementation(() => undefined);+});++afterEach(() => {+ vi.restoreAllMocks();+});++test("requires json output flag", async () => {+ await expect(+ apiCommand(+ {+ command: "whoami",+ },+ dependencies+ )+ ).rejects.toThrow("Handled CLI error");++ expect(apiCalls.getApiTokenInfo).not.toHaveBeenCalled();+ expect(console.error).toHaveBeenCalledWith(+ "whoami currently requires --json."+ );+});++test("documents every executable api command", () => {+ expect(apiCommandMetadata.map(({ command }) => command)).toEqual(+ publicApiOperations.map(({ command }) => command)+ );+});++test("has a public operation descriptor for every executable api command", () => {+ expect(+ apiCommandMetadata.map(({ command, method, permit }) => ({+ command,+ method,+ permit,+ }))+ ).toEqual(+ publicApiOperations.map(({ command }) => ({+ command,+ method: getPublicApiOperation(command).method,+ permit: getPublicApiOperation(command).permit,+ }))+ );+});++const simpleCommandCases = [+ ["auth introspection", { command: "whoami" }, "getApiTokenInfo", {}],+ ["project details", { command: "inspect" }, "getProjectInfo", {}],+ [+ "project permissions",+ { command: "permissions" },+ "getProjectPermissions",+ {},+ ],+ [+ "page list",+ { command: "list-pages", includeFolders: true },+ "listPages",+ { includeFolders: true },+ ],+ [+ "folder list",+ { command: "list-folders", includePages: true },+ "listFolders",+ { includePages: true },+ ],+ [+ "folder delete",+ { command: "delete-folder", folder: "folder-1" },+ "deleteFolder",+ { folderId: "folder-1" },+ ],+ [+ "page details by id",+ { command: "get-page", page: "page-1" },+ "getPage",+ { pageId: "page-1" },+ ],+ [+ "page details by path",+ { command: "get-page-by-path", path: "/pricing" },+ "getPageByPath",+ { path: "/pricing" },+ ],+] satisfies Array<+ readonly [+ string,+ Parameters<typeof apiCommand>[0],+ string,+ Record<string, unknown>?,+ ]+>;++test.each(simpleCommandCases)(+ "calls %s",+ async (_name, options, callName, connection) => {+ await expectCommandCall({+ options,+ call: apiCalls[callName],+ connection: connection ?? {},+ });+ }+);++test("routes local-capable commands through project session runtime", async () => {+ mockConfig();++ await apiCommand(+ { command: "list-pages", includeFolders: true, json: true },+ dependencies+ );++ const session = createCliProjectSession.mock.results[0]?.value;+ expect(session.read).toHaveBeenCalledWith(+ "pages.list",+ {+ projectId: "project-1",+ includeFolders: true,+ },+ {+ permit: "view",+ }+ );+});++test("routes server-only commands through project session transport", async () => {+ mockConfig();++ await apiCommand({ command: "whoami", json: true }, dependencies);++ const session = createCliProjectSession.mock.results[0]?.value;+ expect(session.executeServerOperation).toHaveBeenCalledWith(+ {+ id: "auth.me",+ invalidatesNamespaces: [],+ refetchInvalidatedNamespaces: false,+ },+ {}+ );+});++test("passes refresh to local-capable command session", async () => {+ mockConfig();++ await apiCommand(+ { command: "list-pages", refresh: true, json: true },+ dependencies+ );++ const session = createCliProjectSession.mock.results[0]?.value;+ expect(session.refresh).toHaveBeenCalledWith(["pages"]);+ expect(session.read).toHaveBeenCalledWith(+ "pages.list",+ { projectId: "project-1", includeFolders: undefined },+ { permit: "view" }+ );+});++test("passes dry-run to local-capable mutations", async () => {+ mockConfig();++ await apiCommand(+ {+ command: "create-folder",+ name: "Draft",+ slug: "draft",+ dryRun: true,+ json: true,+ },+ dependencies+ );++ const session = createCliProjectSession.mock.results[0]?.value;+ expect(session.mutate).toHaveBeenCalledWith(+ "folders.create",+ {+ projectId: "project-1",+ folderId: undefined,+ name: "Draft",+ slug: "draft",+ parentFolderId: undefined,+ },+ { permit: "build", dryRun: true }+ );+});++test("calls build snapshot for configured project", async () => {+ await expectCommandCall({+ options: {+ command: "snapshot",+ include: ["pages", "designTokens"],+ version: 3,+ },+ call: apiCalls.getBuildSnapshot,+ connection: { include: ["pages", "designTokens"], version: 3 },+ });+});++test("applies build patch transactions for configured project", async () => {+ await expectCommandCall({+ options: {+ command: "apply-patch",+ baseVersion: 5,+ input: "patch.json",+ },+ call: apiCalls.applyBuildPatch,+ inputJson: patchTransactions,+ connection: { baseVersion: 5, transactions: patchTransactions },+ });+});++test("maps api conflict errors to version conflict json", async () => {+ mockConfig();+ readFile.mockResolvedValueOnce(JSON.stringify(patchTransactions));+ apiCalls.applyBuildPatch.mockRejectedValue(+ Object.assign(new Error("Build version mismatch"), {+ data: { code: "CONFLICT" },+ })+ );++ await expect(+ apiCommand(+ {+ command: "apply-patch",+ baseVersion: 5,+ input: "patch.json",+ json: true,+ },+ dependencies+ )+ ).rejects.toThrow("Handled CLI error");++ expectJsonErrorOutput({+ command: "apply-patch",+ code: "VERSION_CONFLICT",+ message: "Build version mismatch",+ retry:+ "Use MCP tool snapshot, read the latest build version, regenerate the patch, then retry MCP tool apply-patch.",+ });+});++test("maps api not found errors to not found json", async () => {+ mockConfig();+ apiCalls.getPage.mockRejectedValue(+ Object.assign(new Error("Page not found"), {+ data: { code: "NOT_FOUND" },+ })+ );++ await expect(+ apiCommand(+ {+ command: "get-page",+ page: "missing",+ json: true,+ },+ dependencies+ )+ ).rejects.toThrow("Handled CLI error");++ expectJsonErrorOutput({+ command: "get-page",+ code: "NOT_FOUND",+ message: "Page not found",+ });+});++test("splits comma-separated include values", async () => {+ mockConfig();++ await apiCommand(+ {+ command: "snapshot",+ include: ["pages,instances", "styles"],+ json: true,+ },+ dependencies+ );++ expect(apiCalls.getBuildSnapshot).toHaveBeenCalledWith(+ expectConnection({+ include: ["pages", "instances", "styles"],+ version: undefined,+ })+ );+});++test("creates folder with settings", async () => {+ await expectCommandCall({+ options: {+ command: "create-folder",+ name: "Blog",+ slug: "blog",+ parentFolder: "root-folder",+ },+ call: apiCalls.createFolder,+ connection: {+ folderId: undefined,+ name: "Blog",+ slug: "blog",+ parentFolderId: "root-folder",+ },+ });+});++test("updates folder settings", async () => {+ await expectCommandCall({+ options: {+ command: "update-folder",+ folder: "folder-1",+ name: "Blog",+ slug: "blog",+ parentFolder: "root-folder",+ },+ call: apiCalls.updateFolder,+ connection: {+ folderId: "folder-1",+ values: {+ name: "Blog",+ slug: "blog",+ parentFolderId: "root-folder",+ },+ },+ });+});++test("creates page with settings", async () => {+ await expectCommandCall({+ options: {+ command: "create-page",+ name: "Pricing",+ path: "/pricing",+ title: "Pricing",+ parentFolder: "folder-1",+ description: "Plans",+ },+ call: apiCalls.createPage,+ connection: {+ pageId: undefined,+ name: "Pricing",+ path: "/pricing",+ title: "Pricing",+ parentFolderId: "folder-1",+ meta: {+ description: "Plans",+ language: undefined,+ redirect: undefined,+ socialImageUrl: undefined,+ socialImageAssetId: undefined,+ excludePageFromSearch: undefined,+ documentType: undefined,+ content: undefined,+ status: undefined,+ auth: undefined,+ },+ },+ });+});++test("updates page metadata", async () => {+ await expectCommandCall({+ options: {+ command: "update-page",+ page: "page-1",+ title: "Pricing",+ excludePageFromSearch: true,+ status: "200",+ authLogin: "user",+ authPassword: "pass",+ },+ call: apiCalls.updatePage,+ connection: {+ pageId: "page-1",+ values: {+ name: undefined,+ path: undefined,+ title: "Pricing",+ parentFolderId: undefined,+ meta: {+ description: undefined,+ language: undefined,+ redirect: undefined,+ socialImageUrl: undefined,+ socialImageAssetId: undefined,+ excludePageFromSearch: true,+ documentType: undefined,+ content: undefined,+ status: "200",+ auth: { method: "basic", login: "user", password: "pass" },+ },+ },+ },+ });+});++test("updates project settings from input file", async () => {+ const input = {+ meta: { siteName: "Acme", faviconAssetId: null },+ compiler: { atomicStyles: true },+ };+ await expectCommandCall({+ options: {+ command: "update-project-settings",+ input: "project-settings.json",+ },+ inputJson: input,+ call: apiCalls.updateProjectSettings,+ connection: input,+ });+});++test("creates redirect", async () => {+ await expectCommandCall({+ options: {+ command: "create-redirect",+ old: "/old",+ new: "/new",+ status: "301",+ },+ call: apiCalls.createRedirect,+ connection: { old: "/old", new: "/new", status: "301" },+ });+});++test("updates redirect and can clear status", async () => {+ await expectCommandCall({+ options: {+ command: "update-redirect",+ old: "/old",+ newOld: "/older",+ new: "/newer",+ clearStatus: true,+ },+ call: apiCalls.updateRedirect,+ connection: {+ old: "/old",+ values: { old: "/older", new: "/newer", status: null },+ },+ });+});++test("rejects redirect status and clear-status together", async () => {+ mockConfig();+ await expect(+ apiCommand(+ {+ command: "update-redirect",+ old: "/old",+ status: "301",+ clearStatus: true,+ json: true,+ },+ dependencies+ )+ ).rejects.toThrow("Handled CLI error");++ expectJsonErrorOutput({+ command: "update-redirect",+ code: "API_COMMAND_FAILED",+ message: "--clear-status cannot be used with --status.",+ });+ expect(apiCalls.updateRedirect).not.toHaveBeenCalled();+});++test("deletes redirect", async () => {+ await expectCommandCall({+ options: { command: "delete-redirect", old: "/old" },+ call: apiCalls.deleteRedirect,+ connection: { old: "/old" },+ });+});++test("creates breakpoint", async () => {+ await expectCommandCall({+ options: {+ command: "create-breakpoint",+ breakpoint: "tablet",+ label: "Tablet",+ maxWidth: 991,+ },+ call: apiCalls.createBreakpoint,+ connection: {+ id: "tablet",+ label: "Tablet",+ minWidth: undefined,+ maxWidth: 991,+ condition: undefined,+ },+ });+});++test("updates breakpoint", async () => {+ await expectCommandCall({+ options: {+ command: "update-breakpoint",+ breakpoint: "tablet",+ label: "Tablet",+ maxWidth: 1023,+ },+ call: apiCalls.updateBreakpoint,+ connection: {+ breakpointId: "tablet",+ values: {+ label: "Tablet",+ minWidth: undefined,+ maxWidth: 1023,+ condition: undefined,+ },+ },+ });+});++test("updates breakpoint and can clear media fields", async () => {+ await expectCommandCall({+ options: {+ command: "update-breakpoint",+ breakpoint: "tablet",+ clearMinWidth: true,+ maxWidth: 1023,+ clearCondition: true,+ },+ call: apiCalls.updateBreakpoint,+ connection: {+ breakpointId: "tablet",+ values: {+ label: undefined,+ minWidth: null,+ maxWidth: 1023,+ condition: null,+ },+ },+ });+});++test("rejects breakpoint clear and value options together", async () => {+ mockConfig();+ await expect(+ apiCommand(+ {+ command: "update-breakpoint",+ breakpoint: "tablet",+ minWidth: 768,+ clearMinWidth: true,+ json: true,+ },+ dependencies+ )+ ).rejects.toThrow("Handled CLI error");++ expectJsonErrorOutput({+ command: "update-breakpoint",+ code: "API_COMMAND_FAILED",+ message: "--clear-min-width cannot be used with --min-width.",+ });+ expect(apiCalls.updateBreakpoint).not.toHaveBeenCalled();+});++test("deletes breakpoint with confirmation", async () => {+ await expectCommandCall({+ options: {+ command: "delete-breakpoint",+ breakpoint: "tablet",+ confirm: true,+ },+ call: apiCalls.deleteBreakpoint,+ connection: { breakpointId: "tablet" },+ });+});++test("deletes page", async () => {+ await expectCommandCall({+ options: { command: "delete-page", page: "page-1" },+ call: apiCalls.deletePage,+ connection: { pageId: "page-1" },+ });+});++test("duplicates page", async () => {+ await expectCommandCall({+ options: {+ command: "duplicate-page",+ page: "page-1",+ name: "Pricing Copy",+ path: "/pricing-copy",+ parentFolder: "folder-1",+ },+ call: apiCalls.duplicatePage,+ connection: {+ pageId: "page-1",+ name: "Pricing Copy",+ path: "/pricing-copy",+ parentFolderId: "folder-1",+ },+ });+});++test("lists page templates", async () => {+ await expectCommandCall({+ options: { command: "list-page-templates" },+ call: apiCalls.listPageTemplates,+ });+});++test("creates page from template", async () => {+ await expectCommandCall({+ options: {+ command: "create-page-from-template",+ template: "template-1",+ name: "Landing",+ path: "/landing",+ parentFolder: "folder-1",+ },+ call: apiCalls.createPageFromTemplate,+ connection: {+ templateId: "template-1",+ name: "Landing",+ path: "/landing",+ parentFolderId: "folder-1",+ },+ });+});++test("requires page id for page details", async () => {+ mockConfig();++ await expect(+ apiCommand(+ {+ command: "get-page",+ json: true,+ },+ dependencies+ )+ ).rejects.toThrow("Handled CLI error");++ expect(apiCalls.getPage).not.toHaveBeenCalled();+ expectJsonErrorOutput({+ command: "get-page",+ code: "INVALID_ARGUMENT",+ message: "--page is required.",+ });+});++test("calls instance list with filters", async () => {+ await expectCommandCall({+ options: {+ command: "list-instances",+ page: "page-1",+ maxDepth: 2,+ topLevel: true,+ component: "Box",+ label: "Hero",+ },+ call: apiCalls.listInstances,+ connection: {+ pageId: "page-1",+ pagePath: undefined,+ rootInstanceId: undefined,+ maxDepth: 2,+ topLevelOnly: true,+ component: "Box",+ tag: undefined,+ labelContains: "Hero",+ },+ });+});++test("inspects instance details", async () => {+ await expectCommandCall({+ options: {+ command: "inspect-instance",+ instance: "instance-1",+ include: ["props,styles,children"],+ childDepth: 2,+ },+ call: apiCalls.inspectInstance,+ connection: {+ instanceId: "instance-1",+ include: ["props", "styles", "children"],+ childDepth: 2,+ },+ });+});++test("appends instances from input file", async () => {+ await expectCommandCall({+ options: {+ command: "append-instance",+ parent: "parent-id",+ input: "children.json",+ mode: "prepend",+ },+ call: apiCalls.appendInstance,+ inputJson: [{ tag: "div", label: "Hero", text: "Hello" }],+ connection: {+ parentInstanceId: "parent-id",+ mode: "prepend",+ insertIndex: undefined,+ children: [{ tag: "div", label: "Hero", text: "Hello" }],+ },+ });+});++test("moves instances from input file", async () => {+ await expectCommandCall({+ options: { command: "move-instance", input: "moves.json" },+ call: apiCalls.moveInstance,+ inputJson: [{ instanceId: "instance-id", parentInstanceId: "parent-id" }],+ connection: {+ moves: [{ instanceId: "instance-id", parentInstanceId: "parent-id" }],+ },+ });+});++test("clones instance", async () => {+ await expectCommandCall({+ options: {+ command: "clone-instance",+ source: "source-id",+ parent: "parent-id",+ insertIndex: 1,+ },+ call: apiCalls.cloneInstance,+ connection: {+ sourceInstanceId: "source-id",+ targetParentInstanceId: "parent-id",+ insertIndex: 1,+ },+ });+});++test("deletes instances", async () => {+ await expectCommandCall({+ options: {+ command: "delete-instance",+ instance: ["instance-1,instance-2"],+ },+ call: apiCalls.deleteInstance,+ connection: { instanceIds: ["instance-1", "instance-2"] },+ });+});++test("rejects empty required list options", async () => {+ mockConfig();++ await expect(+ apiCommand(+ {+ command: "delete-instance",+ instance: [","],+ json: true,+ },+ dependencies+ )+ ).rejects.toThrow("Handled CLI error");++ expect(apiCalls.deleteInstance).not.toHaveBeenCalled();+ expectJsonErrorOutput({+ command: "delete-instance",+ code: "INVALID_ARGUMENT",+ message: "--instance is required.",+ });+});++test("updates props from input file", async () => {+ const updates = [+ {+ instanceId: "instance-id",+ name: "title",+ type: "string",+ value: "Hello",+ },+ ];+ await expectCommandCall({+ options: { command: "update-props", input: "props.json" },+ call: apiCalls.updateProps,+ inputJson: updates,+ connection: { updates },+ });+});++test("deletes props from input file", async () => {+ await expectCommandCall({+ options: { command: "delete-props", input: "props.json" },+ call: apiCalls.deleteProps,+ inputJson: [{ instanceId: "instance-id", name: "title" }],+ connection: {+ deletions: [{ instanceId: "instance-id", name: "title" }],+ },+ });+});++test("binds props from input file", async () => {+ const bindings = [+ {+ instanceId: "instance-id",+ name: "title",+ binding: { type: "expression", value: "title" },+ },+ ];+ await expectCommandCall({+ options: { command: "bind-props", input: "bindings.json" },+ call: apiCalls.bindProps,+ inputJson: bindings,+ connection: { bindings },+ });+});++test("updates text child", async () => {+ await expectCommandCall({+ options: {+ command: "update-text",+ instance: "instance-1",+ childIndex: 2,+ text: "Launch faster",+ mode: "text",+ },+ call: apiCalls.updateText,+ connection: {+ instanceId: "instance-1",+ childIndex: 2,+ text: "Launch faster",+ mode: "text",+ },+ });+});++test("lists text children with filters", async () => {+ await expectCommandCall({+ options: {+ command: "list-texts",+ page: "page-1",+ instance: "instance-1",+ mode: "expression",+ contains: "headline",+ maxValueLength: 80,+ },+ call: apiCalls.listTexts,+ connection: {+ pageId: "page-1",+ pagePath: undefined,+ instanceId: "instance-1",+ mode: "expression",+ contains: "headline",+ maxValueLength: 80,+ },+ });+});++test("allows clearing text child", async () => {+ await expectCommandCall({+ options: {+ command: "update-text",+ instance: "instance-1",+ childIndex: 2,+ text: "",+ },+ call: apiCalls.updateText,+ connection: {+ instanceId: "instance-1",+ childIndex: 2,+ text: "",+ mode: undefined,+ },+ });+});++test("creates variable with parsed value", async () => {+ await expectCommandCall({+ options: {+ command: "create-variable",+ scopeInstance: "body-id",+ name: "items",+ valueType: "string[]",+ value: '["a","b"]',+ },+ call: apiCalls.createVariable,+ connection: {+ dataSourceId: undefined,+ scopeInstanceId: "body-id",+ name: "items",+ value: { type: "string[]", value: ["a", "b"] },+ },+ });+});++test("lists variables with scope filter", async () => {+ await expectCommandCall({+ options: { command: "list-variables", scopeInstance: "body-id" },+ call: apiCalls.listVariables,+ connection: { scopeInstanceId: "body-id" },+ });+});++test("updates variable", async () => {+ await expectCommandCall({+ options: {+ command: "update-variable",+ variable: "variable-id",+ name: "count",+ valueType: "number",+ value: "2",+ },+ call: apiCalls.updateVariable,+ connection: {+ dataSourceId: "variable-id",+ values: {+ scopeInstanceId: undefined,+ name: "count",+ value: { type: "number", value: 2 },+ },+ },+ });+});++test("deletes variable", async () => {+ await expectCommandCall({+ options: { command: "delete-variable", variable: "variable-id" },+ call: apiCalls.deleteVariable,+ connection: { dataSourceId: "variable-id" },+ });+});++test("creates resource from options and exposes data source", async () => {+ await expectCommandCall({+ options: {+ command: "create-resource",+ name: "Posts",+ method: "get",+ url: '"https://api.example.com/posts"',+ scopeInstance: "body-id",+ dataSourceName: "posts",+ },+ call: apiCalls.createResource,+ connection: {+ resourceId: undefined,+ resource: {+ name: "Posts",+ method: "get",+ url: '"https://api.example.com/posts"',+ body: undefined,+ headers: [],+ },+ dataSourceId: undefined,+ scopeInstanceId: "body-id",+ dataSourceName: "posts",+ },+ });+});++test("lists resources with scope filter", async () => {+ await expectCommandCall({+ options: { command: "list-resources", scopeInstance: "body-id" },+ call: apiCalls.listResources,+ connection: { scopeInstanceId: "body-id" },+ });+});++test("updates resource from input file", async () => {+ await expectCommandCall({+ options: {+ command: "update-resource",+ resource: "resource-id",+ input: "resource.json",+ name: "Posts",+ },+ call: apiCalls.updateResource,+ inputJson: { headers: [{ name: "Authorization", value: "token" }] },+ connection: {+ resourceId: "resource-id",+ values: {+ name: "Posts",+ method: undefined,+ url: undefined,+ body: undefined,+ headers: [{ name: "Authorization", value: "token" }],+ },+ dataSourceName: undefined,+ scopeInstanceId: undefined,+ },+ });+});++test("deletes resource with force", async () => {+ await expectCommandCall({+ options: {+ command: "delete-resource",+ resource: "resource-id",+ force: true,+ },+ call: apiCalls.deleteResource,+ connection: { resourceId: "resource-id", force: true },+ });+});++test("publishes project", async () => {+ await expectCommandCall({+ options: {+ command: "publish",+ target: "production",+ domain: ["example.com,www.example.com"],+ message: "Ship",+ idempotencyKey: "publish-key",+ },+ call: apiCalls.publish,+ connection: {+ target: "production",+ domains: ["example.com", "www.example.com"],+ message: "Ship",+ idempotencyKey: "publish-key",+ },+ });+});++test("lists publishes", async () => {+ await expectCommandCall({+ options: { command: "list-publishes" },+ call: apiCalls.listPublishes,+ });+});++test("gets publish job", async () => {+ await expectCommandCall({+ options: { command: "get-publish-job", job: "job-id" },+ call: apiCalls.getPublishJob,+ connection: { jobId: "job-id" },+ });+});++test("unpublishes project with confirmation", async () => {+ await expectCommandCall({+ options: {+ command: "unpublish",+ target: "production",+ domain: ["example.com"],+ confirm: true,+ },+ call: apiCalls.unpublish,+ connection: {+ target: "production",+ domains: ["example.com"],+ message: undefined,+ idempotencyKey: undefined,+ },+ });+});++test("lists domains", async () => {+ await expectCommandCall({+ options: { command: "list-domains" },+ call: apiCalls.listDomains,+ });+});++test("creates domain", async () => {+ await expectCommandCall({+ options: { command: "create-domain", domain: "example.com" },+ call: apiCalls.createDomain,+ connection: { domain: "example.com" },+ });+});++test("updates domain", async () => {+ await expectCommandCall({+ options: {+ command: "update-domain",+ domainId: "domain-id",+ domain: "www.example.com",+ },+ call: apiCalls.updateDomain,+ connection: {+ domainId: "domain-id",+ updates: { domain: "www.example.com" },+ },+ });+});++test("deletes domain with confirmation", async () => {+ await expectCommandCall({+ options: { command: "delete-domain", domainId: "domain-id", confirm: true },+ call: apiCalls.deleteDomain,+ connection: { domainId: "domain-id" },+ });+});++test("verifies domain", async () => {+ await expectCommandCall({+ options: { command: "verify-domain", domainId: "domain-id" },+ call: apiCalls.verifyDomain,+ connection: { domainId: "domain-id" },+ });+});++test("calls asset list with pagination", async () => {+ await expectCommandCall({+ options: {+ command: "list-assets",+ type: "image",+ sort: "createdAt",+ withUsage: true,+ cursor: "2",+ limit: 10,+ },+ call: apiCalls.listAssets,+ connection: {+ type: "image",+ sort: "createdAt",+ withUsage: true,+ cursor: "2",+ limit: 10,+ },+ });+});++test("uploads asset descriptor with local file reader", async () => {+ mockConfig();+ readFile.mockResolvedValueOnce(+ JSON.stringify({+ name: "image.png",+ type: "image",+ format: "png",+ meta: { width: 10, height: 20 },+ })+ );+ readFile.mockResolvedValueOnce(new Uint8Array([1, 2, 3]));++ await apiCommand(+ {+ command: "upload-asset",+ input: "asset.json",+ assetsDir: "assets",+ json: true,+ },+ dependencies+ );++ expect(apiCalls.uploadProjectAsset).toHaveBeenCalledWith(+ expectConnection({+ asset: {+ name: "image.png",+ type: "image",+ format: "png",+ meta: { width: 10, height: 20 },+ },+ readAssetData: expect.any(Function),+ })+ );+ const call = apiCalls.uploadProjectAsset.mock.calls.at(-1)?.[0];+ await call.readAssetData({ name: "image.png" });+ expect(readFile).toHaveBeenLastCalledWith(+ expect.stringMatching(/assets[/\\]image\.png$/)+ );+ expectJsonOutput("upload-asset");+});++test("uploads asset descriptors with local file reader", async () => {+ await expectCommandCall({+ options: {+ command: "upload-assets",+ input: "assets.json",+ },+ call: apiCalls.uploadProjectAssets,+ inputJson: [+ {+ name: "image.png",+ type: "image",+ format: "png",+ meta: { width: 10, height: 20 },+ },+ ],+ connection: {+ assets: [+ {+ name: "image.png",+ type: "image",+ format: "png",+ meta: { width: 10, height: 20 },+ },+ ],+ readAssetData: expect.any(Function),+ },+ });+});++test("finds asset usage", async () => {+ await expectCommandCall({+ options: {+ command: "find-asset-usage",+ asset: "asset-id",+ },+ call: apiCalls.findAssetUsage,+ connection: { assetId: "asset-id" },+ });+});++test("replaces asset with confirmation", async () => {+ await expectCommandCall({+ options: {+ command: "replace-asset",+ from: "old-asset-id",+ to: "new-asset-id",+ confirm: true,+ },+ call: apiCalls.replaceAsset,+ connection: {+ fromAssetId: "old-asset-id",+ toAssetId: "new-asset-id",+ },+ });+});++test("deletes assets with confirmation", async () => {+ await expectCommandCall({+ options: {+ command: "delete-asset",+ asset: ["asset-id,asset-prefix"],+ confirm: true,+ force: true,+ },+ call: apiCalls.deleteAssets,+ connection: {+ assetIdsOrPrefixes: ["asset-id", "asset-prefix"],+ force: true,+ },+ });+});++test("passes style token inclusion through to the api", async () => {+ await expectCommandCall({+ options: {+ command: "get-styles",+ instance: "instance-1",+ includeTokens: true,+ },+ call: apiCalls.getStyleDeclarations,+ connection: {+ instanceIds: ["instance-1"],+ pageId: undefined,+ pagePath: undefined,+ breakpoint: undefined,+ state: undefined,+ property: undefined,+ propertyFilter: undefined,+ includeTokens: true,+ },+ });+});++test("lists design tokens with filters", async () => {+ await expectCommandCall({+ options: {+ command: "list-design-tokens",+ filter: "brand",+ withUsage: true,+ sort: "usage",+ },+ call: apiCalls.listDesignTokens,+ connection: { filter: "brand", withUsage: true, sort: "usage" },+ });+});++test("updates styles from input file", async () => {+ const updates = [+ {+ instanceId: "instance-id",+ property: "color",+ value: { type: "keyword", value: "red" },+ },+ ];+ await expectCommandCall({+ options: { command: "update-styles", input: "styles.json" },+ call: apiCalls.updateStyleDeclarations,+ inputJson: updates,+ connection: { updates },+ });+});++test("deletes styles from input file", async () => {+ await expectCommandCall({+ options: { command: "delete-styles", input: "styles.json" },+ call: apiCalls.deleteStyleDeclarations,+ inputJson: [{ instanceId: "instance-id", property: "color" }],+ connection: {+ deletions: [{ instanceId: "instance-id", property: "color" }],+ },+ });+});++test("replaces styles from input file", async () => {+ const inputJson = {+ property: "color",+ fromValue: { type: "keyword", value: "red" },+ toValue: { type: "keyword", value: "blue" },+ };+ await expectCommandCall({+ options: { command: "replace-styles", input: "replace.json" },+ call: apiCalls.replaceStyleValues,+ inputJson,+ connection: inputJson,+ });+});++test("creates design tokens from input file", async () => {+ const tokens = [+ {+ name: "Primary",+ styles: { color: { type: "keyword", value: "red" } },+ },+ ];+ await expectCommandCall({+ options: { command: "create-design-token", input: "tokens.json" },+ call: apiCalls.createDesignTokens,+ inputJson: tokens,+ connection: { tokens },+ });+});++test("updates design token styles from input file", async () => {+ const updates = [+ { property: "color", value: { type: "keyword", value: "blue" } },+ ];+ await expectCommandCall({+ options: {+ command: "update-design-token-styles",+ designToken: "token-id",+ input: "styles.json",+ },+ call: apiCalls.updateDesignTokenStyles,+ inputJson: updates,+ connection: { designTokenId: "token-id", updates },+ });+});++test("deletes design token styles from input file", async () => {+ await expectCommandCall({+ options: {+ command: "delete-design-token-styles",+ designToken: "token-id",+ input: "styles.json",+ },+ call: apiCalls.deleteDesignTokenStyles,+ inputJson: [{ property: "color" }],+ connection: {+ designTokenId: "token-id",+ deletions: [{ property: "color" }],+ },+ });+});++test("attaches design token from input file", async () => {+ await expectCommandCall({+ options: {+ command: "attach-design-token",+ designToken: "token-id",+ input: "instances.json",+ position: "before-local",+ },+ call: apiCalls.attachDesignToken,+ inputJson: ["instance-id"],+ connection: {+ designTokenId: "token-id",+ instanceIds: ["instance-id"],+ position: "before-local",+ },+ });+});++test("detaches design token from input file", async () => {+ await expectCommandCall({+ options: {+ command: "detach-design-token",+ designToken: "token-id",+ input: "instances.json",+ },+ call: apiCalls.detachDesignToken,+ inputJson: ["instance-id"],+ connection: { designTokenId: "token-id", instanceIds: ["instance-id"] },+ });+});++test("extracts design token from input file", async () => {+ const inputJson = {+ instanceIds: ["instance-id"],+ name: "Extracted",+ removeLocalProps: ["color"],+ };+ await expectCommandCall({+ options: { command: "extract-design-token", input: "token.json" },+ call: apiCalls.extractDesignToken,+ inputJson,+ connection: inputJson,+ });+});++test("lists css variables", async () => {+ await expectCommandCall({+ options: { command: "list-css-variables", withUsage: true },+ call: apiCalls.listCssVariables,+ connection: { filter: undefined, withUsage: true },+ });+});++test("defines css variables from input file", async () => {+ await expectCommandCall({+ options: {+ command: "define-css-variable",+ input: "vars.json",+ overwrite: true,+ },+ call: apiCalls.defineCssVariables,+ inputJson: { "--brand-color": "red" },+ connection: { vars: { "--brand-color": "red" }, overwrite: true },+ });+});++test("deletes css variables from input file", async () => {+ await expectCommandCall({+ options: {+ command: "delete-css-variable",+ input: "names.json",+ confirm: true,+ force: true,+ },+ call: apiCalls.deleteCssVariables,+ inputJson: ["--brand-color"],+ connection: { names: ["--brand-color"], force: true },+ });+});++test("rewrites css variable refs from input file", async () => {+ await expectCommandCall({+ options: {+ command: "rewrite-css-variable-refs",+ input: "variables.json",+ scopeRegex: "body",+ },+ call: apiCalls.rewriteCssVariableRefs,+ inputJson: { "--brand-color": "--accent-color" },+ connection: {+ map: { "--brand-color": "--accent-color" },+ scopeRegex: "body",+ },+ });+});++test("supports legacy host field in global linked config", async () => {+ mockConfig({ origin: "https://legacy.example.com", useLegacyHost: true });++ await apiCommand(+ {+ command: "whoami",+ json: true,+ },+ dependencies+ );++ expect(apiCalls.getApiTokenInfo).toHaveBeenCalledWith(+ expect.objectContaining({+ origin: "https://legacy.example.com",+ authToken: "token-1",+ })+ );+});++test("requires initialized local config", async () => {+ await expect(+ apiCommand(+ {+ command: "whoami",+ json: true,+ },+ dependencies+ )+ ).rejects.toThrow("Handled CLI error");++ expect(apiCalls.getApiTokenInfo).not.toHaveBeenCalled();+ expectJsonErrorOutput({+ command: "whoami",+ code: "NOT_INITIALIZED",+ message:+ "Local config file is not found. Run webstudio init --link <api-share-link> from a Webstudio project.",+ projectId: false,+ });+});++test("requires global config for configured project", async () => {+ isFileExists.mockResolvedValue(true);+ readFile+ .mockResolvedValueOnce(JSON.stringify({ projectId: "project-1" }))+ .mockResolvedValueOnce(JSON.stringify({}));++ await expect(+ apiCommand(+ {+ command: "inspect",+ json: true,+ },+ dependencies+ )+ ).rejects.toThrow("Handled CLI error");++ expect(apiCalls.getProjectInfo).not.toHaveBeenCalled();+ expectJsonErrorOutput({+ command: "inspect",+ code: "NOT_INITIALIZED",+ message:+ "Project config is not found. Run webstudio init --link <api-share-link>.",+ projectId: false,+ });+});diff --git a/packages/cli/src/commands/api-command.ts b/packages/cli/src/commands/api-command.tsnew file mode 100644index 0000000000..ca277f8b48--- /dev/null+++ b/packages/cli/src/commands/api-command.ts@@ -0,0 +1,2659 @@+import { readFile } from "node:fs/promises";+import * as httpClient from "@webstudio-is/http-client";+import { isFileExists } from "../fs-utils";+import { HandledCliError } from "../errors";+import { getLocalAssetPath, LOCAL_ASSETS_DIR } from "../asset-files";+import { createCliProjectSession } from "../project-session";+import { getStableErrorCode } from "../error-codes";+import { printJson } from "../json-output";+import {+ executeProjectSessionApiOperation,+ getProjectSessionMeta,+ isProjectSessionEnvelope,+ type ProjectSessionApiCommand,+} from "../project-session-api";+import { resolveApiConnection, type ApiConnection } from "../api-connection";+import { apiCompatibilityHeaders } from "./api";+import type { CommonYargsArgv } from "./yargs-types";++const apiCommandHttpClient = httpClient;++type ApiCommandDependencies = typeof apiCommandHttpClient & {+ isFileExists: typeof isFileExists;+ readFile: typeof readFile;+ createCliProjectSession: typeof createCliProjectSession;+};++const defaultDependencies: ApiCommandDependencies = {+ ...apiCommandHttpClient,+ isFileExists,+ readFile,+ createCliProjectSession,+};++export type ApiCommandName = ProjectSessionApiCommand;++let activeApiCommandDryRun = false;+let activeApiCommandRefresh = false;++export const apiCommandOptions = (yargs: CommonYargsArgv) =>+ yargs+ .option("json", {+ type: "boolean",+ describe: "Required. Print a machine-readable JSON response to stdout",+ default: false,+ })+ .option("dry-run", {+ type: "boolean",+ describe:+ "Plan a local-capable mutation and return the patch without committing it. Not supported for server-only operations.",+ })+ .option("refresh", {+ type: "boolean",+ describe:+ "Refresh required local project namespaces from the remote project before running a local-capable command.",+ });++const requiredInputOption = (yargs: CommonYargsArgv, describe: string) =>+ yargs.option("input", {+ type: "string",+ describe,+ demandOption: true,+ });++const confirmOption = (yargs: CommonYargsArgv, describe: string) =>+ yargs.option("confirm", {+ type: "boolean",+ describe,+ demandOption: true,+ });++export const snapshotCommandOptions = (yargs: CommonYargsArgv) =>+ apiCommandOptions(yargs.version(false))+ .option("include", {+ type: "array",+ string: true,+ describe:+ "Comma-separated build data namespaces to include, such as pages, instances, styles, assets, resources, variables",+ })+ .option("version", {+ type: "number",+ describe:+ "Read a specific numeric dev build version instead of the latest dev build",+ })+ .example(+ "$0 snapshot --include pages,instances,styles --json",+ "Read selected build namespaces from the configured project"+ );++export const applyPatchCommandOptions = (yargs: CommonYargsArgv) =>+ apiCommandOptions(yargs)+ .option("base-version", {+ type: "number",+ describe:+ "Required. Expected current build version; the write fails if the project has changed",+ demandOption: true,+ })+ .option("input", {+ type: "string",+ describe:+ "Required. JSON file containing BuildPatchTransaction[] or { transactions } generated from Builder store patches",+ demandOption: true,+ })+ .example(+ "$0 apply-patch --base-version 42 --input patch.json --json",+ "Apply Builder patch transactions with optimistic version checking"+ );++export const pageCommandOptions = (yargs: CommonYargsArgv) =>+ apiCommandOptions(yargs).option("page", {+ type: "string",+ describe: "Required page id",+ demandOption: true,+ });++export const pathCommandOptions = (yargs: CommonYargsArgv) =>+ apiCommandOptions(yargs).option("path", {+ type: "string",+ describe: "Required page path, for example /pricing",+ demandOption: true,+ });++export const pagesCommandOptions = (yargs: CommonYargsArgv) =>+ apiCommandOptions(yargs).option("include-folders", {+ type: "boolean",+ describe: "Include folder records alongside page summaries",+ });++export const createPageCommandOptions = (yargs: CommonYargsArgv) =>+ apiCommandOptions(yargs)+ .option("page", {+ type: "string",+ describe: "Optional page id to create; generated by Builder when omitted",+ })+ .option("name", {+ type: "string",+ describe: "Required page name shown in Builder",+ demandOption: true,+ })+ .option("path", {+ type: "string",+ describe: "Required page URL path, for example /pricing",+ demandOption: true,+ })+ .option("title", {+ type: "string",+ describe: "Page title expression; defaults to --name",+ })+ .option("parent-folder", {+ type: "string",+ describe: "Folder id where the page should be created",+ });++export const updatePageCommandOptions = (yargs: CommonYargsArgv) =>+ apiCommandOptions(yargs)+ .option("page", {+ type: "string",+ describe: "Required page id to update",+ demandOption: true,+ })+ .option("name", {+ type: "string",+ describe: "Update page name shown in Builder",+ })+ .option("path", {+ type: "string",+ describe: "Update page URL path, for example /pricing",+ })+ .option("title", {+ type: "string",+ describe: "Update page title expression",+ })+ .option("description", {+ type: "string",+ describe: "Update page meta description expression",+ })+ .option("language", {+ type: "string",+ describe: "Update page language expression",+ })+ .option("redirect", {+ type: "string",+ describe: "Update page redirect expression",+ })+ .option("social-image-url", {+ type: "string",+ describe: "Update page social image URL expression",+ })+ .option("social-image-asset", {+ type: "string",+ describe: "Update page social image asset id",+ })+ .option("exclude-page-from-search", {+ type: "boolean",+ describe: "Set whether search engines should skip this page",+ })+ .option("document-type", {+ choices: ["html", "xml", "text"] as const,+ describe: "Set page document type",+ })+ .option("content", {+ type: "string",+ describe: "Update page custom document content",+ })+ .option("status", {+ type: "string",+ describe: "Update page response status expression",+ })+ .option("auth-login", {+ type: "string",+ describe: "Set page basic-auth login",+ })+ .option("auth-password", {+ type: "string",+ describe: "Set page basic-auth password",+ })+ .option("parent-folder", {+ type: "string",+ describe: "Move page into this folder id",+ });++export const projectSettingsCommandOptions = (yargs: CommonYargsArgv) =>+ apiCommandOptions(yargs);++export const updateProjectSettingsCommandOptions = (yargs: CommonYargsArgv) =>+ requiredInputOption(+ apiCommandOptions(yargs),+ "Required JSON file with optional meta and compiler objects. Use null values to remove existing fields."+ );++export const createRedirectCommandOptions = (yargs: CommonYargsArgv) =>+ apiCommandOptions(yargs)+ .option("old", {+ type: "string",+ describe: "Required source URL path to redirect from, for example /old",+ demandOption: true,+ })+ .option("new", {+ type: "string",+ describe: "Required destination URL or path, for example /new",+ demandOption: true,+ })+ .option("status", {+ type: "string",+ choices: ["301", "302"] as const,+ describe: "Redirect HTTP status code",+ });++export const updateRedirectCommandOptions = (yargs: CommonYargsArgv) =>+ apiCommandOptions(yargs)+ .option("old", {+ type: "string",+ describe: "Required current source URL path to update",+ demandOption: true,+ })+ .option("new-old", {+ type: "string",+ describe: "Replace the source URL path",+ })+ .option("new", {+ type: "string",+ describe: "Replace the destination URL or path",+ })+ .option("status", {+ type: "string",+ choices: ["301", "302"] as const,+ describe: "Replace the redirect HTTP status code",+ })+ .option("clear-status", {+ type: "boolean",+ describe: "Remove explicit redirect status and use the default",+ });++export const deleteRedirectCommandOptions = (yargs: CommonYargsArgv) =>+ apiCommandOptions(yargs).option("old", {+ type: "string",+ describe: "Required source URL path to delete",+ demandOption: true,+ });++export const breakpointCommandOptions = (yargs: CommonYargsArgv) =>+ apiCommandOptions(yargs);++const breakpointFieldsCommandOptions = (+ yargs: CommonYargsArgv,+ options: { requireLabel?: boolean } = {}+) =>+ yargs+ .option("label", {+ type: "string",+ describe:+ options.requireLabel === true+ ? "Required breakpoint label shown in Builder"+ : "Breakpoint label shown in Builder",+ demandOption: options.requireLabel,+ })+ .option("min-width", {+ type: "number",+ describe: "Minimum viewport width in pixels",+ })+ .option("max-width", {+ type: "number",+ describe: "Maximum viewport width in pixels",+ })+ .option("condition", {+ type: "string",+ describe: "Custom CSS media query condition without @media",+ })+ .option("clear-min-width", {+ type: "boolean",+ describe: "Remove the minimum viewport width",+ })+ .option("clear-max-width", {+ type: "boolean",+ describe: "Remove the maximum viewport width",+ })+ .option("clear-condition", {+ type: "boolean",+ describe: "Remove the custom media query condition",+ });++export const createBreakpointCommandOptions = (yargs: CommonYargsArgv) =>+ breakpointFieldsCommandOptions(+ apiCommandOptions(yargs).option("breakpoint", {+ type: "string",+ describe: "Required breakpoint id to create",+ demandOption: true,+ }),+ { requireLabel: true }+ );++export const updateBreakpointCommandOptions = (yargs: CommonYargsArgv) =>+ breakpointFieldsCommandOptions(+ apiCommandOptions(yargs).option("breakpoint", {+ type: "string",+ describe: "Required breakpoint id to update",+ demandOption: true,+ })+ );++export const deleteBreakpointCommandOptions = (yargs: CommonYargsArgv) =>+ confirmOption(+ apiCommandOptions(yargs).option("breakpoint", {+ type: "string",+ describe: "Required breakpoint id to delete",+ demandOption: true,+ }),+ "Required. Confirm deleting this breakpoint and its style declarations"+ );++export const deletePageCommandOptions = (yargs: CommonYargsArgv) =>+ apiCommandOptions(yargs).option("page", {+ type: "string",+ describe: "Required page id to delete",+ demandOption: true,+ });++export const duplicatePageCommandOptions = (yargs: CommonYargsArgv) =>+ apiCommandOptions(yargs)+ .option("page", {+ type: "string",+ describe: "Required page id to duplicate",+ demandOption: true,+ })+ .option("name", {+ type: "string",+ describe: "Optional name for the duplicated page",+ })+ .option("path", {+ type: "string",+ describe: "Optional URL path for the duplicated page",+ })+ .option("parent-folder", {+ type: "string",+ describe: "Folder id where the duplicated page should be inserted",+ });++export const listPageTemplatesCommandOptions = (yargs: CommonYargsArgv) =>+ apiCommandOptions(yargs);++export const createPageFromTemplateCommandOptions = (yargs: CommonYargsArgv) =>+ apiCommandOptions(yargs)+ .option("template", {+ type: "string",+ describe: "Required page template id to copy",+ demandOption: true,+ })+ .option("name", {+ type: "string",+ describe: "Required new page name shown in Builder",+ demandOption: true,+ })+ .option("path", {+ type: "string",+ describe: "Required new page URL path, for example /landing",+ demandOption: true,+ })+ .option("parent-folder", {+ type: "string",+ describe: "Folder id where the new page should be inserted",+ });++export const foldersCommandOptions = (yargs: CommonYargsArgv) =>+ apiCommandOptions(yargs).option("include-pages", {+ type: "boolean",+ describe: "Include a top-level pages array with page summaries",+ });++export const createFolderCommandOptions = (yargs: CommonYargsArgv) =>+ apiCommandOptions(yargs)+ .option("folder", {+ type: "string",+ describe:+ "Optional folder id to create; generated by Builder when omitted",+ })+ .option("name", {+ type: "string",+ describe: "Required folder name shown in Builder",+ demandOption: true,+ })+ .option("slug", {+ type: "string",+ describe:+ "Required folder URL slug, use empty string for no path segment",+ demandOption: true,+ })+ .option("parent-folder", {+ type: "string",+ describe: "Parent folder id where the folder should be created",+ });++export const updateFolderCommandOptions = (yargs: CommonYargsArgv) =>+ apiCommandOptions(yargs)+ .option("folder", {+ type: "string",+ describe: "Required folder id to update",+ demandOption: true,+ })+ .option("name", {+ type: "string",+ describe: "Update folder name shown in Builder",+ })+ .option("slug", {+ type: "string",+ describe: "Update folder URL slug",+ })+ .option("parent-folder", {+ type: "string",+ describe: "Move folder into this parent folder id",+ });++export const deleteFolderCommandOptions = (yargs: CommonYargsArgv) =>+ apiCommandOptions(yargs).option("folder", {+ type: "string",+ describe: "Required folder id to delete with its child folders and pages",+ demandOption: true,+ });++export const instanceListCommandOptions = (yargs: CommonYargsArgv) =>+ apiCommandOptions(yargs)+ .option("page", {+ type: "string",+ describe: "Limit results to a page id",+ })+ .option("path", {+ type: "string",+ describe: "Limit results to a page path, for example /pricing",+ })+ .option("root", {+ type: "string",+ describe: "Limit traversal to this root instance id",+ })+ .option("max-depth", {+ type: "number",+ describe: "Maximum descendant depth to include from the root",+ })+ .option("top-level", {+ type: "boolean",+ describe: "Only return root-level instances in the selected scope",+ })+ .option("component", {+ type: "string",+ describe: "Only return instances with this component name",+ })+ .option("tag", {+ type: "string",+ describe: "Only return instances with this HTML tag override",+ })+ .option("label", {+ type: "string",+ describe: "Only return instances whose label contains this text",+ });++export const instanceInspectCommandOptions = (yargs: CommonYargsArgv) =>+ apiCommandOptions(yargs)+ .option("instance", {+ type: "string",+ describe: "Required instance id to inspect",+ demandOption: true,+ })+ .option("include", {+ type: "array",+ string: true,+ describe:+ "Comma-separated details to include: props, styles, children, bindings, sources",+ })+ .option("child-depth", {+ type: "number",+ describe: "When including children, maximum descendant depth to return",+ });++export const appendInstanceCommandOptions = (yargs: CommonYargsArgv) =>+ requiredInputOption(+ apiCommandOptions(yargs)+ .option("parent", {+ type: "string",+ describe: "Required parent instance id where new children are inserted",+ demandOption: true,+ })+ .option("mode", {+ choices: ["append", "prepend", "replace"] as const,+ describe:+ "Append, prepend, or replace parent children before inserting new instances",+ })+ .option("insert-index", {+ type: "number",+ describe: "Zero-based child index for insertion",+ }),+ "Required JSON file containing an array of children with tag, optional component, label, text, and instanceId"+ );++export const moveInstanceCommandOptions = (yargs: CommonYargsArgv) =>+ requiredInputOption(+ apiCommandOptions(yargs),+ "Required JSON file containing an array of moves with instanceId, parentInstanceId, and optional insertIndex"+ );++export const cloneInstanceCommandOptions = (yargs: CommonYargsArgv) =>+ apiCommandOptions(yargs)+ .option("source", {+ type: "string",+ describe: "Required source instance id to clone",+ demandOption: true,+ })+ .option("parent", {+ type: "string",+ describe:+ "Optional target parent instance id; defaults to the source parent",+ })+ .option("insert-index", {+ type: "number",+ describe: "Zero-based child index for the cloned instance",+ });++export const deleteInstanceCommandOptions = (yargs: CommonYargsArgv) =>+ apiCommandOptions(yargs).option("instance", {+ type: "array",+ string: true,+ describe:+ "Required instance id to delete. Repeat or comma-separate to delete multiple roots.",+ demandOption: true,+ });++export const updatePropsCommandOptions = (yargs: CommonYargsArgv) =>+ requiredInputOption(+ apiCommandOptions(yargs),+ "Required JSON file containing an array of prop updates with instanceId, name, type, value, and optional propId"+ );++export const deletePropsCommandOptions = (yargs: CommonYargsArgv) =>+ requiredInputOption(+ apiCommandOptions(yargs),+ "Required JSON file containing an array of prop deletions with instanceId and name"+ );++export const bindPropsCommandOptions = (yargs: CommonYargsArgv) =>+ requiredInputOption(+ apiCommandOptions(yargs),+ "Required JSON file containing an array of prop bindings with instanceId, name, and binding"+ );++export const textListCommandOptions = (yargs: CommonYargsArgv) =>+ apiCommandOptions(yargs)+ .option("page", {+ type: "string",+ describe: "Limit text nodes to a page id",+ })+ .option("path", {+ type: "string",+ describe: "Limit text nodes to a page path, for example /pricing",+ })+ .option("instance", {+ type: "string",+ describe: "Limit text nodes to one instance id",+ })+ .option("mode", {+ choices: ["text", "expression", "all"] as const,+ describe: "Return text children, expression children, or both",+ })+ .option("contains", {+ type: "string",+ describe: "Only return text nodes whose value contains this substring",+ })+ .option("max-value-length", {+ type: "number",+ describe: "Truncate returned text values to this character count",+ });++export const textUpdateCommandOptions = (yargs: CommonYargsArgv) =>+ apiCommandOptions(yargs)+ .option("instance", {+ type: "string",+ describe: "Required instance id containing the text child",+ demandOption: true,+ })+ .option("child-index", {+ type: "number",+ describe:+ "Required zero-based child index from list-texts for the text child to update",+ demandOption: true,+ })+ .option("text", {+ type: "string",+ describe: "Required replacement text or expression string",+ demandOption: true,+ })+ .option("mode", {+ choices: ["text", "expression"] as const,+ describe:+ "Optional expected child type; use expression to validate expression syntax",+ });++export const stylesCommandOptions = (yargs: CommonYargsArgv) =>+ apiCommandOptions(yargs)+ .option("instance", {+ type: "string",+ describe: "Limit declarations to one instance id",+ })+ .option("page", {+ type: "string",+ describe: "Limit declarations to instances on this page id",+ })+ .option("path", {+ type: "string",+ describe: "Limit declarations to instances on this page path",+ })+ .option("breakpoint", {+ type: "string",+ describe: "Only return declarations for this breakpoint id",+ })+ .option("state", {+ type: "string",+ describe: "Only return declarations for this state selector",+ })+ .option("property", {+ type: "string",+ describe: "Only return declarations for this exact CSS property",+ })+ .option("property-filter", {+ type: "string",+ describe:+ "Only return declarations whose CSS property contains this text",+ })+ .option("include-tokens", {+ type: "boolean",+ describe:+ "Include token style declarations in addition to local declarations",+ });++export const updateStylesCommandOptions = (yargs: CommonYargsArgv) =>+ requiredInputOption(+ apiCommandOptions(yargs),+ "Required JSON file containing an array of style updates with instanceId, property, value, optional breakpoint/state"+ );++export const deleteStylesCommandOptions = (yargs: CommonYargsArgv) =>+ requiredInputOption(+ apiCommandOptions(yargs),+ "Required JSON file containing an array of style deletions with instanceId, property, optional breakpoint/state"+ );++export const replaceStylesCommandOptions = (yargs: CommonYargsArgv) =>+ requiredInputOption(+ apiCommandOptions(yargs),+ "Required JSON file containing property, fromValue, toValue, and optional pageId/pagePath"+ );++export const designTokensCommandOptions = (yargs: CommonYargsArgv) =>+ apiCommandOptions(yargs)+ .option("filter", {+ type: "string",+ describe: "Only return design tokens whose name contains this text",+ })+ .option("with-usage", {+ type: "boolean",+ describe: "Include how many instances use each design token",+ })+ .option("sort", {+ choices: ["name", "usage"] as const,+ describe: "Sort design tokens by name or usage count",+ });++export const createDesignTokenCommandOptions = (yargs: CommonYargsArgv) =>+ requiredInputOption(+ apiCommandOptions(yargs),+ "Required JSON file containing an array of design tokens with name, optional tokenId, styles object, or declarations array"+ );++export const updateDesignTokenStylesCommandOptions = (yargs: CommonYargsArgv) =>+ requiredInputOption(+ apiCommandOptions(yargs).option("design-token", {+ type: "string",+ describe: "Required design token id",+ demandOption: true,+ }),+ "Required JSON file containing an array of style updates with property, value, optional breakpoint/state"+ );++export const deleteDesignTokenStylesCommandOptions = (yargs: CommonYargsArgv) =>+ requiredInputOption(+ apiCommandOptions(yargs).option("design-token", {+ type: "string",+ describe: "Required design token id",+ demandOption: true,+ }),+ "Required JSON file containing an array of style deletions with property, optional breakpoint/state"+ );++export const attachDesignTokenCommandOptions = (yargs: CommonYargsArgv) =>+ requiredInputOption(+ apiCommandOptions(yargs)+ .option("design-token", {+ type: "string",+ describe: "Required design token id",+ demandOption: true,+ })+ .option("position", {+ choices: ["before-local", "after-local"] as const,+ describe:+ "Where to place the token relative to an instance local style source",+ }),+ "Required JSON file containing an array of instance ids"+ );++export const detachDesignTokenCommandOptions = (yargs: CommonYargsArgv) =>+ requiredInputOption(+ apiCommandOptions(yargs).option("design-token", {+ type: "string",+ describe: "Required design token id",+ demandOption: true,+ }),+ "Required JSON file containing an array of instance ids"+ );++export const extractDesignTokenCommandOptions = (yargs: CommonYargsArgv) =>+ requiredInputOption(+ apiCommandOptions(yargs),+ "Required JSON file containing instanceIds, name, and optional removeLocalProps"+ );++export const cssVariablesCommandOptions = (yargs: CommonYargsArgv) =>+ apiCommandOptions(yargs)+ .option("filter", {+ type: "string",+ describe: "Only return CSS variables whose name contains this text",+ })+ .option("with-usage", {+ type: "boolean",+ describe: "Include how many references use each CSS variable",+ });++export const defineCssVariableCommandOptions = (yargs: CommonYargsArgv) =>+ requiredInputOption(+ apiCommandOptions(yargs).option("overwrite", {+ type: "boolean",+ describe: "Replace existing CSS variable definitions with the same name",+ }),+ "Required JSON file containing an object of CSS variable names to values"+ );++export const deleteCssVariableCommandOptions = (yargs: CommonYargsArgv) =>+ requiredInputOption(+ confirmOption(+ apiCommandOptions(yargs).option("force", {+ type: "boolean",+ describe:+ "Delete CSS variable definitions even when they are referenced",+ }),+ "Required. Confirm deleting CSS variable definitions"+ ),+ "Required JSON file containing an array of CSS variable names"+ );++export const rewriteCssVariableRefsCommandOptions = (yargs: CommonYargsArgv) =>+ requiredInputOption(+ apiCommandOptions(yargs).option("scope-regex", {+ type: "string",+ describe: "Only rewrite references in matching instance or style scopes",+ }),+ "Required JSON file containing an object that maps old CSS variable names to new names"+ );++export const scopedCommandOptions = (yargs: CommonYargsArgv) =>+ apiCommandOptions(yargs).option("scope-instance", {+ type: "string",+ describe: "Only return items scoped to this instance id",+ });++export const createVariableCommandOptions = (yargs: CommonYargsArgv) =>+ apiCommandOptions(yargs)+ .option("variable", {+ type: "string",+ describe:+ "Optional variable data source id to create; generated by Builder when omitted",+ })+ .option("scope-instance", {+ type: "string",+ describe: "Required instance id where the variable is scoped",+ demandOption: true,+ })+ .option("name", {+ type: "string",+ describe: "Required variable name used in expressions",+ demandOption: true,+ })+ .option("value-type", {+ choices: ["string", "number", "boolean", "string[]", "json"] as const,+ describe: "Required variable value type",+ demandOption: true,+ })+ .option("value", {+ type: "string",+ describe:+ "Required variable value; use JSON for json and string[] value types",+ demandOption: true,+ });++export const updateVariableCommandOptions = (yargs: CommonYargsArgv) =>+ apiCommandOptions(yargs)+ .option("variable", {+ type: "string",+ describe: "Required variable data source id to update",+ demandOption: true,+ })+ .option("scope-instance", {+ type: "string",+ describe: "Move variable scope to this instance id",+ })+ .option("name", {+ type: "string",+ describe: "Update variable name used in expressions",+ })+ .option("value-type", {+ choices: ["string", "number", "boolean", "string[]", "json"] as const,+ describe: "Variable value type when updating --value",+ })+ .option("value", {+ type: "string",+ describe: "Updated variable value; use JSON for json and string[] types",+ });++export const deleteVariableCommandOptions = (yargs: CommonYargsArgv) =>+ apiCommandOptions(yargs).option("variable", {+ type: "string",+ describe: "Required variable data source id to delete",+ demandOption: true,+ });++export const createResourceCommandOptions = (yargs: CommonYargsArgv) =>+ apiCommandOptions(yargs)+ .option("resource", {+ type: "string",+ describe:+ "Optional resource id to create; generated by Builder when omitted",+ })+ .option("input", {+ type: "string",+ describe:+ "Optional JSON file with resource fields: name, method, url, headers, searchParams, body, control",+ })+ .option("name", {+ type: "string",+ describe: "Required resource name unless provided by --input",+ })+ .option("method", {+ choices: ["get", "post", "put", "delete"] as const,+ describe: "Required HTTP method unless provided by --input",+ })+ .option("url", {+ type: "string",+ describe:+ 'Required URL expression unless provided by --input, for example "\\"https://api.example.com/items\\""',+ })+ .option("body", {+ type: "string",+ describe: "Optional request body expression",+ })+ .option("scope-instance", {+ type: "string",+ describe:+ "Expose the resource as a data variable scoped to this instance",+ })+ .option("data-source", {+ type: "string",+ describe: "Optional data source id when exposing the resource",+ })+ .option("data-source-name", {+ type: "string",+ describe:+ "Optional data variable name when exposing the resource; defaults to resource name",+ });++export const updateResourceCommandOptions = (yargs: CommonYargsArgv) =>+ apiCommandOptions(yargs)+ .option("resource", {+ type: "string",+ describe: "Required resource id to update",+ demandOption: true,+ })+ .option("input", {+ type: "string",+ describe:+ "Optional JSON file with resource fields to update: name, method, url, headers, searchParams, body, control",+ })+ .option("name", {+ type: "string",+ describe: "Update resource name",+ })+ .option("method", {+ choices: ["get", "post", "put", "delete"] as const,+ describe: "Update HTTP method",+ })+ .option("url", {+ type: "string",+ describe: "Update URL expression",+ })+ .option("body", {+ type: "string",+ describe: "Update request body expression",+ })+ .option("scope-instance", {+ type: "string",+ describe: "Move the exposed resource data variable to this instance id",+ })+ .option("data-source-name", {+ type: "string",+ describe: "Update the exposed resource data variable name",+ });++export const deleteResourceCommandOptions = (yargs: CommonYargsArgv) =>+ apiCommandOptions(yargs)+ .option("resource", {+ type: "string",+ describe: "Required resource id to delete",+ demandOption: true,+ })+ .option("force", {+ type: "boolean",+ describe:+ "Also remove direct resource prop references that point at this resource",+ });++const publishTargetOption = (yargs: CommonYargsArgv) =>+ yargs.option("target", {+ choices: ["staging", "production"] as const,+ describe: "Required publish target",+ demandOption: true,+ });++const publishDomainsOption = (yargs: CommonYargsArgv) =>+ yargs.option("domain", {+ type: "array",+ string: true,+ describe:+ "Domain to publish or unpublish. Repeat or comma-separate to target multiple domains. Defaults to the configured project domain and active verified custom domains.",+ });++export const publishCommandOptions = (yargs: CommonYargsArgv) =>+ publishDomainsOption(publishTargetOption(apiCommandOptions(yargs)))+ .option("message", {+ type: "string",+ describe: "Optional human-readable publish message",+ })+ .option("idempotency-key", {+ type: "string",+ describe: "Optional idempotency key for retrying the same publish",+ });++export const publishJobCommandOptions = (yargs: CommonYargsArgv) =>+ apiCommandOptions(yargs).option("job", {+ type: "string",+ describe: "Required publish job id returned by publish or unpublish",+ demandOption: true,+ });++export const unpublishCommandOptions = (yargs: CommonYargsArgv) =>+ confirmOption(+ publishCommandOptions(yargs),+ "Required. Confirm that selected domains should be unpublished"+ );++export const createDomainCommandOptions = (yargs: CommonYargsArgv) =>+ apiCommandOptions(yargs).option("domain", {+ type: "string",+ describe: "Required custom domain, for example example.com",+ demandOption: true,+ });++export const updateDomainCommandOptions = (yargs: CommonYargsArgv) =>+ apiCommandOptions(yargs)+ .option("domain-id", {+ type: "string",+ describe: "Required domain id to update",+ demandOption: true,+ })+ .option("input", {+ type: "string",+ describe: "Optional JSON file containing { domain }",+ })+ .option("domain", {+ type: "string",+ describe: "Set custom domain, for example www.example.com",+ });++export const deleteDomainCommandOptions = (yargs: CommonYargsArgv) =>+ confirmOption(+ apiCommandOptions(yargs).option("domain-id", {+ type: "string",+ describe: "Required domain id to delete",+ demandOption: true,+ }),+ "Required. Confirm that the domain should be removed"+ );++export const verifyDomainCommandOptions = (yargs: CommonYargsArgv) =>+ apiCommandOptions(yargs).option("domain-id", {+ type: "string",+ describe: "Required domain id to verify",+ demandOption: true,+ });++export const assetsCommandOptions = (yargs: CommonYargsArgv) =>+ apiCommandOptions(yargs)+ .option("type", {+ choices: ["image", "font"] as const,+ describe: "Only return assets of this type",+ })+ .option("sort", {+ choices: ["name", "size", "createdAt", "usage"] as const,+ describe: "Sort assets by name, size, creation time, or usage count",+ })+ .option("with-usage", {+ type: "boolean",+ describe: "Include how many build references point to each asset",+ })+ .option("cursor", {+ type: "string",+ describe: "Pagination cursor returned as nextCursor by the previous call",+ })+ .option("limit", {+ type: "number",+ describe: "Maximum number of assets to return",+ });++export const uploadAssetCommandOptions = (yargs: CommonYargsArgv) =>+ requiredInputOption(+ apiCommandOptions(yargs).option("assets-dir", {+ type: "string",+ describe: `Directory containing asset files; defaults to ${LOCAL_ASSETS_DIR}`,+ }),+ "Required JSON file containing asset descriptor: name, type, format, meta"+ );++export const uploadAssetsCommandOptions = (yargs: CommonYargsArgv) =>+ requiredInputOption(+ apiCommandOptions(yargs).option("assets-dir", {+ type: "string",+ describe: `Directory containing asset files; defaults to ${LOCAL_ASSETS_DIR}`,+ }),+ "Required JSON file containing an array of asset descriptors"+ );++export const assetCommandOptions = (yargs: CommonYargsArgv) =>+ apiCommandOptions(yargs).option("asset", {+ type: "string",+ describe: "Required asset id",+ demandOption: true,+ });++export const replaceAssetCommandOptions = (yargs: CommonYargsArgv) =>+ confirmOption(+ apiCommandOptions(yargs)+ .option("from", {+ type: "string",+ describe: "Required asset id to replace",+ demandOption: true,+ })+ .option("to", {+ type: "string",+ describe: "Required replacement asset id",+ demandOption: true,+ }),+ "Required. Confirm replacing asset references and deleting old asset"+ );++export const deleteAssetCommandOptions = (yargs: CommonYargsArgv) =>+ confirmOption(+ apiCommandOptions(yargs)+ .option("asset", {+ type: "array",+ string: true,+ describe: "Required asset ids or id prefixes to delete",+ demandOption: true,+ })+ .option("force", {+ type: "boolean",+ describe: "Delete assets even when they are referenced",+ }),+ "Required. Confirm deleting asset records"+ );++type ApiCommandOptions = {+ command: ApiCommandName;+ json?: boolean;+ include?: string[];+ version?: number;+ baseVersion?: number;+ input?: string;+ assetsDir?: string;+ page?: string;+ template?: string;+ folder?: string;+ path?: string;+ name?: string;+ variable?: string;+ resource?: string;+ dataSource?: string;+ asset?: string | string[];+ domain?: string | string[];+ domainId?: string;+ target?: "staging" | "production";+ job?: string;+ idempotencyKey?: string;+ from?: string;+ to?: string;+ designToken?: string;+ dataSourceName?: string;+ slug?: string;+ title?: string;+ description?: string;+ language?: string;+ redirect?: string;+ socialImageUrl?: string;+ socialImageAsset?: string;+ excludePageFromSearch?: boolean;+ documentType?: "html" | "xml" | "text";+ content?: string;+ status?: "301" | "302" | string;+ clearStatus?: boolean;+ old?: string;+ new?: string;+ newOld?: string;+ minWidth?: number;+ maxWidth?: number;+ condition?: string;+ clearMinWidth?: boolean;+ clearMaxWidth?: boolean;+ clearCondition?: boolean;+ authLogin?: string;+ authPassword?: string;+ message?: string;+ parentFolder?: string;+ includeFolders?: boolean;+ includePages?: boolean;+ root?: string;+ maxDepth?: number;+ topLevel?: boolean;+ component?: string;+ tag?: string;+ label?: string;+ instance?: string | string[];+ parent?: string;+ source?: string;+ insertIndex?: number;+ childIndex?: number;+ text?: string;+ childDepth?: number;+ mode?: "text" | "expression" | "all" | "append" | "prepend" | "replace";+ valueType?: "string" | "number" | "boolean" | "string[]" | "json";+ value?: string;+ method?: "get" | "post" | "put" | "delete";+ url?: string;+ body?: string;+ force?: boolean;+ confirm?: boolean;+ overwrite?: boolean;+ scopeRegex?: string;+ contains?: string;+ maxValueLength?: number;+ breakpoint?: string;+ state?: string;+ property?: string;+ propertyFilter?: string;+ includeTokens?: boolean;+ position?: "before-local" | "after-local";+ filter?: string;+ withUsage?: boolean;+ scopeInstance?: string;+ type?: "image" | "font" | "file";+ sort?: "name" | "usage" | "size" | "createdAt";+ cursor?: string;+ limit?: number;+ dryRun?: boolean;+ refresh?: boolean;+};++type ApiCommandConnection = ApiConnection & {+ headers: typeof apiCompatibilityHeaders;+};++type ResourceFieldsInput = Parameters<+ typeof httpClient.createResource+>[0]["resource"];+type ProjectSettingsInput = Pick<+ Parameters<typeof httpClient.updateProjectSettings>[0],+ "meta" | "compiler"+>;+type BreakpointInput = Pick<+ Parameters<typeof httpClient.createBreakpoint>[0],+ "id" | "label" | "minWidth" | "maxWidth" | "condition"+>;+type BreakpointUpdateInput = Parameters<+ typeof httpClient.updateBreakpoint+>[0]["values"];+type VariableValueInput = Parameters<+ typeof httpClient.createVariable+>[0]["value"];+type AppendInstanceChildrenInput = Parameters<+ typeof httpClient.appendInstance+>[0]["children"];+type MoveInstanceInput = Parameters<typeof httpClient.moveInstance>[0]["moves"];+type PropUpdatesInput = Parameters<typeof httpClient.updateProps>[0]["updates"];+type PropDeletionsInput = Parameters<+ typeof httpClient.deleteProps+>[0]["deletions"];+type PropBindingsInput = Parameters<typeof httpClient.bindProps>[0]["bindings"];+type StyleUpdatesInput = Parameters<+ typeof httpClient.updateStyleDeclarations+>[0]["updates"];+type StyleDeletionsInput = Parameters<+ typeof httpClient.deleteStyleDeclarations+>[0]["deletions"];+type StyleReplaceInput = Omit<+ Parameters<typeof httpClient.replaceStyleValues>[0],+ "authToken" | "headers" | "origin" | "projectId"+>;+type CreateDesignTokensInput = Parameters<+ typeof httpClient.createDesignTokens+>[0]["tokens"];+type UpdateDesignTokenStylesInput = Parameters<+ typeof httpClient.updateDesignTokenStyles+>[0]["updates"];+type DeleteDesignTokenStylesInput = Parameters<+ typeof httpClient.deleteDesignTokenStyles+>[0]["deletions"];+type ExtractDesignTokenInput = Omit<+ Parameters<typeof httpClient.extractDesignToken>[0],+ "authToken" | "headers" | "origin" | "projectId"+>;+type DefineCssVariablesInput = Parameters<+ typeof httpClient.defineCssVariables+>[0]["vars"];+type DeleteCssVariablesInput = Parameters<+ typeof httpClient.deleteCssVariables+>[0]["names"];+type RewriteCssVariableRefsInput = Parameters<+ typeof httpClient.rewriteCssVariableRefs+>[0]["map"];+type UploadAssetInput = Parameters<+ typeof httpClient.uploadProjectAsset+>[0]["asset"];+type UploadAssetsInput = Parameters<+ typeof httpClient.uploadProjectAssets+>[0]["assets"];+type UpdateDomainInput = Parameters<+ typeof httpClient.updateDomain+>[0]["updates"];++const requireOption = (value: string | undefined, name: string) => {+ if (value === undefined || value.length === 0) {+ throw new Error(`${name} is required.`);+ }+ return value;+};++const requireSingleOption = (+ value: string | string[] | undefined,+ name: string+) => {+ if (Array.isArray(value)) {+ return requireOption(value[0], name);+ }+ return requireOption(value, name);+};++const requireStringOption = (value: string | undefined, name: string) => {+ if (value === undefined) {+ throw new Error(`${name} is required.`);+ }+ return value;+};++const requireTrueOption = (value: boolean | undefined, name: string) => {+ if (value !== true) {+ throw new Error(`${name} is required.`);+ }+};++const rejectOptionConflict = (+ clearOption: boolean | undefined,+ clearOptionName: string,+ valueOption: unknown,+ valueOptionName: string+) => {+ if (clearOption === true && valueOption !== undefined) {+ throw new Error(+ `${clearOptionName} cannot be used with ${valueOptionName}.`+ );+ }+};++const requireNumberOption = (value: number | undefined, name: string) => {+ if (value === undefined) {+ throw new Error(`${name} is required.`);+ }+ return value;+};++const listOption = (value: string[] | undefined) =>+ value?.flatMap((item) =>+ item+ .split(",")+ .map((item) => item.trim())+ .filter((item) => item.length > 0)+ );++const listStringOption = (value: string | string[] | undefined) =>+ listOption(+ Array.isArray(value) ? value : value === undefined ? undefined : [value]+ );++const requireListOption = (+ value: string | string[] | undefined,+ name: string+) => {+ const values = listStringOption(value);+ if (values === undefined || values.length === 0) {+ throw new Error(`${name} is required.`);+ }+ return values;+};++const optionalChoice = <Choice extends string>(+ value: string | undefined,+ choices: readonly Choice[],+ name: string+): Choice | undefined => {+ if (value === undefined) {+ return;+ }+ if ((choices as readonly string[]).includes(value)) {+ return value as Choice;+ }+ throw new Error(`Unsupported ${name} "${value}".`);+};++const requiredChoice = <Choice extends string>(+ value: string | undefined,+ choices: readonly Choice[],+ name: string+) => {+ const choice = optionalChoice(value, choices, name);+ if (choice === undefined) {+ throw new Error(`${name} is required.`);+ }+ return choice;+};++const designTokenSortOption = (+ value: ApiCommandOptions["sort"]+): "name" | "usage" | undefined =>+ optionalChoice(value, ["name", "usage"], "design token sort");++const assetListTypeOption = (+ value: ApiCommandOptions["type"]+): "image" | "font" | undefined =>+ optionalChoice(value, ["image", "font"], "asset list type");++const publishTargetValue = (+ value: ApiCommandOptions["target"]+): "staging" | "production" =>+ requiredChoice(value, ["staging", "production"], "--target");++const textUpdateModeOption = (+ value: ApiCommandOptions["mode"]+): "text" | "expression" | undefined =>+ optionalChoice(value, ["text", "expression"], "text update mode");++const textListModeOption = (+ value: ApiCommandOptions["mode"]+): "text" | "expression" | "all" | undefined =>+ optionalChoice(value, ["text", "expression", "all"], "text list mode");++const appendInstanceModeOption = (+ value: ApiCommandOptions["mode"]+): "append" | "prepend" | "replace" | undefined =>+ optionalChoice(+ value,+ ["append", "prepend", "replace"],+ "append instance mode"+ );++const readJsonFile = async (+ dependencies: ApiCommandDependencies,+ path: string | undefined,+ name: string+) => {+ return JSON.parse(+ await dependencies.readFile(requireOption(path, name), "utf-8")+ ) as unknown;+};++const readOptionalJsonObject = async (+ dependencies: ApiCommandDependencies,+ path: string | undefined+) => {+ if (path === undefined) {+ return {};+ }+ const value = await readJsonFile(dependencies, path, "--input");+ if (typeof value !== "object" || value === null || Array.isArray(value)) {+ throw new Error("--input must contain a JSON object.");+ }+ return value as Record<string, unknown>;+};++const readJsonArray = async (+ dependencies: ApiCommandDependencies,+ path: string | undefined,+ name: string+) => {+ const value = await readJsonFile(dependencies, path, name);+ if (Array.isArray(value) === false) {+ throw new Error(`${name} must contain a JSON array.`);+ }+ return value;+};++const readInputObject = async <Value>(+ dependencies: ApiCommandDependencies,+ options: ApiCommandOptions+) => (await readOptionalJsonObject(dependencies, options.input)) as Value;++const readInputArray = async <Value>(+ dependencies: ApiCommandDependencies,+ options: ApiCommandOptions+) => (await readJsonArray(dependencies, options.input, "--input")) as Value;++const readAssetData =+ (dependencies: ApiCommandDependencies, assetsDirectory?: string) =>+ async (asset: { name: string }) =>+ (await dependencies.readFile(+ getLocalAssetPath(asset.name, assetsDirectory)+ )) as unknown as ArrayBufferView<ArrayBuffer>;++const parseVariableValue = (+ type: ApiCommandOptions["valueType"],+ value: string | undefined+): VariableValueInput => {+ const valueType = requireOption(type, "--value-type");+ const rawValue = requireStringOption(value, "--value");+ if (valueType === "string") {+ return { type: valueType, value: rawValue };+ }+ if (valueType === "number") {+ const number = Number(rawValue);+ if (Number.isFinite(number) === false) {+ throw new Error("--value must be a finite number.");+ }+ return { type: valueType, value: number };+ }+ if (valueType === "boolean") {+ if (rawValue !== "true" && rawValue !== "false") {+ throw new Error('--value must be "true" or "false".');+ }+ return { type: valueType, value: rawValue === "true" };+ }+ const parsed = JSON.parse(rawValue) as unknown;+ if (valueType === "string[]") {+ if (+ Array.isArray(parsed) === false ||+ parsed.every((item) => typeof item === "string") === false+ ) {+ throw new Error("--value must be a JSON array of strings.");+ }+ return { type: valueType, value: parsed };+ }+ return { type: "json", value: parsed };+};++const parseOptionalVariableValue = (+ options: ApiCommandOptions+): VariableValueInput | undefined => {+ if (options.value === undefined && options.valueType === undefined) {+ return;+ }+ if (options.value === undefined || options.valueType === undefined) {+ throw new Error("--value and --value-type must be provided together.");+ }+ return parseVariableValue(options.valueType, options.value);+};++const getResourceFields = async (+ dependencies: ApiCommandDependencies,+ options: ApiCommandOptions,+ requireComplete: boolean+) => {+ const input = await readOptionalJsonObject(dependencies, options.input);+ const fields: Record<string, unknown> = {+ ...input,+ name: options.name ?? input.name,+ method: options.method ?? input.method,+ url: options.url ?? input.url,+ body: options.body ?? input.body,+ };+ if (requireComplete && fields.headers === undefined) {+ fields.headers = [];+ }+ if (requireComplete) {+ fields.name = requireOption(+ typeof fields.name === "string" ? fields.name : undefined,+ "--name"+ );+ fields.method = requireOption(+ typeof fields.method === "string" ? fields.method : undefined,+ "--method"+ );+ fields.url = requireOption(+ typeof fields.url === "string" ? fields.url : undefined,+ "--url"+ );+ }+ return fields;+};++const getPageMetaOptions = (options: ApiCommandOptions) => {+ const auth =+ options.authLogin !== undefined || options.authPassword !== undefined+ ? {+ method: "basic" as const,+ login: requireOption(options.authLogin, "--auth-login"),+ password: requireOption(options.authPassword, "--auth-password"),+ }+ : undefined;+ const meta = {+ description: options.description,+ language: options.language,+ redirect: options.redirect,+ status: options.status,+ socialImageUrl: options.socialImageUrl,+ socialImageAssetId: options.socialImageAsset,+ excludePageFromSearch: options.excludePageFromSearch,+ documentType: options.documentType,+ content: options.content,+ auth,+ };+ return Object.values(meta).some((value) => value !== undefined)+ ? meta+ : undefined;+};++const redirectStatusOption = (status: ApiCommandOptions["status"]) =>+ status === "301" || status === "302" ? status : undefined;++const getErrorCode = (error: unknown) => {+ const message = error instanceof Error ? error.message : String(error);+ const stableCode = getStableErrorCode(error);+ if (stableCode === "CONFLICT") {+ return "VERSION_CONFLICT";+ }+ if (stableCode === "UNAUTHORIZED" || stableCode === "FORBIDDEN") {+ return "UNAUTHORIZED";+ }+ if (stableCode === "BAD_REQUEST") {+ return "INVALID_ARGUMENT";+ }+ if (stableCode !== undefined) {+ return stableCode;+ }+ if (error instanceof SyntaxError) {+ return "INVALID_JSON";+ }+ if (+ message.includes("Local config file") ||+ message.includes("Project config")+ ) {+ return "NOT_INITIALIZED";+ }+ if (message.includes(" is required")) {+ return "INVALID_ARGUMENT";+ }+ if (message.includes("does not support --dry-run")) {+ return "INVALID_ARGUMENT";+ }+ if (message.includes("Invalid patch JSON")) {+ return "INVALID_PATCH";+ }+ if (message.includes("version") || message.includes("CONFLICT")) {+ return "VERSION_CONFLICT";+ }+ return "API_COMMAND_FAILED";+};++const getRetryHint = (code: string) => {+ if (code === "VERSION_CONFLICT") {+ return "Use MCP tool snapshot, read the latest build version, regenerate the patch, then retry MCP tool apply-patch.";+ }+};++const runProjectSessionCommand = async (+ command: ApiCommandName,+ input: unknown,+ connection: ApiCommandConnection,+ dependencies: ApiCommandDependencies,+ options: { dryRun?: boolean } = {}+) =>+ executeProjectSessionApiOperation({+ command,+ input,+ connection,+ createProjectSession: dependencies.createCliProjectSession,+ dryRun: options.dryRun ?? activeApiCommandDryRun,+ refresh: activeApiCommandRefresh,+ });++type ApiCommandHandler = (+ options: ApiCommandOptions,+ connection: ApiCommandConnection,+ dependencies: ApiCommandDependencies+) => Promise<unknown>;++const apiCommandHandlers = {+ whoami: async (_options, connection, dependencies) =>+ runProjectSessionCommand("whoami", {}, connection, dependencies),+ permissions: async (_options, connection, dependencies) =>+ runProjectSessionCommand("permissions", {}, connection, dependencies),+ inspect: async (_options, connection, dependencies) =>+ runProjectSessionCommand("inspect", {}, connection, dependencies),+ snapshot: async (options, connection, dependencies) => {+ const input = {+ include: listOption(options.include),+ version: options.version,+ };+ return runProjectSessionCommand(+ "snapshot",+ input,+ connection,+ dependencies+ );+ },+ "apply-patch": async (options, connection, dependencies) => {+ const patchInput = await readJsonFile(+ dependencies,+ options.input,+ "--input"+ );+ const input = {+ baseVersion: requireNumberOption(options.baseVersion, "--base-version"),+ transactions: patchInput,+ };+ return runProjectSessionCommand(+ "apply-patch",+ input,+ connection,+ dependencies+ );+ },+ "list-pages": async (options, connection, dependencies) => {+ const input = { includeFolders: options.includeFolders };+ return runProjectSessionCommand(+ "list-pages",+ input,+ connection,+ dependencies+ );+ },+ "get-page": async (options, connection, dependencies) => {+ const input = { pageId: requireOption(options.page, "--page") };+ return runProjectSessionCommand(+ "get-page",+ input,+ connection,+ dependencies+ );+ },+ "get-page-by-path": async (options, connection, dependencies) => {+ const input = { path: requireOption(options.path, "--path") };+ return runProjectSessionCommand(+ "get-page-by-path",+ input,+ connection,+ dependencies+ );+ },+ "create-page": async (options, connection, dependencies) => {+ const input = {+ pageId: options.page,+ name: requireOption(options.name, "--name"),+ path: requireOption(options.path, "--path"),+ title: options.title,+ parentFolderId: options.parentFolder,+ meta: getPageMetaOptions(options),+ };+ return runProjectSessionCommand(+ "create-page",+ input,+ connection,+ dependencies+ );+ },+ "update-page": async (options, connection, dependencies) => {+ const input = {+ pageId: requireOption(options.page, "--page"),+ values: {+ name: options.name,+ path: options.path,+ title: options.title,+ parentFolderId: options.parentFolder,+ meta: getPageMetaOptions(options),+ },+ };+ return runProjectSessionCommand(+ "update-page",+ input,+ connection,+ dependencies+ );+ },+ "get-project-settings": async (_options, connection, dependencies) =>+ runProjectSessionCommand(+ "get-project-settings",+ {},+ connection,+ dependencies+ ),+ "update-project-settings": async (options, connection, dependencies) => {+ const input = await readInputObject<ProjectSettingsInput>(+ dependencies,+ options+ );+ return runProjectSessionCommand(+ "update-project-settings",+ input,+ connection,+ dependencies+ );+ },+ "list-redirects": async (_options, connection, dependencies) =>+ runProjectSessionCommand("list-redirects", {}, connection, dependencies),+ "create-redirect": async (options, connection, dependencies) => {+ const input = {+ old: requireOption(options.old, "--old"),+ new: requireOption(options.new, "--new"),+ status: redirectStatusOption(options.status),+ };+ return runProjectSessionCommand(+ "create-redirect",+ input,+ connection,+ dependencies+ );+ },+ "update-redirect": async (options, connection, dependencies) => {+ rejectOptionConflict(+ options.clearStatus,+ "--clear-status",+ options.status,+ "--status"+ );+ const input = {+ old: requireOption(options.old, "--old"),+ values: {+ old: options.newOld,+ new: options.new,+ status:+ options.clearStatus === true+ ? null+ : redirectStatusOption(options.status),+ },+ };+ return runProjectSessionCommand(+ "update-redirect",+ input,+ connection,+ dependencies+ );+ },+ "delete-redirect": async (options, connection, dependencies) => {+ const input = { old: requireOption(options.old, "--old") };+ return runProjectSessionCommand(+ "delete-redirect",+ input,+ connection,+ dependencies+ );+ },+ "list-breakpoints": async (_options, connection, dependencies) =>+ runProjectSessionCommand("list-breakpoints", {}, connection, dependencies),+ "create-breakpoint": async (options, connection, dependencies) => {+ const input: BreakpointInput = {+ id: requireOption(options.breakpoint, "--breakpoint"),+ label: requireOption(options.label, "--label"),+ minWidth: options.minWidth,+ maxWidth: options.maxWidth,+ condition: options.condition,+ };+ return runProjectSessionCommand(+ "create-breakpoint",+ input,+ connection,+ dependencies+ );+ },+ "update-breakpoint": async (options, connection, dependencies) => {+ rejectOptionConflict(+ options.clearMinWidth,+ "--clear-min-width",+ options.minWidth,+ "--min-width"+ );+ rejectOptionConflict(+ options.clearMaxWidth,+ "--clear-max-width",+ options.maxWidth,+ "--max-width"+ );+ rejectOptionConflict(+ options.clearCondition,+ "--clear-condition",+ options.condition,+ "--condition"+ );+ const values: BreakpointUpdateInput = {+ label: options.label,+ minWidth: options.clearMinWidth === true ? null : options.minWidth,+ maxWidth: options.clearMaxWidth === true ? null : options.maxWidth,+ condition: options.clearCondition === true ? null : options.condition,+ };+ const input = {+ breakpointId: requireOption(options.breakpoint, "--breakpoint"),+ values,+ };+ return runProjectSessionCommand(+ "update-breakpoint",+ input,+ connection,+ dependencies+ );+ },+ "delete-breakpoint": async (options, connection, dependencies) => {+ requireTrueOption(options.confirm, "--confirm");+ const input = {+ breakpointId: requireOption(options.breakpoint, "--breakpoint"),+ };+ return runProjectSessionCommand(+ "delete-breakpoint",+ input,+ connection,+ dependencies+ );+ },+ "delete-page": async (options, connection, dependencies) => {+ const input = { pageId: requireOption(options.page, "--page") };+ return runProjectSessionCommand(+ "delete-page",+ input,+ connection,+ dependencies+ );+ },+ "duplicate-page": async (options, connection, dependencies) => {+ const input = {+ pageId: requireOption(options.page, "--page"),+ parentFolderId: options.parentFolder,+ name: options.name,+ path: options.path,+ };+ return runProjectSessionCommand(+ "duplicate-page",+ input,+ connection,+ dependencies+ );+ },+ "list-page-templates": async (_options, connection, dependencies) =>+ runProjectSessionCommand(+ "list-page-templates",+ {},+ connection,+ dependencies+ ),+ "create-page-from-template": async (options, connection, dependencies) => {+ const input = {+ templateId: requireOption(options.template, "--template"),+ parentFolderId: options.parentFolder,+ name: requireOption(options.name, "--name"),+ path: requireOption(options.path, "--path"),+ };+ return runProjectSessionCommand(+ "create-page-from-template",+ input,+ connection,+ dependencies+ );+ },+ "list-folders": async (options, connection, dependencies) => {+ const input = { includePages: options.includePages };+ return runProjectSessionCommand(+ "list-folders",+ input,+ connection,+ dependencies+ );+ },+ "create-folder": async (options, connection, dependencies) => {+ const input = {+ folderId: options.folder,+ name: requireOption(options.name, "--name"),+ slug: requireOption(options.slug, "--slug"),+ parentFolderId: options.parentFolder,+ };+ return runProjectSessionCommand(+ "create-folder",+ input,+ connection,+ dependencies+ );+ },+ "update-folder": async (options, connection, dependencies) => {+ const input = {+ folderId: requireOption(options.folder, "--folder"),+ values: {+ name: options.name,+ slug: options.slug,+ parentFolderId: options.parentFolder,+ },+ };+ return runProjectSessionCommand(+ "update-folder",+ input,+ connection,+ dependencies+ );+ },+ "delete-folder": async (options, connection, dependencies) => {+ const input = { folderId: requireOption(options.folder, "--folder") };+ return runProjectSessionCommand(+ "delete-folder",+ input,+ connection,+ dependencies+ );+ },+ "list-instances": async (options, connection, dependencies) => {+ const input = {+ pageId: options.page,+ pagePath: options.path,+ rootInstanceId: options.root,+ maxDepth: options.maxDepth,+ topLevelOnly: options.topLevel,+ component: options.component,+ tag: options.tag,+ labelContains: options.label,+ };+ return runProjectSessionCommand(+ "list-instances",+ input,+ connection,+ dependencies+ );+ },+ "inspect-instance": async (options, connection, dependencies) => {+ const input = {+ instanceId: requireSingleOption(options.instance, "--instance"),+ include: listOption(options.include),+ childDepth: options.childDepth,+ };+ return runProjectSessionCommand(+ "inspect-instance",+ input,+ connection,+ dependencies+ );+ },+ "append-instance": async (options, connection, dependencies) => {+ const input = {+ parentInstanceId: requireOption(options.parent, "--parent"),+ mode: appendInstanceModeOption(options.mode),+ insertIndex: options.insertIndex,+ children: await readInputArray<AppendInstanceChildrenInput>(+ dependencies,+ options+ ),+ };+ return runProjectSessionCommand(+ "append-instance",+ input,+ connection,+ dependencies+ );+ },+ "move-instance": async (options, connection, dependencies) => {+ const input = {+ moves: await readInputArray<MoveInstanceInput>(dependencies, options),+ };+ return runProjectSessionCommand(+ "move-instance",+ input,+ connection,+ dependencies+ );+ },+ "clone-instance": async (options, connection, dependencies) => {+ const input = {+ sourceInstanceId: requireOption(options.source, "--source"),+ targetParentInstanceId: options.parent,+ insertIndex: options.insertIndex,+ };+ return runProjectSessionCommand(+ "clone-instance",+ input,+ connection,+ dependencies+ );+ },+ "delete-instance": async (options, connection, dependencies) => {+ const input = {+ instanceIds: requireListOption(options.instance, "--instance"),+ };+ return runProjectSessionCommand(+ "delete-instance",+ input,+ connection,+ dependencies+ );+ },+ "update-props": async (options, connection, dependencies) => {+ const input = {+ updates: await readInputArray<PropUpdatesInput>(dependencies, options),+ };+ return runProjectSessionCommand(+ "update-props",+ input,+ connection,+ dependencies+ );+ },+ "delete-props": async (options, connection, dependencies) => {+ const input = {+ deletions: await readInputArray<PropDeletionsInput>(+ dependencies,+ options+ ),+ };+ return runProjectSessionCommand(+ "delete-props",+ input,+ connection,+ dependencies+ );+ },+ "bind-props": async (options, connection, dependencies) => {+ const input = {+ bindings: await readInputArray<PropBindingsInput>(dependencies, options),+ };+ return runProjectSessionCommand(+ "bind-props",+ input,+ connection,+ dependencies+ );+ },+ "list-texts": async (options, connection, dependencies) => {+ const input = {+ pageId: options.page,+ pagePath: options.path,+ instanceId:+ typeof options.instance === "string" ? options.instance : undefined,+ mode: textListModeOption(options.mode),+ contains: options.contains,+ maxValueLength: options.maxValueLength,+ };+ return runProjectSessionCommand(+ "list-texts",+ input,+ connection,+ dependencies+ );+ },+ "update-text": async (options, connection, dependencies) => {+ const input = {+ instanceId: requireSingleOption(options.instance, "--instance"),+ childIndex: requireNumberOption(options.childIndex, "--child-index"),+ text: requireStringOption(options.text, "--text"),+ mode: textUpdateModeOption(options.mode),+ };+ return runProjectSessionCommand(+ "update-text",+ input,+ connection,+ dependencies+ );+ },+ "get-styles": async (options, connection, dependencies) => {+ const input = {+ instanceIds:+ typeof options.instance === "string" ? [options.instance] : undefined,+ pageId: options.page,+ pagePath: options.path,+ breakpoint: options.breakpoint,+ state: options.state,+ property: options.property,+ propertyFilter: options.propertyFilter,+ includeTokens: options.includeTokens,+ };+ return runProjectSessionCommand(+ "get-styles",+ input,+ connection,+ dependencies+ );+ },+ "update-styles": async (options, connection, dependencies) => {+ const input = {+ updates: await readInputArray<StyleUpdatesInput>(dependencies, options),+ };+ return runProjectSessionCommand(+ "update-styles",+ input,+ connection,+ dependencies+ );+ },+ "delete-styles": async (options, connection, dependencies) => {+ const input = {+ deletions: await readInputArray<StyleDeletionsInput>(+ dependencies,+ options+ ),+ };+ return runProjectSessionCommand(+ "delete-styles",+ input,+ connection,+ dependencies+ );+ },+ "replace-styles": async (options, connection, dependencies) => {+ const input = await readInputObject<StyleReplaceInput>(+ dependencies,+ options+ );+ return runProjectSessionCommand(+ "replace-styles",+ input,+ connection,+ dependencies+ );+ },+ "list-design-tokens": async (options, connection, dependencies) => {+ const input = {+ filter: options.filter,+ withUsage: options.withUsage,+ sort: designTokenSortOption(options.sort),+ };+ return runProjectSessionCommand(+ "list-design-tokens",+ input,+ connection,+ dependencies+ );+ },+ "create-design-token": async (options, connection, dependencies) => {+ const input = {+ tokens: await readInputArray<CreateDesignTokensInput>(+ dependencies,+ options+ ),+ };+ return runProjectSessionCommand(+ "create-design-token",+ input,+ connection,+ dependencies+ );+ },+ "update-design-token-styles": async (options, connection, dependencies) => {+ const input = {+ designTokenId: requireOption(options.designToken, "--design-token"),+ updates: await readInputArray<UpdateDesignTokenStylesInput>(+ dependencies,+ options+ ),+ };+ return runProjectSessionCommand(+ "update-design-token-styles",+ input,+ connection,+ dependencies+ );+ },+ "delete-design-token-styles": async (options, connection, dependencies) => {+ const input = {+ designTokenId: requireOption(options.designToken, "--design-token"),+ deletions: await readInputArray<DeleteDesignTokenStylesInput>(+ dependencies,+ options+ ),+ };+ return runProjectSessionCommand(+ "delete-design-token-styles",+ input,+ connection,+ dependencies+ );+ },+ "attach-design-token": async (options, connection, dependencies) => {+ const input = {+ designTokenId: requireOption(options.designToken, "--design-token"),+ instanceIds: await readInputArray<string[]>(dependencies, options),+ position: options.position,+ };+ return runProjectSessionCommand(+ "attach-design-token",+ input,+ connection,+ dependencies+ );+ },+ "detach-design-token": async (options, connection, dependencies) => {+ const input = {+ designTokenId: requireOption(options.designToken, "--design-token"),+ instanceIds: await readInputArray<string[]>(dependencies, options),+ };+ return runProjectSessionCommand(+ "detach-design-token",+ input,+ connection,+ dependencies+ );+ },+ "extract-design-token": async (options, connection, dependencies) => {+ const input = await readInputObject<ExtractDesignTokenInput>(+ dependencies,+ options+ );+ return runProjectSessionCommand(+ "extract-design-token",+ input,+ connection,+ dependencies+ );+ },+ "list-css-variables": async (options, connection, dependencies) => {+ const input = {+ filter: options.filter,+ withUsage: options.withUsage,+ };+ return runProjectSessionCommand(+ "list-css-variables",+ input,+ connection,+ dependencies+ );+ },+ "define-css-variable": async (options, connection, dependencies) => {+ const input = {+ vars: await readInputObject<DefineCssVariablesInput>(+ dependencies,+ options+ ),+ overwrite: options.overwrite,+ };+ return runProjectSessionCommand(+ "define-css-variable",+ input,+ connection,+ dependencies+ );+ },+ "delete-css-variable": async (options, connection, dependencies) => {+ requireTrueOption(options.confirm, "--confirm");+ const input = {+ names: await readInputArray<DeleteCssVariablesInput>(+ dependencies,+ options+ ),+ force: options.force,+ };+ return runProjectSessionCommand(+ "delete-css-variable",+ input,+ connection,+ dependencies+ );+ },+ "rewrite-css-variable-refs": async (options, connection, dependencies) => {+ const input = {+ map: await readInputObject<RewriteCssVariableRefsInput>(+ dependencies,+ options+ ),+ scopeRegex: options.scopeRegex,+ };+ return runProjectSessionCommand(+ "rewrite-css-variable-refs",+ input,+ connection,+ dependencies+ );+ },+ "list-variables": async (options, connection, dependencies) => {+ const input = { scopeInstanceId: options.scopeInstance };+ return runProjectSessionCommand(+ "list-variables",+ input,+ connection,+ dependencies+ );+ },+ "create-variable": async (options, connection, dependencies) => {+ const input = {+ dataSourceId: options.variable,+ scopeInstanceId: requireOption(options.scopeInstance, "--scope-instance"),+ name: requireOption(options.name, "--name"),+ value: parseVariableValue(options.valueType, options.value),+ };+ return runProjectSessionCommand(+ "create-variable",+ input,+ connection,+ dependencies+ );+ },+ "update-variable": async (options, connection, dependencies) => {+ const input = {+ dataSourceId: requireOption(options.variable, "--variable"),+ values: {+ scopeInstanceId: options.scopeInstance,+ name: options.name,+ value: parseOptionalVariableValue(options),+ },+ };+ return runProjectSessionCommand(+ "update-variable",+ input,+ connection,+ dependencies+ );+ },+ "delete-variable": async (options, connection, dependencies) => {+ const input = {+ dataSourceId: requireOption(options.variable, "--variable"),+ };+ return runProjectSessionCommand(+ "delete-variable",+ input,+ connection,+ dependencies+ );+ },+ "list-resources": async (options, connection, dependencies) => {+ const input = { scopeInstanceId: options.scopeInstance };+ return runProjectSessionCommand(+ "list-resources",+ input,+ connection,+ dependencies+ );+ },+ "create-resource": async (options, connection, dependencies) => {+ const input = {+ resourceId: options.resource,+ resource: (await getResourceFields(+ dependencies,+ options,+ true+ )) as ResourceFieldsInput,+ dataSourceId: options.dataSource,+ scopeInstanceId: options.scopeInstance,+ dataSourceName: options.dataSourceName,+ };+ return runProjectSessionCommand(+ "create-resource",+ input,+ connection,+ dependencies+ );+ },+ "update-resource": async (options, connection, dependencies) => {+ const input = {+ resourceId: requireOption(options.resource, "--resource"),+ values: (await getResourceFields(+ dependencies,+ options,+ false+ )) as Partial<ResourceFieldsInput>,+ dataSourceName: options.dataSourceName,+ scopeInstanceId: options.scopeInstance,+ };+ return runProjectSessionCommand(+ "update-resource",+ input,+ connection,+ dependencies+ );+ },+ "delete-resource": async (options, connection, dependencies) => {+ const input = {+ resourceId: requireOption(options.resource, "--resource"),+ force: options.force,+ };+ return runProjectSessionCommand(+ "delete-resource",+ input,+ connection,+ dependencies+ );+ },+ publish: async (options, connection, dependencies) => {+ const input = {+ target: publishTargetValue(options.target),+ domains: listStringOption(options.domain),+ message: options.message,+ idempotencyKey: options.idempotencyKey,+ };+ return runProjectSessionCommand("publish", input, connection, dependencies);+ },+ "list-publishes": async (_options, connection, dependencies) =>+ runProjectSessionCommand("list-publishes", {}, connection, dependencies),+ "get-publish-job": async (options, connection, dependencies) => {+ const input = { jobId: requireOption(options.job, "--job") };+ return runProjectSessionCommand(+ "get-publish-job",+ input,+ connection,+ dependencies+ );+ },+ unpublish: async (options, connection, dependencies) => {+ requireTrueOption(options.confirm, "--confirm");+ const input = {+ target: publishTargetValue(options.target),+ domains: listStringOption(options.domain),+ message: options.message,+ idempotencyKey: options.idempotencyKey,+ };+ return runProjectSessionCommand(+ "unpublish",+ input,+ connection,+ dependencies+ );+ },+ "list-domains": async (_options, connection, dependencies) =>+ runProjectSessionCommand("list-domains", {}, connection, dependencies),+ "create-domain": async (options, connection, dependencies) => {+ const input = { domain: requireSingleOption(options.domain, "--domain") };+ return runProjectSessionCommand(+ "create-domain",+ input,+ connection,+ dependencies+ );+ },+ "update-domain": async (options, connection, dependencies) => {+ const input = {+ domainId: requireOption(options.domainId, "--domain-id"),+ updates: {+ ...(await readInputObject<UpdateDomainInput>(dependencies, options)),+ domain: typeof options.domain === "string" ? options.domain : undefined,+ },+ };+ return runProjectSessionCommand(+ "update-domain",+ input,+ connection,+ dependencies+ );+ },+ "delete-domain": async (options, connection, dependencies) => {+ requireTrueOption(options.confirm, "--confirm");+ const input = { domainId: requireOption(options.domainId, "--domain-id") };+ return runProjectSessionCommand(+ "delete-domain",+ input,+ connection,+ dependencies+ );+ },+ "verify-domain": async (options, connection, dependencies) => {+ const input = { domainId: requireOption(options.domainId, "--domain-id") };+ return runProjectSessionCommand(+ "verify-domain",+ input,+ connection,+ dependencies+ );+ },+ "list-assets": async (options, connection, dependencies) => {+ const input = {+ type: assetListTypeOption(options.type),+ sort: options.sort,+ withUsage: options.withUsage,+ cursor: options.cursor,+ limit: options.limit,+ };+ return runProjectSessionCommand(+ "list-assets",+ input,+ connection,+ dependencies+ );+ },+ "upload-asset": async (options, connection, dependencies) => {+ const input = {+ asset: await readInputObject<UploadAssetInput>(dependencies, options),+ readAssetData: readAssetData(dependencies, options.assetsDir),+ };+ return runProjectSessionCommand(+ "upload-asset",+ input,+ connection,+ dependencies+ );+ },+ "upload-assets": async (options, connection, dependencies) => {+ const input = {+ assets: await readInputArray<UploadAssetsInput>(dependencies, options),+ readAssetData: readAssetData(dependencies, options.assetsDir),+ };+ return runProjectSessionCommand(+ "upload-assets",+ input,+ connection,+ dependencies+ );+ },+ "find-asset-usage": async (options, connection, dependencies) => {+ const input = { assetId: requireSingleOption(options.asset, "--asset") };+ return runProjectSessionCommand(+ "find-asset-usage",+ input,+ connection,+ dependencies+ );+ },+ "replace-asset": async (options, connection, dependencies) => {+ requireTrueOption(options.confirm, "--confirm");+ const input = {+ fromAssetId: requireOption(options.from, "--from"),+ toAssetId: requireOption(options.to, "--to"),+ };+ return runProjectSessionCommand(+ "replace-asset",+ input,+ connection,+ dependencies+ );+ },+ "delete-asset": async (options, connection, dependencies) => {+ requireTrueOption(options.confirm, "--confirm");+ const input = {+ assetIdsOrPrefixes: requireListOption(options.asset, "--asset"),+ force: options.force,+ };+ return runProjectSessionCommand(+ "delete-asset",+ input,+ connection,+ dependencies+ );+ },+} satisfies Record<ApiCommandName, ApiCommandHandler>;++export const apiCommand = async (+ options: ApiCommandOptions,+ dependencies = defaultDependencies+) => {+ const start = Date.now();+ let projectId: string | undefined;+ try {+ if (options.json !== true) {+ throw new Error(`${options.command} currently requires --json.`);+ }++ const connection = await resolveApiConnection(dependencies);+ projectId = connection.projectId;+ const apiConnection = {+ ...connection,+ headers: apiCompatibilityHeaders,+ };++ const query = apiCommandHandlers[options.command];+ const previousDryRun = activeApiCommandDryRun;+ const previousRefresh = activeApiCommandRefresh;+ activeApiCommandDryRun = options.dryRun === true;+ activeApiCommandRefresh = options.refresh === true;+ const response = await query(options, apiConnection, dependencies).finally(+ () => {+ activeApiCommandDryRun = previousDryRun;+ activeApiCommandRefresh = previousRefresh;+ }+ );+ const session = isProjectSessionEnvelope(response)+ ? getProjectSessionMeta(response)+ : undefined;+ printJson({+ ok: true,+ data: isProjectSessionEnvelope(response) ? response.result : response,+ meta: {+ command: options.command,+ projectId: connection.projectId,+ durationMs: Date.now() - start,+ ...(session === undefined ? {} : { session }),+ },+ });+ } catch (error) {+ const message = error instanceof Error ? error.message : String(error);+ if (options.json === true) {+ const code = getErrorCode(error);+ printJson({+ ok: false,+ error: {+ code,+ message,+ retry: getRetryHint(code),+ },+ meta: {+ command: options.command,+ projectId,+ durationMs: Date.now() - start,+ },+ });+ } else {+ console.error(message);+ }+ throw new HandledCliError();+ }+};diff --git a/packages/cli/src/commands/api-guardrails.test.ts b/packages/cli/src/commands/api-guardrails.test.tsnew file mode 100644index 0000000000..33fbba13c8--- /dev/null+++ b/packages/cli/src/commands/api-guardrails.test.ts@@ -0,0 +1,44 @@+import { readFile, readdir } from "node:fs/promises";+import { join } from "node:path";+import { expect, test } from "vitest";++const commandsDir = new URL(".", import.meta.url);++const readCommandFiles = async () => {+ const names = await readdir(commandsDir);+ const files = await Promise.all(+ names+ .filter((name) => name.endsWith(".ts"))+ .filter((name) => name !== "api-guardrails.test.ts")+ .map(async (name) => ({+ name,+ content: await readFile(join(commandsDir.pathname, name), "utf-8"),+ }))+ );+ return files;+};++test("api cli command layer does not import low-level trpc clients", async () => {+ const files = await readCommandFiles();+ for (const file of files) {+ expect(file.content, file.name).not.toMatch(/@trpc\/client|httpBatchLink/);+ }+});++test("api cli command tests do not mock modules", async () => {+ const files = await readCommandFiles();+ for (const file of files) {+ expect(file.content, file.name).not.toMatch(+ /\bvi\.mock\(|\bjest\.mock\(|unstable_mockModule|mockModule/+ );+ }+});++test("api command execution does not construct builder patch payloads", async () => {+ const content = await readFile(+ join(commandsDir.pathname, "api-command.ts"),+ "utf-8"+ );+ expect(content).not.toMatch(/\bnamespace:\s*["']/);+ expect(content).not.toMatch(/\bpatches:\s*\[/);+});diff --git a/packages/cli/src/commands/api.ts b/packages/cli/src/commands/api.tsindex 0cd25d30cd..6db420f5ff 100644--- a/packages/cli/src/commands/api.ts+++ b/packages/cli/src/commands/api.ts@@ -1,31 +1,22 @@import { spinner } from "@clack/prompts";import {- apiClientHeader,- apiClientVersionHeader,- getApiCompatibilityPayload,-} from "@webstudio-is/trpc-interface/api-compatibility";+ createApiClientHeaders,+ getApiCompatibilityMessage,+} from "@webstudio-is/http-client";import packageJson from "../../package.json";-export const apiCompatibilityHeaders = {- [apiClientHeader]: "cli",- [apiClientVersionHeader]: packageJson.version,-};+export const apiCompatibilityHeaders = createApiClientHeaders({+ name: "cli",+ version: packageJson.version,+});const updateCliCommand = "npm install -g webstudio@latest";const getCliCompatibilityMessage = (error: unknown, command: string) => {- const payload = getApiCompatibilityPayload(error);- if (payload?.action.type !== "updateCli") {- return;- }-- return `${payload.message}--Update the CLI with:- ${updateCliCommand}--Or run the latest version once with:- npx webstudio@latest ${command}`;+ return getApiCompatibilityMessage(error, {+ updateCommand: updateCliCommand,+ runLatestCommand: `npx webstudio@latest ${command}`,+ });};export const stopSpinnerWithError = (diff --git a/packages/cli/src/commands/import.test.ts b/packages/cli/src/commands/import.test.tsdeleted file mode 100644index 3d2eeebd30..0000000000--- a/packages/cli/src/commands/import.test.ts+++ /dev/null@@ -1,662 +0,0 @@-import { afterEach, beforeEach, expect, test, vi } from "vitest";-import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";-import { join } from "node:path";-import { tmpdir } from "node:os";-import makeCLI from "yargs";-import { createApiCompatibilityPayload } from "@webstudio-is/trpc-interface/api-compatibility";-import { bundleVersion } from "@webstudio-is/protocol";-import {- createImageAssetFixture,- createPublishedProjectBundleFixture,-} from "@webstudio-is/protocol/fixtures";-import { loadJSONFile } from "../fs-utils";-import {- createAuthConfigContentFromBundle,- LOCAL_AUTH_FILE,-} from "../auth-config";-import { importOptions, importProject } from "./import";-import type { CommonYargsArgv } from "./yargs-types";--const originalCwd = process.cwd();-let tempDir: string;-const destinationProjectId = "090e6e14-ae50-4b2e-bd22-71733cec05bb";-const destinationShareLink = `https://p-${destinationProjectId}-dot-example.com/?authToken=token-1`;-const destinationRequest = {- projectId: destinationProjectId,- authToken: "token-1",- origin: "https://example.com",- headers: expect.objectContaining({- "x-webstudio-client": "cli",- }),-};-const imageAsset = createImageAssetFixture({- size: 5,- meta: { width: 1, height: 1 },-});-const log = {- info: vi.fn(),-};-const indicator = {- start: vi.fn(),- message: vi.fn(),- stop: vi.fn(),-};-const checkProjectBuildPermission = vi.fn();-const importProjectBundle = vi.fn();-const uploadAssetFiles = vi.fn();-const promptText = vi.fn();-const dependencies = {- checkProjectBuildPermission,- importProjectBundle,- uploadAssetFiles,- loadJSONFile,- text: promptText,- isInteractive: false,- log,- spinner: () => indicator,-};--const createSyncedData = (data = {}) =>- createPublishedProjectBundleFixture({- assets: [],- projectDomain: "example.com",- ...data,- });--const writeSyncedData = async (data = {}) => {- const syncedData = createSyncedData(data);- await writeFile(".webstudio/data.json", JSON.stringify(syncedData), "utf8");- return syncedData;-};--beforeEach(async () => {- tempDir = await mkdtemp(join(tmpdir(), "webstudio-import-"));- process.chdir(tempDir);- await mkdir(".webstudio", { recursive: true });- checkProjectBuildPermission.mockResolvedValue(undefined);- importProjectBundle.mockResolvedValue({ version: 1 });- uploadAssetFiles.mockResolvedValue(undefined);- promptText.mockResolvedValue(destinationShareLink);- checkProjectBuildPermission.mockClear();- uploadAssetFiles.mockClear();- promptText.mockClear();- log.info.mockClear();- indicator.start.mockClear();- indicator.message.mockClear();- indicator.stop.mockClear();-});--afterEach(async () => {- process.chdir(originalCwd);- await rm(tempDir, { recursive: true, force: true });- vi.clearAllMocks();-});--test("imports local synced data into destination project", async () => {- await writeSyncedData();-- await importProject({ to: destinationShareLink }, dependencies);-- expect(checkProjectBuildPermission).toHaveBeenCalledWith(destinationRequest);- expect(importProjectBundle).toHaveBeenCalledWith({- ...destinationRequest,- data: createSyncedData(),- ignoreVersionCheck: undefined,- });- expect(indicator.stop).toHaveBeenCalledWith("Project imported successfully");- expect(indicator.message).toHaveBeenCalledWith(- "Reading .webstudio/data.json"- );- expect(log.info).toHaveBeenCalledWith("Read .webstudio/data.json");- expect(log.info).toHaveBeenCalledWith(- `Destination project: ${destinationProjectId}`- );- expect(log.info).toHaveBeenCalledWith(- "Destination origin: https://example.com"- );- expect(indicator.message).toHaveBeenCalledWith(- "Checking destination build permission"- );- expect(indicator.message).toHaveBeenCalledWith(- `Waiting for API response while importing into ${destinationProjectId}`- );-});--test("prompts for destination share link when running interactively", async () => {- await writeSyncedData();-- await importProject(- {},- {- ...dependencies,- isInteractive: true,- }- );-- expect(promptText).toHaveBeenCalledWith({- message: "Please paste a destination share link with build permissions",- validate: expect.any(Function),- });- expect(checkProjectBuildPermission).toHaveBeenCalledWith(- expect.objectContaining({- projectId: destinationProjectId,- authToken: "token-1",- origin: "https://example.com",- })- );- expect(importProjectBundle).toHaveBeenCalledWith(- expect.objectContaining({- projectId: destinationProjectId,- })- );-});--test("stops when destination share link is missing in non-interactive mode", async () => {- const loadJSONFile = vi.fn();-- await expect(- importProject(- {},- {- ...dependencies,- loadJSONFile,- }- )- ).rejects.toThrow("Handled CLI error");-- expect(loadJSONFile).not.toHaveBeenCalled();- expect(promptText).not.toHaveBeenCalled();- expect(checkProjectBuildPermission).not.toHaveBeenCalled();- expect(importProjectBundle).not.toHaveBeenCalled();- expect(indicator.stop).toHaveBeenCalledWith(- "Please specify a destination share link with --to",- 2- );-});--test("requires destination share link before running non-interactive command", async () => {- const parser = importOptions(- makeCLI([])- .exitProcess(false)- .fail((message, error) => {- throw error ?? new Error(message);- }) as CommonYargsArgv- );-- expect(() => parser.parse([])).toThrow(- "Please specify a destination share link with --to"- );-});--test("parses skip-assets flag", async () => {- const parser = importOptions(- makeCLI([])- .exitProcess(false)- .fail((message, error) => {- throw error ?? new Error(message);- }) as CommonYargsArgv- );-- expect(- parser.parse(["--to", destinationShareLink, "--skip-assets"])- ).toMatchObject({- skipAssets: true,- });-});--test("stops with sync instruction when local data is missing", async () => {- await expect(- importProject(- {- to: destinationShareLink,- },- dependencies- )- ).rejects.toThrow("Handled CLI error");-- expect(importProjectBundle).not.toHaveBeenCalled();- expect(checkProjectBuildPermission).not.toHaveBeenCalled();- expect(indicator.stop).toHaveBeenCalledWith(- "Project bundle is missing. Please run webstudio sync before importing.",- 2- );-});--test("stops with invalid data message when local data is malformed JSON", async () => {- await writeFile(".webstudio/data.json", "{", "utf8");-- await expect(- importProject(- {- to: destinationShareLink,- },- dependencies- )- ).rejects.toThrow("Handled CLI error");-- expect(importProjectBundle).not.toHaveBeenCalled();- expect(checkProjectBuildPermission).not.toHaveBeenCalled();- expect(indicator.stop).toHaveBeenCalledWith(- "Project bundle is invalid. Please run webstudio sync before importing.",- 2- );-});--test("does not prompt for destination when local data is missing", async () => {- await expect(- importProject(- {},- {- ...dependencies,- isInteractive: true,- }- )- ).rejects.toThrow("Handled CLI error");-- expect(promptText).not.toHaveBeenCalled();- expect(checkProjectBuildPermission).not.toHaveBeenCalled();- expect(importProjectBundle).not.toHaveBeenCalled();- expect(indicator.stop).toHaveBeenCalledWith(- "Project bundle is missing. Please run webstudio sync before importing.",- 2- );-});--test("stops before API request when local data is from old format", async () => {- await writeSyncedData({ bundleVersion: undefined });-- await expect(- importProject(- {- to: destinationShareLink,- },- dependencies- )- ).rejects.toThrow("Handled CLI error");-- expect(importProjectBundle).not.toHaveBeenCalled();- expect(checkProjectBuildPermission).not.toHaveBeenCalled();- expect(indicator.stop).toHaveBeenCalledWith(- `Project bundle format is incompatible. Expected version ${bundleVersion}, received missing. Sync with a compatible API/CLI version and retry, or pass --ignore-version-check if you know the source and target data formats are compatible.`,- 2- );-});--test("imports old local data when version check is explicitly ignored", async () => {- await writeSyncedData({ bundleVersion: undefined });-- await importProject(- {- to: destinationShareLink,- ignoreVersionCheck: true,- },- dependencies- );-- expect(importProjectBundle).toHaveBeenCalledWith(- expect.objectContaining({- ignoreVersionCheck: true,- data: createSyncedData({ bundleVersion: undefined }),- })- );- expect(indicator.stop).toHaveBeenCalledWith("Project imported successfully");-});--test("stops before API request when ignored-version data is missing assets", async () => {- await writeSyncedData({- assets: undefined,- bundleVersion: undefined,- });-- await expect(- importProject(- {- to: destinationShareLink,- ignoreVersionCheck: true,- },- dependencies- )- ).rejects.toThrow("Handled CLI error");-- expect(checkProjectBuildPermission).not.toHaveBeenCalled();- expect(importProjectBundle).not.toHaveBeenCalled();- expect(indicator.stop).toHaveBeenCalledWith(- "Project bundle is invalid. Please run webstudio sync before importing. Invalid fields: assets: Required",- 2- );-});--test("stops before API request when ignored-version data is missing published metadata", async () => {- await writeSyncedData({- projectTitle: undefined,- bundleVersion: undefined,- });-- await expect(- importProject(- {- to: destinationShareLink,- ignoreVersionCheck: true,- },- dependencies- )- ).rejects.toThrow("Handled CLI error");-- expect(checkProjectBuildPermission).not.toHaveBeenCalled();- expect(importProjectBundle).not.toHaveBeenCalled();- expect(indicator.stop).toHaveBeenCalledWith(- "Project bundle is invalid. Please run webstudio sync before importing. Invalid fields: projectTitle: Required",- 2- );-});--test("passes version-check bypass to target API", async () => {- await writeSyncedData();-- await importProject(- {- to: destinationShareLink,- ignoreVersionCheck: true,- },- dependencies- );-- expect(importProjectBundle).toHaveBeenCalledWith(- expect.objectContaining({- ignoreVersionCheck: true,- })- );-});--test("uploads local asset files before import", async () => {- await mkdir(".webstudio/assets", { recursive: true });- await writeSyncedData({- assets: [imageAsset],- });- await writeFile(".webstudio/assets/image.png", "hello", "utf8");-- await importProject({ to: destinationShareLink }, dependencies);-- expect(uploadAssetFiles).toHaveBeenCalledWith({- ...destinationRequest,- assets: [imageAsset],- });- expect(importProjectBundle).toHaveBeenCalledWith(- expect.objectContaining({- data: createSyncedData({ assets: [imageAsset] }),- })- );-});--test("re-uploads missing asset files reported by import API", async () => {- await mkdir(".webstudio/assets", { recursive: true });- await writeSyncedData({- assets: [imageAsset],- });- await writeFile(".webstudio/assets/image.png", "hello", "utf8");- importProjectBundle- .mockRejectedValueOnce(- new Error("Imported asset files are missing: image.png")- )- .mockResolvedValueOnce({ version: 1 });-- await importProject({ to: destinationShareLink }, dependencies);-- expect(uploadAssetFiles).toHaveBeenNthCalledWith(1, {- ...destinationRequest,- assets: [imageAsset],- });- expect(uploadAssetFiles).toHaveBeenNthCalledWith(2, {- ...destinationRequest,- assets: [imageAsset],- });- expect(importProjectBundle).toHaveBeenCalledTimes(2);- expect(indicator.message).toHaveBeenCalledWith(- "Re-uploading 1 missing assets"- );- expect(indicator.stop).toHaveBeenCalledWith("Project imported successfully");-});--test("does not retry unknown missing asset files", async () => {- await mkdir(".webstudio/assets", { recursive: true });- await writeSyncedData({- assets: [imageAsset],- });- await writeFile(".webstudio/assets/image.png", "hello", "utf8");- importProjectBundle.mockRejectedValueOnce(- new Error("Imported asset files are missing: unknown.png")- );-- await expect(- importProject({ to: destinationShareLink }, dependencies)- ).rejects.toThrow("Handled CLI error");-- expect(uploadAssetFiles).toHaveBeenCalledTimes(1);- expect(importProjectBundle).toHaveBeenCalledTimes(1);- expect(indicator.stop).toHaveBeenCalledWith(- "Imported asset files are missing: unknown.png",- 2- );-});--test("imports without uploading assets when requested", async () => {- await writeSyncedData({- assets: [imageAsset],- });-- await importProject(- {- to: destinationShareLink,- skipAssets: true,- },- dependencies- );-- expect(uploadAssetFiles).not.toHaveBeenCalled();- expect(log.info).toHaveBeenCalledWith("Skipped asset upload and asset rows");- expect(importProjectBundle).toHaveBeenCalledWith(- expect.objectContaining({- data: createSyncedData({ assets: [] }),- })- );-});--test("validates exported auth config before importing", async () => {- const syncedData = await writeSyncedData();- await writeFile(- LOCAL_AUTH_FILE,- createAuthConfigContentFromBundle(syncedData),- "utf8"- );-- await importProject({ to: destinationShareLink }, dependencies);-- expect(importProjectBundle).toHaveBeenCalledWith(- expect.objectContaining({- data: syncedData,- })- );- expect(log.info).toHaveBeenCalledWith(`Read ${LOCAL_AUTH_FILE}`);-});--test("stops before API request when exported auth config is malformed", async () => {- await writeSyncedData();- await writeFile(LOCAL_AUTH_FILE, "{", "utf8");-- await expect(- importProject({ to: destinationShareLink }, dependencies)- ).rejects.toThrow("Handled CLI error");-- expect(checkProjectBuildPermission).not.toHaveBeenCalled();- expect(importProjectBundle).not.toHaveBeenCalled();- expect(indicator.stop).toHaveBeenCalledWith(- `Project bundle auth config is invalid. Please run webstudio prebuild before importing. ${LOCAL_AUTH_FILE} is invalid JSON`,- 2- );-});--test("stops before API request when exported auth config does not match data", async () => {- await writeSyncedData();- await writeFile(- LOCAL_AUTH_FILE,- JSON.stringify({- version: 1,- routes: {- "/private": {- method: "basic",- login: "admin",- password: "secret",- },- },- }),- "utf8"- );-- await expect(- importProject({ to: destinationShareLink }, dependencies)- ).rejects.toThrow("Handled CLI error");-- expect(checkProjectBuildPermission).not.toHaveBeenCalled();- expect(importProjectBundle).not.toHaveBeenCalled();- expect(indicator.stop).toHaveBeenCalledWith(- `Project bundle auth config is invalid. Please run webstudio prebuild before importing. ${LOCAL_AUTH_FILE} does not match .webstudio/data.json`,- 2- );-});--test("stops before API request when destination link is invalid", async () => {- await writeSyncedData();-- await expect(- importProject(- {- to: "https://example.com",- },- dependencies- )- ).rejects.toThrow("Handled CLI error");-- expect(importProjectBundle).not.toHaveBeenCalled();- expect(checkProjectBuildPermission).not.toHaveBeenCalled();- expect(indicator.stop).toHaveBeenCalledWith(- "Destination share link is invalid.",- 2- );-});--test("stops before API request when current local data is malformed", async () => {- await writeSyncedData({ assets: undefined });-- await expect(- importProject(- {- to: destinationShareLink,- },- dependencies- )- ).rejects.toThrow("Handled CLI error");-- expect(checkProjectBuildPermission).not.toHaveBeenCalled();- expect(importProjectBundle).not.toHaveBeenCalled();- expect(indicator.stop).toHaveBeenCalledWith(- "Project bundle is invalid. Please run webstudio sync before importing. Invalid fields: assets: Required",- 2- );-});--test("stops before API request when current local data is missing published metadata", async () => {- await writeSyncedData({ projectTitle: undefined });-- await expect(- importProject(- {- to: destinationShareLink,- },- dependencies- )- ).rejects.toThrow("Handled CLI error");-- expect(checkProjectBuildPermission).not.toHaveBeenCalled();- expect(importProjectBundle).not.toHaveBeenCalled();- expect(indicator.stop).toHaveBeenCalledWith(- "Project bundle is invalid. Please run webstudio sync before importing. Invalid fields: projectTitle: Required",- 2- );-});--test("stops before uploading asset files when destination permission check fails", async () => {- await writeSyncedData({- assets: [imageAsset],- });- const uploadAssetFiles = vi.fn();- checkProjectBuildPermission.mockRejectedValue(- new Error("You don't have permission to build this project")- );-- await expect(- importProject(- {- to: destinationShareLink,- },- {- ...dependencies,- uploadAssetFiles,- }- )- ).rejects.toThrow("Handled CLI error");-- expect(checkProjectBuildPermission).toHaveBeenCalledWith(destinationRequest);- expect(uploadAssetFiles).not.toHaveBeenCalled();- expect(importProjectBundle).not.toHaveBeenCalled();- expect(indicator.stop).toHaveBeenCalledWith(- "You don't have permission to build this project",- 2- );-});--test("prints import command in CLI compatibility guidance", async () => {- await writeSyncedData();- importProjectBundle.mockRejectedValue(- new Error("Version mismatch", {- cause: createApiCompatibilityPayload({- reason: "apiProcedureNotFound",- target: "cli",- }),- })- );-- await expect(- importProject(- {- to: destinationShareLink,- },- dependencies- )- ).rejects.toThrow("Handled CLI error");-- expect(indicator.stop).toHaveBeenCalledWith(- expect.stringContaining("npx webstudio@latest import"),- 2- );-});--test("forwards oversized project bundle import error", async () => {- await writeSyncedData();- importProjectBundle.mockRejectedValue(- new Error("Project bundle is too large to import. Maximum size is 20 MiB.")- );-- await expect(- importProject(- {- to: destinationShareLink,- },- dependencies- )- ).rejects.toThrow("Handled CLI error");-- expect(indicator.stop).toHaveBeenCalledWith(- "Project bundle is too large to import. Maximum size is 20 MiB.",- 2- );-});diff --git a/packages/cli/src/commands/import.ts b/packages/cli/src/commands/import.tsdeleted file mode 100644index 4715bdfca8..0000000000--- a/packages/cli/src/commands/import.ts+++ /dev/null@@ -1,300 +0,0 @@-import { cwd, stdin, stdout } from "node:process";-import { join } from "node:path";-import { cancel, isCancel, log, spinner, text } from "@clack/prompts";-import {- getBundleVersion,- getBundleVersionMismatchMessage,- parseMissingImportedAssetFilesMessage,- publishedProjectBundle,- bundleVersion,-} from "@webstudio-is/protocol";-import {- checkProjectBuildPermission,- importProjectBundle,-} from "@webstudio-is/http-client";-import { LOCAL_DATA_FILE } from "../config";-import { loadJSONFile } from "../fs-utils";-import { HandledCliError } from "../errors";-import { uploadAssetFiles } from "../asset-files";-import { LOCAL_AUTH_FILE, validateAuthConfigFile } from "../auth-config";-import { apiCompatibilityHeaders, stopSpinnerWithError } from "./api";-import { parseShareLink, validateShareLink } from "./link";-import { formatZodIssues } from "../zod-utils";-import type {- CommonYargsArgv,- StrictYargsOptionsToInterface,-} from "./yargs-types";--type ImportProjectDependencies = {- checkProjectBuildPermission: typeof checkProjectBuildPermission;- importProjectBundle: typeof importProjectBundle;- uploadAssetFiles: typeof uploadAssetFiles;- loadJSONFile: typeof loadJSONFile;- text: typeof text;- isInteractive: boolean;- log: Pick<typeof log, "info">;- spinner: typeof spinner;-};--const isInteractiveTerminal = () =>- stdin.isTTY === true && stdout.isTTY === true;--const defaultDependencies: ImportProjectDependencies = {- checkProjectBuildPermission,- importProjectBundle,- uploadAssetFiles,- loadJSONFile,- text,- isInteractive: isInteractiveTerminal(),- log,- spinner,-};--const missingDestinationMessage =- "Please specify a destination share link with --to";-const missingProjectBundleMessage =- "Project bundle is missing. Please run webstudio sync before importing.";-const invalidProjectBundleMessage =- "Project bundle is invalid. Please run webstudio sync before importing.";-const invalidAuthConfigMessage =- "Project bundle auth config is invalid. Please run webstudio prebuild before importing.";-const invalidDestinationMessage = "Destination share link is invalid.";-const maxMissingAssetImportRetries = 5;--export const importOptions = (yargs: CommonYargsArgv) =>- yargs- .option("to", {- type: "string",- describe: "Share link with build permissions to import synced data into",- })- .option("ignore-version-check", {- type: "boolean",- describe:- "Import data without a compatible data version; import may fail if source and target API data formats differ",- })- .option("skip-assets", {- type: "boolean",- describe:- "Import project data without uploading or importing asset files; referenced assets may be missing in the target project",- })- .check((options) => {- if (options.to === undefined && isInteractiveTerminal() === false) {- return missingDestinationMessage;- }- return true;- });--type ImportOptions = Pick<- Partial<StrictYargsOptionsToInterface<typeof importOptions>>,- "ignoreVersionCheck" | "skipAssets"-> & {- to?: string;-};--export const importProject = async (- options: ImportOptions,- dependencies = defaultDependencies-) => {- const importing = dependencies.spinner();- importing.start("Importing project bundle");-- if (options.to === undefined && dependencies.isInteractive === false) {- importing.stop(missingDestinationMessage, 2);- throw new HandledCliError();- }-- importing.message(`Reading ${LOCAL_DATA_FILE}`);-- let data: unknown | null;- try {- data = await dependencies.loadJSONFile<unknown>(- join(cwd(), LOCAL_DATA_FILE)- );- } catch {- importing.stop(invalidProjectBundleMessage, 2);- throw new HandledCliError();- }- if (data === null) {- importing.stop(missingProjectBundleMessage, 2);- throw new HandledCliError();- }- const localBundleVersion = getBundleVersion(data);- if (- localBundleVersion !== bundleVersion &&- options.ignoreVersionCheck !== true- ) {- importing.stop(- getBundleVersionMismatchMessage({- ignoreVersionCheckHint:- "pass --ignore-version-check if you know the source and target data formats are compatible",- receivedVersion: localBundleVersion,- }),- 2- );- throw new HandledCliError();- }- const parsedData = publishedProjectBundle.safeParse(data);- if (parsedData.success === false) {- importing.stop(- `${invalidProjectBundleMessage} Invalid fields: ${formatZodIssues(- parsedData.error.issues- )}`,- 2- );- throw new HandledCliError();- }- const importData = parsedData.data;-- importing.message(`Reading ${LOCAL_AUTH_FILE}`);- try {- if (- await validateAuthConfigFile({- data: importData,- filePath: join(cwd(), LOCAL_AUTH_FILE),- })- ) {- dependencies.log.info(`Read ${LOCAL_AUTH_FILE}`);- }- } catch (error) {- importing.stop(- error instanceof Error- ? `${invalidAuthConfigMessage} ${error.message}`- : invalidAuthConfigMessage,- 2- );- throw new HandledCliError();- }-- let destinationShareLink = options.to;- if (- destinationShareLink === undefined &&- dependencies.isInteractive === true- ) {- importing.stop(`Read ${LOCAL_DATA_FILE}`);- const shareLink = await dependencies.text({- message: "Please paste a destination share link with build permissions",- validate: validateShareLink,- });- if (isCancel(shareLink)) {- cancel("Project import is cancelled");- throw new HandledCliError();- }- destinationShareLink = shareLink;- importing.start("Importing project bundle");- }- if (destinationShareLink === undefined) {- importing.stop(missingDestinationMessage, 2);- throw new HandledCliError();- }-- let destination;- try {- destination = parseShareLink(destinationShareLink);- } catch {- importing.stop(invalidDestinationMessage, 2);- throw new HandledCliError();- }-- dependencies.log.info(`Read ${LOCAL_DATA_FILE}`);- dependencies.log.info(`Destination project: ${destination.projectId}`);- dependencies.log.info(`Destination origin: ${destination.origin}`);- const destinationRequest = {- projectId: destination.projectId,- authToken: destination.token,- origin: destination.origin,- headers: apiCompatibilityHeaders,- };-- importing.message("Checking destination build permission");- try {- await dependencies.checkProjectBuildPermission(destinationRequest);- } catch (error) {- stopSpinnerWithError(- importing,- error,- "Unable to check destination build permission",- "import"- );- throw new HandledCliError();- }-- if (options.skipAssets === true) {- dependencies.log.info("Skipped asset upload and asset rows");- } else {- importing.message(`Uploading ${importData.assets.length} assets`);- try {- await dependencies.uploadAssetFiles({- assets: importData.assets,- ...destinationRequest,- });- } catch (error) {- importing.stop(- error instanceof Error- ? `Unable to upload assets: ${error.message}`- : "Unable to upload assets",- 2- );- throw new HandledCliError();- }- }-- const dataToImport =- options.skipAssets === true ? { ...importData, assets: [] } : importData;- const stopImportWithError = (error: unknown): never => {- stopSpinnerWithError(- importing,- error,- "Unable to import project bundle",- "import"- );- throw new HandledCliError();- };-- for (let attempt = 0; attempt <= maxMissingAssetImportRetries; attempt += 1) {- importing.message(- `Waiting for API response while importing into ${destination.projectId}`- );-- try {- await dependencies.importProjectBundle({- ...destinationRequest,- data: dataToImport,- ignoreVersionCheck: options.ignoreVersionCheck,- });- importing.stop("Project imported successfully");- return;- } catch (error) {- const missingAssetNames =- options.skipAssets === true- ? undefined- : parseMissingImportedAssetFilesMessage(error);- const assetNames = missingAssetNames ?? [];- if (assetNames.length === 0 || attempt === maxMissingAssetImportRetries) {- stopImportWithError(error);- }-- const missingAssets = importData.assets.filter((asset) =>- assetNames.includes(asset.name)- );- if (missingAssets.length !== assetNames.length) {- stopImportWithError(error);- }-- importing.message(`Re-uploading ${missingAssets.length} missing assets`);- try {- await dependencies.uploadAssetFiles({- assets: missingAssets,- ...destinationRequest,- });- } catch (uploadError) {- importing.stop(- uploadError instanceof Error- ? `Unable to upload missing assets: ${uploadError.message}`- : "Unable to upload missing assets",- 2- );- throw new HandledCliError();- }- }- }-};diff --git a/packages/cli/src/commands/init-flow.test.ts b/packages/cli/src/commands/init-flow.test.tsnew file mode 100644index 0000000000..b5f614480c--- /dev/null+++ b/packages/cli/src/commands/init-flow.test.ts@@ -0,0 +1,52 @@+import { afterEach, beforeEach, expect, test, vi } from "vitest";+import { mkdtemp, rm } from "node:fs/promises";+import { join } from "node:path";+import { tmpdir } from "node:os";+import { initFlow } from "./init-flow";++const originalCwd = process.cwd();+let tempDir: string;++beforeEach(async () => {+ tempDir = await mkdtemp(join(tmpdir(), "webstudio-init-"));+ process.chdir(tempDir);+ vi.spyOn(console, "info").mockImplementation(() => undefined);+});++afterEach(async () => {+ process.chdir(originalCwd);+ await rm(tempDir, { recursive: true, force: true });+ vi.restoreAllMocks();+});++test("initializes credentials from share link", async () => {+ const projectId = "11111111-1111-4111-8111-111111111111";+ const saveShareLink = vi.fn().mockResolvedValue({+ origin: "https://example.com",+ projectId,+ });++ await initFlow(+ {+ assets: true,+ json: true,+ link: `https://p-${projectId}-dot-example.com/?authToken=token-1`,+ template: [],+ },+ { saveShareLink }+ );++ expect(saveShareLink).toHaveBeenCalledWith(+ `https://p-${projectId}-dot-example.com/?authToken=token-1`+ );+ const output = JSON.parse(vi.mocked(console.info).mock.calls[0][0]);+ expect(output).toEqual({+ ok: true,+ data: { projectId },+ meta: {+ command: "init",+ projectId,+ durationMs: expect.any(Number),+ },+ });+});diff --git a/packages/cli/src/commands/init-flow.ts b/packages/cli/src/commands/init-flow.tsindex 738f12ef80..a3946048c9 100644--- a/packages/cli/src/commands/init-flow.ts+++ b/packages/cli/src/commands/init-flow.ts@@ -13,11 +13,15 @@ import {} from "@clack/prompts";import { createFolderIfNotExists, isFileExists } from "../fs-utils";import { PROJECT_TEMPLATES } from "../config";-import { link, validateShareLink } from "./link";+import { link, saveShareLink, validateShareLink } from "./link";import { sync } from "./sync";import { build, buildOptions } from "./build";-import type { StrictYargsOptionsToInterface } from "./yargs-types";+import type {+ CommonYargsArgv,+ StrictYargsOptionsToInterface,+} from "./yargs-types";import { mapToTemplatesFromOptions } from "../build-utils";+import { printJson } from "../json-output";type ProjectTemplates = (typeof PROJECT_TEMPLATES)[number]["value"];@@ -29,9 +33,52 @@ const exitIfCancelled = <Value>(value: Value | symbol): Value => {return value;};+export const initOptions = (yargs: CommonYargsArgv) =>+ buildOptions(yargs)+ .option("link", {+ alias: "l",+ type: "string",+ describe: "Builder API share link",+ })+ .option("json", {+ type: "boolean",+ default: false,+ describe: "Print JSON output",+ });++type InitOptions = StrictYargsOptionsToInterface<typeof initOptions>;++type InitFlowDependencies = {+ saveShareLink: typeof saveShareLink;+};++const defaultDependencies: InitFlowDependencies = {+ saveShareLink,+};+export const initFlow = async (- options: StrictYargsOptionsToInterface<typeof buildOptions>+ options: InitOptions,+ dependencies = defaultDependencies) => {+ if (options.link !== undefined) {+ const start = Date.now();+ const { projectId } = await dependencies.saveShareLink(options.link);+ if (options.json) {+ printJson({+ ok: true,+ data: { projectId },+ meta: {+ command: "init",+ projectId,+ durationMs: Date.now() - start,+ },+ });+ } else {+ log.step("The project is linked successfully");+ }+ return;+ }+const isProjectConfigured = await isFileExists(".webstudio/config.json");let shouldInstallDeps = false;let folderName: undefined | string;diff --git a/packages/cli/src/commands/link.test.ts b/packages/cli/src/commands/link.test.tsnew file mode 100644index 0000000000..905c43fb82--- /dev/null+++ b/packages/cli/src/commands/link.test.ts@@ -0,0 +1,71 @@+import { afterEach, beforeEach, expect, test } from "vitest";+import {+ copyFile,+ mkdir,+ mkdtemp,+ readFile,+ rm,+ writeFile,+} from "node:fs/promises";+import { dirname, join } from "node:path";+import { tmpdir } from "node:os";+import { GLOBAL_CONFIG_FILE, LOCAL_CONFIG_FILE } from "../config";+import { parseShareLink, saveShareLink, validateShareLink } from "./link";++const originalCwd = process.cwd();+const projectId = "11111111-1111-4111-8111-111111111111";+const shareLink = `https://p-${projectId}-dot-example.com/?authToken=token-1`;+let tempDir: string;+let backupPath: string;++beforeEach(async () => {+ tempDir = await mkdtemp(join(tmpdir(), "webstudio-link-"));+ backupPath = join(tempDir, "global-config-backup.json");+ process.chdir(tempDir);+ await mkdir(dirname(GLOBAL_CONFIG_FILE), { recursive: true });+ try {+ await copyFile(GLOBAL_CONFIG_FILE, backupPath);+ } catch {+ await rm(backupPath, { force: true });+ }+ await writeFile(GLOBAL_CONFIG_FILE, "{}", "utf8");+});++afterEach(async () => {+ process.chdir(originalCwd);+ try {+ await copyFile(backupPath, GLOBAL_CONFIG_FILE);+ } catch {+ await rm(GLOBAL_CONFIG_FILE, { force: true });+ }+ await rm(tempDir, { recursive: true, force: true });+});++test("parses and validates share links", () => {+ expect(parseShareLink(shareLink)).toEqual({+ origin: "https://example.com",+ projectId,+ token: "token-1",+ });++ expect(validateShareLink("")).toBe("Share link is required");+ expect(validateShareLink("not-a-url")).toBe("Share link is invalid");+ expect(validateShareLink(shareLink)).toBeUndefined();+});++test("saves global credentials and local project config", async () => {+ await expect(saveShareLink(shareLink)).resolves.toEqual({+ origin: "https://example.com",+ projectId,+ });++ expect(JSON.parse(await readFile(GLOBAL_CONFIG_FILE, "utf8"))).toEqual({+ [projectId]: {+ origin: "https://example.com",+ token: "token-1",+ },+ });+ expect(JSON.parse(await readFile(LOCAL_CONFIG_FILE, "utf8"))).toEqual({+ projectId,+ });+});diff --git a/packages/cli/src/commands/link.ts b/packages/cli/src/commands/link.tsindex 15e57c6f57..9b49c13f7e 100644--- a/packages/cli/src/commands/link.ts+++ b/packages/cli/src/commands/link.ts@@ -1,8 +1,8 @@import { cwd, exit } from "node:process";-import { join } from "node:path";-import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";+import { dirname, join } from "node:path";+import { mkdir, readFile, rm, writeFile } from "node:fs/promises";import { cancel, isCancel, log, text } from "@clack/prompts";-import { parseBuilderUrl } from "@webstudio-is/http-client";+import { parseBuilderUrl } from "@webstudio-is/protocol";import {GLOBAL_CONFIG_FILE,LOCAL_CONFIG_FILE,@@ -10,7 +10,7 @@ import {jsonToGlobalConfig,type LocalConfig,} from "../config";-import { createFileIfNotExists } from "../fs-utils";+import { writeFileAtomic } from "../fs-utils";import type {CommonYargsArgv,StrictYargsOptionsToInterface,@@ -47,9 +47,7 @@ const withConfigLock = async <Result>(callback: () => Promise<Result>) => {};const writeConfigFile = async (content: string) => {- const temporaryFile = `${GLOBAL_CONFIG_FILE}.${process.pid}.tmp`;- await writeFile(temporaryFile, content, "utf8");- await rename(temporaryFile, GLOBAL_CONFIG_FILE);+ await writeFileAtomic(GLOBAL_CONFIG_FILE, content);};export const parseShareLink = (value: string) => {@@ -105,23 +103,7 @@ export const linkOptions = (yargs: CommonYargsArgv) =>describe: "Link to a webstudio project",});-export const link = async (- options: StrictYargsOptionsToInterface<typeof linkOptions> | { link?: string }-) => {- let shareLink: string | symbol;- if (options.link) {- shareLink = options.link;- } else {- shareLink = await text({- message: "Please paste a link from the Share Dialog in the builder",- validate: validateShareLink,- });- if (isCancel(shareLink)) {- cancel("Project linking is cancelled");- exit(1);- }- }-+export const saveShareLink = async (shareLink: string) => {const { origin, projectId, token } = parseShareLink(shareLink);await withConfigLock(async () => {@@ -138,16 +120,41 @@ export const link = async (await writeConfigFile(JSON.stringify(newConfig, null, 2));});- log.info(`Saved credentials for project ${projectId}.-You can find your config at ${GLOBAL_CONFIG_FILE}`);const localConfig: LocalConfig = {projectId,};- await createFileIfNotExists(- join(cwd(), LOCAL_CONFIG_FILE),- JSON.stringify(localConfig, null, 2)+ const localConfigPath = join(cwd(), LOCAL_CONFIG_FILE);+ await mkdir(dirname(localConfigPath), { recursive: true });+ await writeFile(+ localConfigPath,+ JSON.stringify(localConfig, null, 2),+ "utf8");++ return { origin, projectId };+};++export const link = async (+ options: StrictYargsOptionsToInterface<typeof linkOptions> | { link?: string }+) => {+ let shareLink: string | symbol;+ if (options.link) {+ shareLink = options.link;+ } else {+ shareLink = await text({+ message: "Please paste a link from the Share Dialog in the builder",+ validate: validateShareLink,+ });+ if (isCancel(shareLink)) {+ cancel("Project linking is cancelled");+ exit(1);+ }+ }++ const { projectId } = await saveShareLink(shareLink);+ log.info(`Saved credentials for project ${projectId}.+You can find your config at ${GLOBAL_CONFIG_FILE}`);log.step("The project is linked successfully");};diff --git a/packages/cli/src/commands/man.test.ts b/packages/cli/src/commands/man.test.tsnew file mode 100644index 0000000000..6a68149f7e--- /dev/null+++ b/packages/cli/src/commands/man.test.ts@@ -0,0 +1,346 @@+import { afterEach, expect, test, vi } from "vitest";+import {+ apiCommandMetadata,+ cliCommandMetadata,+ mcpOnlyApiCommandMetadata,+} from "./api-command-metadata";+import {+ generatedAppDependencyNotes,+ getVisionVerificationLoop,+} from "../mcp-guidance";+import { man } from "./man";++afterEach(() => {+ vi.restoreAllMocks();+});++test("prints api manual with patch workflow and examples", () => {+ vi.spyOn(console, "info").mockImplementation(() => undefined);++ man({ topic: "api", json: false });++ const output = vi.mocked(console.info).mock.calls.at(-1)?.[0];+ expect(output).toContain("webstudio permissions --json");+ expect(output).toContain("Supported namespaces");+ expect(output).toContain("## Use Case Index");+ expect(output).toContain("## CLI Capability Inventory");+ expect(output).toContain("## Known CLI Gaps");+ expect(output).toContain("Save and manage page templates");+ expect(output).toContain("Generate from design input");+ expect(output).toContain("### Top-Level Commands");+ expect(output).toContain("### High-Level API Commands By Area");+ expect(output).toContain("### MCP-Only Operations");+ expect(output).toContain("webstudio mcp");+ expect(output).toContain("## Project Session Cache");+ expect(output).toContain("Use --refresh");+ expect(output).toContain("meta.session");+ expect(output).toContain("Visually verify rendered work with AI vision");+ expect(output).toContain("MCP tool: list-breakpoints {}");+ expect(output).not.toContain(" - webstudio list-breakpoints --json");+ expect(output).toContain(+ 'MCP tool: update-project-settings {"settings":"project-settings.json contents"}'+ );+ expect(output).toContain("Manage marketplace metadata");+ expect(output).toContain("Create a design token");+ for (const { cliCommand } of cliCommandMetadata) {+ expect(output).toContain(`### ${cliCommand}`);+ }+ expect(output).not.toContain("### list-domains\n");+ expect(output).toContain("Operation: list-domains");+ expect(output).not.toContain("### update-props\n");+ expect(output).toContain("- update-props:");+});++test("prints api manual as json", () => {+ vi.spyOn(console, "info").mockImplementation(() => undefined);++ man({ topic: "api", json: true });++ const output = JSON.parse(vi.mocked(console.info).mock.calls.at(-1)?.[0]);+ expect(output.topic).toBe("api");+ expect(output.workflows).toContain("webstudio permissions --json");+ expect(output.workflows).toContain("webstudio mcp");+ expect(output.workflows).not.toContain(+ "webstudio snapshot --include pages,instances,props,styles,styleSources,styleSourceSelections,dataSources,resources,assets --json"+ );+ expect(output.mutationNamespaces).toContain("instances");+ expect(output.sessionBehavior.refreshFlag).toContain("--refresh");+ expect(output.sessionBehavior.metadata).toContain("meta.session");+ expect(output.knownGaps).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ capability: "Save and manage page templates",+ }),+ expect.objectContaining({+ capability: "Generate from design input",+ }),+ ])+ );+ expect(+ output.topLevelCommands.map(({ command }: { command: string }) => command)+ ).toEqual([+ "init",+ "link",+ "sync",+ "build",+ "preview",+ "screenshot",+ "permissions",+ "publish",+ "domains",+ "schema",+ "man",+ "mcp",+ ]);+ expect(+ output.topLevelCommands.map(({ command }: { command: string }) => command)+ ).not.toEqual(expect.arrayContaining(["publish deploy", "domains list"]));+ expect(Object.values(output.apiCommandsByArea).flat().sort()).toEqual(+ cliCommandMetadata.map(({ cliCommand }) => cliCommand).sort()+ );+ expect(+ output.commands.map((command: { command: string }) => command.command)+ ).toEqual(cliCommandMetadata.map(({ cliCommand }) => cliCommand));+ expect(+ output.mcpOnlyCommands.map(+ (command: { command: string }) => command.command+ )+ ).toEqual(mcpOnlyApiCommandMetadata.map(({ command }) => command));+ expect(output.taskRecipes.pages).toContain(+ 'MCP tool: list-pages {"includeFolders":true}'+ );+ expect(output.useCaseScenarios).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ useCase: "Update project settings",+ commands: [+ 'MCP tool: update-project-settings {"settings":"project-settings.json contents"}',+ ],+ }),+ ])+ );+ expect(output.inputFileShapes["children.json"]).toEqual([+ { tag: "div", label: "Hero", text: "Launch faster" },+ ]);+ expect(+ output.useCaseScenarios.map(({ useCase }: { useCase: string }) => useCase)+ ).toEqual([+ "Link/configure one project",+ "Identify current token",+ "Check token permissions",+ "Inspect project/build/version",+ "Discover CLI/API capabilities",+ "Inspect and refresh MCP session cache",+ "Visually verify rendered work with AI vision",+ "List pages",+ "Read page by id",+ "Read page by path",+ "Create page",+ "Update page settings/metadata",+ "Read project settings",+ "Update project settings",+ "List redirects",+ "Create redirect",+ "Update redirect",+ "Delete redirect",+ "List breakpoints",+ "Create breakpoint",+ "Update breakpoint",+ "Delete breakpoint",+ "Duplicate page",+ "List page templates",+ "Create page from template",+ "Delete page",+ "List folders",+ "Create folder",+ "Update folder",+ "Delete folder",+ "List element instances",+ "Inspect one element instance",+ "Append/prepend/replace child elements",+ "Move elements",+ "Clone element subtree",+ "Delete element subtree",+ "List text/expression children",+ "Update text child",+ "Update props",+ "Delete props",+ "Bind props to expressions/resources/actions",+ "Read styles",+ "Update local styles",+ "Delete local styles",+ "Replace matching style values",+ "List design tokens",+ "Create design tokens",+ "Update design token styles",+ "Delete design token styles",+ "Attach design token to instances",+ "Detach design token from instances",+ "Extract design token from local styles",+ "List CSS variables",+ "Define CSS variables",+ "Delete CSS variables",+ "Rewrite CSS variable references",+ "List data variables",+ "Create data variable",+ "Update data variable",+ "Delete data variable",+ "List resources",+ "Create resource",+ "Update resource",+ "Delete resource",+ "List assets",+ "Upload one asset",+ "Upload asset batch",+ "Find asset usage",+ "Replace asset references",+ "Delete assets",+ "Publish project",+ "List publishes",+ "Check publish job",+ "Unpublish",+ "List domains",+ "Create domain",+ "Update domain",+ "Delete domain",+ "Verify domain",+ "Make arbitrary store-level changes",+ "Manage marketplace metadata",+ "Search and inspect safely",+ "Refactor targeted content",+ "Optimize existing project",+ "Connect external data",+ "Support dynamic runtime behavior",+ "Build authenticated pages",+ "Generate from design input",+ "Cross-project maintenance",+ ]);+ const documentedCommands = new Set([+ ...output.commands.map(+ (command: { operation?: string; command: string }) =>+ command.operation ?? command.command+ ),+ ...output.useCaseScenarios+ .flatMap(({ commands }: { commands: string[] }) => commands)+ .flatMap((command: string) => {+ const match = command.match(/^webstudio ([a-z-]+)/);+ if (match !== null) {+ return [match[1]];+ }+ const mcpMatch = command.match(/^MCP tool: ([a-z-]+)/);+ return mcpMatch === null ? [] : [mcpMatch[1]];+ }),+ ]);+ const documentedVisibleCommands = new Set(+ output.useCaseScenarios+ .flatMap(({ commands }: { commands: string[] }) => commands)+ .flatMap((command: string) => {+ const match = command.match(/^webstudio ([a-z-]+)/);+ if (match !== null) {+ return [match[1]];+ }+ const mcpMatch = command.match(/^MCP tool: ([a-z-]+)/);+ return mcpMatch === null ? [] : [mcpMatch[1]];+ })+ );+ for (const { command } of apiCommandMetadata) {+ expect(documentedCommands).toContain(command);+ }+ expect(documentedVisibleCommands).not.toContain("validate-patch");+});++test("prints llm manual with discovery rules", () => {+ vi.spyOn(console, "info").mockImplementation(() => undefined);++ man({ topic: "llm", json: false });++ const output = vi.mocked(console.info).mock.calls.at(-1)?.[0];+ expect(output).toContain("webstudio schema api --json");+ expect(output).toContain("webstudio permissions --json");+ expect(output).toContain("## MCP Argument Examples");+ expect(output).toContain('"updates"');+ expect(output).toContain('"instanceId": "instance-id"');+ expect(output).toContain("Never guess ids");+ expect(output).toContain("--refresh");+ expect(output).toContain("## Known Gaps");+ expect(output).toContain("Provider-specific authenticated pages");+});++test("prints mcp manual with startup and JSON argument examples", () => {+ vi.spyOn(console, "info").mockImplementation(() => undefined);++ man({ topic: "mcp", json: false });++ const output = vi.mocked(console.info).mock.calls.at(-1)?.[0];+ expect(output).toContain("# Webstudio MCP Manual");+ expect(output).toContain("stdout is reserved for MCP JSON-RPC");+ expect(output).toContain("meta.get_more_tools");+ expect(output).toContain("webstudio://project/tools");+ expect(output).toContain("## Vision Verification Loop");+ expect(output).toContain("screenshot.diff");+ expect(output).toContain("Read screenshot.diff textAnalysis");+ expect(output).toContain("vision.install-ocr");+ expect(output).toContain('"parentInstanceId": "parent-id"');+});++test("prints mcp manual as json", () => {+ vi.spyOn(console, "info").mockImplementation(() => undefined);++ man({ topic: "mcp", json: true });++ const output = JSON.parse(vi.mocked(console.info).mock.calls.at(-1)?.[0]);+ expect(output.topic).toBe("mcp");+ expect(output.discovery).toContain("meta.index");+ expect(output.resources).toContain("webstudio://project/tools");+ expect(output.rules).toContain(+ "For visual/design work, verify the rendered result with vision before finishing."+ );+ expect(output.visionVerificationLoop).toContain(+ getVisionVerificationLoop({ includeDiff: true })[1]+ );+ expect(output.visionVerificationLoop).toContain(+ generatedAppDependencyNotes[0]+ );+ expect(output.visionVerificationLoop).toEqual(+ expect.arrayContaining([+ expect.stringContaining(+ 'Call screenshot with { path: "/" } or the changed page path.'+ ),+ ])+ );+ expect(output.visionVerificationLoop).toContain(+ "When a baseline PNG exists, call screenshot.diff with baselinePath, currentPath, and outputDir."+ );+ expect(output.screenshotVerification).toContain("screenshot.diff");+ expect(output.screenshotVerification).toContain("OCR textAnalysis");+ expect(output.mcpArgumentExamples["vision.install-ocr"]).toEqual([+ { confirm: true },+ ]);+ expect(output.mcpArgumentExamples["screenshot.diff"]).toEqual([+ {+ baselinePath: "baseline.png",+ currentPath: "current.png",+ outputDir: "visual-diff",+ threshold: 0.1,+ ignoreTopNormalizedY: 0,+ },+ ]);+ expect(output.mcpArgumentExamples["update-text"]).toEqual([+ {+ instanceId: "instance-id",+ childIndex: 0,+ text: "Launch faster",+ },+ ]);+});++test("prints available topics for unknown manual topic", () => {+ vi.spyOn(console, "info").mockImplementation(() => undefined);++ man({ topic: "missing", json: false });++ expect(vi.mocked(console.info).mock.calls.at(-1)?.[0]).toContain(+ "Available topics"+ );+ expect(vi.mocked(console.info).mock.calls.at(-1)?.[0]).toContain("- mcp");+});diff --git a/packages/cli/src/commands/man.ts b/packages/cli/src/commands/man.tsnew file mode 100644index 0000000000..69bf9dd051--- /dev/null+++ b/packages/cli/src/commands/man.ts@@ -0,0 +1,622 @@+import type {+ CommonYargsArgv,+ StrictYargsOptionsToInterface,+} from "./yargs-types";+import { buildPatchNamespaces } from "@webstudio-is/protocol";+import { mcpArgumentExamples } from "@webstudio-is/project-build/mcp";+import { readCliDoc } from "../docs";+import {+ generatedAppDependencyNotes,+ getVisionVerificationLoop,+ screenshotVerificationSummary,+} from "../mcp-guidance";+import { printJson } from "../json-output";+import {+ cliCommandMetadata,+ formatApiUseCaseCommand,+ mcpOnlyApiCommandMetadata,+ topLevelCliCommandMetadata,+} from "./api-command-metadata";+import { knownCliGaps, useCaseScenarios } from "./api-command-docs";++const apiManualMarkdown = readCliDoc("manual-api");+const llmManualMarkdown = readCliDoc("manual-llm");+const mcpManualMarkdown = readCliDoc("manual-mcp");++export const manOptions = (yargs: CommonYargsArgv) =>+ yargs+ .positional("topic", {+ type: "string",+ describe: "Manual topic to print",+ default: "api",+ })+ .option("json", {+ type: "boolean",+ describe: "Print the manual topic as structured JSON",+ default: false,+ });++type ManOptions = StrictYargsOptionsToInterface<typeof manOptions> & {+ topic?: string;+};++const commandIndex = cliCommandMetadata+ .map((command) => {+ const required = command.requiredOptions?.join(", ") ?? "json";+ const examples = (command.examples ?? []).map(+ (example) => ` - ${formatApiUseCaseCommand(example)}`+ );+ return [+ `### ${command.cliCommand}`,+ `Use: ${command.description}`,+ `Operation: ${command.operation}`,+ `Kind: ${command.method}`,+ `Permit: ${command.permit}`,+ `Required: ${required}`,+ examples.length > 0 ? ["Examples:", ...examples].join("\n") : undefined,+ ]+ .filter(Boolean)+ .join("\n");+ })+ .join("\n\n");++const commandCatalog = cliCommandMetadata.map((command) => ({+ command: command.cliCommand,+ operation: command.operation,+ kind: command.method,+ permit: command.permit,+ use: command.description,+ required: command.requiredOptions ?? ["json"],+ examples: (command.examples ?? []).map(formatApiUseCaseCommand),+}));++const mcpOnlyCommandCatalog = mcpOnlyApiCommandMetadata.map((command) => ({+ command: command.command,+ kind: command.method,+ permit: command.permit,+ use: command.description,+ required: command.requiredOptions ?? ["json"],+ examples: command.examples ?? [],+}));++const readCommands = commandCatalog+ .filter((command) => command.kind === "query")+ .map((command) => command.command);++const writeCommands = commandCatalog+ .filter((command) => command.kind === "mutation")+ .map((command) => command.command);++const topLevelCommandCatalog = topLevelCliCommandMetadata.map(+ ({ command, description, examples }) => ({+ command,+ use: description,+ examples,+ })+);++const taskRecipeUseCases = {+ setup: [+ "Link/configure one project",+ "Check token permissions",+ "Inspect project/build/version",+ "Discover CLI/API capabilities",+ ],+ pages: [+ "List pages",+ "Read page by id",+ "Read page by path",+ "Create page",+ "Update page settings/metadata",+ "Read project settings",+ "Update project settings",+ "List redirects",+ "Create redirect",+ "Update redirect",+ "Delete redirect",+ "List breakpoints",+ "Create breakpoint",+ "Update breakpoint",+ "Delete breakpoint",+ "Duplicate page",+ "List page templates",+ "Create page from template",+ "Delete page",+ ],+ folders: ["List folders", "Create folder", "Update folder", "Delete folder"],+ elements: [+ "List element instances",+ "Inspect one element instance",+ "Append/prepend/replace child elements",+ "Move elements",+ "Clone element subtree",+ "Delete element subtree",+ ],+ text: ["List text/expression children", "Update text child"],+ props: [+ "Update props",+ "Delete props",+ "Bind props to expressions/resources/actions",+ ],+ styles: [+ "Read styles",+ "Update local styles",+ "Delete local styles",+ "Replace matching style values",+ ],+ designTokens: [+ "List design tokens",+ "Create design tokens",+ "Update design token styles",+ "Delete design token styles",+ "Attach design token to instances",+ "Detach design token from instances",+ "Extract design token from local styles",+ ],+ cssVariables: [+ "List CSS variables",+ "Define CSS variables",+ "Delete CSS variables",+ "Rewrite CSS variable references",+ ],+ data: [+ "List data variables",+ "Create data variable",+ "Update data variable",+ "Delete data variable",+ "List resources",+ "Create resource",+ "Update resource",+ "Delete resource",+ ],+ assets: [+ "List assets",+ "Upload one asset",+ "Upload asset batch",+ "Find asset usage",+ "Replace asset references",+ "Delete assets",+ ],+ publishDomains: [+ "Publish project",+ "List publishes",+ "Check publish job",+ "Unpublish",+ "List domains",+ "Create domain",+ "Update domain",+ "Delete domain",+ "Verify domain",+ ],+} as const;++const commandsByUseCase = new Map(+ useCaseScenarios.map((scenario) => [scenario.useCase, scenario.commands])+);++const getCommandsForUseCase = (useCase: string) => {+ const commands = commandsByUseCase.get(useCase);+ if (commands === undefined) {+ throw new Error(`Unknown API CLI use case "${useCase}".`);+ }+ return commands;+};++const taskRecipes = Object.fromEntries(+ Object.entries(taskRecipeUseCases).map(([group, useCases]) => [+ group,+ useCases.flatMap(getCommandsForUseCase),+ ])+) as Record<keyof typeof taskRecipeUseCases, string[]>;++const inputFileShapes = {+ "children.json": [{ tag: "div", label: "Hero", text: "Launch faster" }],+ "moves.json": [+ {+ instanceId: "child-id",+ parentInstanceId: "parent-id",+ insertIndex: 0,+ },+ ],+ "props.json": [+ {+ instanceId: "instance-id",+ name: "aria-label",+ type: "string",+ value: "Menu",+ },+ ],+ "bindings.json": [+ {+ instanceId: "instance-id",+ name: "href",+ binding: { type: "expression", value: "url" },+ },+ ],+ "styles.json": [+ {+ instanceId: "instance-id",+ property: "color",+ value: { type: "keyword", value: "red" },+ },+ ],+ "delete-styles-input.json": [+ { instanceId: "instance-id", property: "color" },+ ],+ "replace.json": {+ property: "color",+ fromValue: { type: "keyword", value: "red" },+ toValue: { type: "keyword", value: "blue" },+ },+ "tokens.json": [+ {+ name: "Brand Primary",+ styles: { color: { type: "keyword", value: "red" } },+ },+ ],+ "instances.json": ["instance-id"],+ "token.json": {+ instanceIds: ["instance-id"],+ name: "Card Accent",+ removeLocalProps: ["color"],+ },+ "vars.json": { "--brand-color": "red" },+ "names.json": ["--brand-color"],+ "variables.json": { "--old-color": "--new-color" },+ "project-settings.json": {+ meta: {+ siteName: "Acme Studio",+ faviconAssetId: "asset-id",+ code: "<script>console.log('site')</script>",+ },+ compiler: { atomicStyles: true },+ },+ "asset.json": {+ name: "hero.png",+ type: "image",+ format: "png",+ meta: { width: 1200, height: 630 },+ },+ "assets.json": [+ {+ name: "hero.png",+ type: "image",+ format: "png",+ meta: { width: 1200, height: 630 },+ },+ ],+ "domain.json": { domain: "www.example.com" },+ "patch.json": [+ {+ id: "transaction-id",+ payload: [+ {+ namespace: "pages",+ patches: [+ {+ op: "replace",+ path: ["meta", "siteName"],+ value: "Site name",+ },+ ],+ },+ ],+ },+ ],+};++const inputFileShapeIndex = Object.entries(inputFileShapes)+ .map(([name, value]) => `${name}:\n\n${JSON.stringify(value, undefined, 2)}`)+ .join("\n\n");++const mcpArgumentExampleIndex = Object.entries(mcpArgumentExamples)+ .map(+ ([name, examples]) =>+ `### ${name}\n\n${examples+ .map((example) => JSON.stringify(example, undefined, 2))+ .join("\n\n")}`+ )+ .join("\n\n");++const mcpVisionVerificationLoop = getVisionVerificationLoop({+ includeDiff: true,+});++const mcpVisionVerificationLoopMarkdown = mcpVisionVerificationLoop+ .map((step, index) => `${index + 1}. ${step}`)+ .join("\n");++const mcpGeneratedAppDependencyNotes = generatedAppDependencyNotes+ .map((note) => `- ${note}`)+ .join("\n");++const useCaseIndex = useCaseScenarios+ .map((scenario) => {+ const commands = scenario.commands.map((command) => ` - ${command}`);+ const namespaces =+ "patchNamespaces" in scenario && scenario.patchNamespaces !== undefined+ ? [`Patch namespaces: ${scenario.patchNamespaces.join(", ")}`]+ : [];+ const notes =+ "notes" in scenario && scenario.notes !== undefined+ ? scenario.notes.map((note) => `Note: ${note}`)+ : [];+ return [+ `### ${scenario.useCase}`,+ "Commands:",+ ...commands,+ ...namespaces,+ ...notes,+ ].join("\n");+ })+ .join("\n\n");++const knownCliGapIndex = knownCliGaps+ .map((gap) =>+ [+ `### ${gap.capability}`,+ `Missing: ${gap.missing}`,+ `Current fallback: ${gap.currentFallback}`,+ gap.suggestedCommands.length > 0+ ? `Suggested commands: ${gap.suggestedCommands.join(", ")}`+ : undefined,+ ]+ .filter(Boolean)+ .join("\n")+ )+ .join("\n\n");++const renderUseCaseCommands = (useCases: readonly string[]) =>+ useCases+ .map((useCase) =>+ [+ `${useCase}:`,+ ...getCommandsForUseCase(useCase).map((command) => `- ${command}`),+ ].join("\n")+ )+ .join("\n\n");++const readFirstUseCases = [+ "List pages",+ "Read page by id",+ "Read page by path",+ "Read project settings",+ "List redirects",+ "List breakpoints",+ "List page templates",+ "List folders",+ "List element instances",+ "Inspect one element instance",+ "List text/expression children",+ "Read styles",+ "List data variables",+ "List resources",+ "List assets",+ "List domains",+ "List publishes",+ "Make arbitrary store-level changes",+] as const;++const apiCommandsByArea = {+ setupAndDiscovery: ["permissions"],+ publishAndDomains: [+ "publish deploy",+ "publish list",+ "publish status",+ "publish unpublish",+ "domains list",+ "domains create",+ "domains update",+ "domains delete",+ "domains verify",+ ],+} as const;++const mcpOnlyCommandIndex = mcpOnlyCommandCatalog+ .map((command) => `- ${command.command}: ${command.use}`)+ .join("\n");++const renderCapabilityCommands = (commands: readonly string[]) =>+ commands.map((command) => `- ${command}`).join("\n");++const topLevelCapabilityIndex = topLevelCommandCatalog+ .map((command) =>+ [+ `### ${command.command}`,+ command.use,+ "Examples:",+ ...command.examples.map((example) => `- ${example}`),+ ].join("\n")+ )+ .join("\n\n");++const apiCapabilityIndex = Object.entries(apiCommandsByArea)+ .map(([area, commands]) =>+ [`### ${area}`, renderCapabilityCommands(commands)].join("\n")+ )+ .join("\n\n");++const taskRecipeIndex = Object.entries(taskRecipeUseCases)+ .map(([group, useCases]) =>+ [`### ${group}`, renderUseCaseCommands(useCases)].join("\n\n")+ )+ .join("\n\n");++const renderMarkdownTemplate = (+ template: string,+ replacements: Record<string, string>+) =>+ template.replace(+ /{{([a-zA-Z0-9]+)}}/g,+ (match, name: string) => replacements[name] ?? match+ );++const manualReplacements = {+ start: renderUseCaseCommands(taskRecipeUseCases.setup),+ readFirst: renderUseCaseCommands(readFirstUseCases),+ topLevelCapabilityIndex,+ apiCapabilityIndex,+ mcpOnlyCommandIndex,+ taskRecipeIndex,+ useCaseIndex,+ knownCliGapIndex,+ inputFileShapeIndex,+ commandIndex,+ mcpArgumentExampleIndex,+ mcpVisionVerificationLoopMarkdown,+ mcpGeneratedAppDependencyNotes,+ screenshotVerificationSummary,+};++const apiManual = renderMarkdownTemplate(apiManualMarkdown, manualReplacements);+const llmManual = renderMarkdownTemplate(llmManualMarkdown, manualReplacements);+const mcpManual = renderMarkdownTemplate(mcpManualMarkdown, manualReplacements);++const topics = {+ api: {+ manual: apiManual,+ json: {+ topic: "api",+ title: "Webstudio API CLI Manual",+ workflows: [+ "webstudio init --link <api-share-link> --json",+ "webstudio permissions --json",+ "webstudio schema api --json",+ "webstudio publish deploy --target production --json",+ "webstudio domains list --json",+ "webstudio mcp",+ ],+ taskRecipes,+ useCaseScenarios,+ knownGaps: knownCliGaps,+ topLevelCommands: topLevelCommandCatalog,+ apiCommandsByArea,+ mcpOnlyCommands: mcpOnlyCommandCatalog,+ inputFileShapes,+ mcpArgumentExamples,+ commands: commandCatalog,+ readCommands,+ writeCommands,+ mutationNamespaces: buildPatchNamespaces,+ sessionBehavior: {+ localReads:+ "Use compatible cached namespaces and fetch only missing or stale namespaces.",+ localMutations:+ "Build patches locally, commit with the cached build version, and update local state only after remote commit succeeds.",+ serverOnly:+ "Run remotely and invalidate/refetch namespaces declared by the public operation catalog.",+ refreshFlag:+ "Use --refresh to refresh required namespaces before local-capable commands.",+ metadata:+ "Successful command JSON includes meta.session with operationId, buildId, version, source, committed, compatibility, namespace metadata, and diagnostics.",+ },+ safetyRules: [+ "Always pass --json.",+ "Never pass project ids; commands use the configured project.",+ "Read ids before writing.",+ "Prefer semantic MCP write tools over apply-patch.",+ "For MCP apply-patch, read the latest version with MCP snapshot before writing.",+ "Reuse ids from MCP snapshot output when updating existing records.",+ "Generate new unique ids when adding records.",+ "Regenerate the patch after a version conflict.",+ ],+ },+ },+ llm: {+ manual: llmManual,+ json: {+ topic: "llm",+ title: "Webstudio CLI Manual for LLMs",+ discovery: [+ "webstudio schema api --json",+ "webstudio permissions --json",+ "webstudio mcp",+ "MCP tool: status",+ "MCP resource: webstudio://project/tools",+ ],+ taskRecipes,+ useCaseScenarios,+ knownGaps: knownCliGaps,+ topLevelCommands: topLevelCommandCatalog,+ apiCommandsByArea,+ mcpOnlyCommands: mcpOnlyCommandCatalog,+ inputFileShapes,+ mcpArgumentExamples,+ commands: commandCatalog,+ readCommands,+ writeCommands,+ sessionBehavior: [+ "Read meta.session.source and meta.session.namespaces to understand whether data came from local cache, remote refresh, dry-run, or server-only execution.",+ "Use --refresh before a local-capable command when the cached snapshot may be stale.",+ "A mutation is durable only when meta.session.committed is true.",+ ],+ writes: [+ "Use MCP tools for fine-grained project edits.",+ "Use top-level CLI only for link/sync/build/publish/domains/permissions/discovery workflows.",+ ],+ rules: [+ "Always pass --json.",+ "Never guess ids for existing records. Read them first.",+ "Use the configured project only.",+ "Regenerate patches after VERSION_CONFLICT.",+ "Use stdout JSON as the contract.",+ ],+ },+ },+ mcp: {+ manual: mcpManual,+ json: {+ topic: "mcp",+ title: "Webstudio MCP Manual",+ startup: [+ "webstudio init --link <api-share-link> --json",+ "webstudio permissions --json",+ "webstudio mcp",+ ],+ discovery: [+ "tools/list",+ "resources/list",+ "meta.index",+ "meta.guide",+ "meta.get_more_tools",+ ],+ resources: [+ "webstudio://project/status",+ "webstudio://project/tools",+ "webstudio://project/guide",+ ],+ rules: [+ "stdout is reserved for MCP JSON-RPC while the server is running.",+ "Operate on the configured project only.",+ "Read ids before writing.",+ "Prefer semantic tools over apply-patch.",+ "Use status and refresh when cached namespaces may be stale.",+ "A mutation is durable only when meta.session.committed is true.",+ "For visual/design work, verify the rendered result with vision before finishing.",+ ],+ visionVerificationLoop: [...mcpVisionVerificationLoop],+ mcpArgumentExamples,+ screenshotVerification: screenshotVerificationSummary,+ },+ },+};++export const man = (options: ManOptions) => {+ const topic = options.topic ?? "api";+ const entry = topics[topic as keyof typeof topics];+ if (entry === undefined) {+ console.info(`Unknown manual topic "${topic}".++Available topics:++${Object.keys(topics)+ .map((name) => `- ${name}`)+ .join("\n")}`);+ return;+ }+ if (options.json === true) {+ printJson(entry.json);+ return;+ }+ console.info(entry.manual);+};diff --git a/packages/cli/src/commands/mcp.test.ts b/packages/cli/src/commands/mcp.test.tsnew file mode 100644index 0000000000..b4ed074db7--- /dev/null+++ b/packages/cli/src/commands/mcp.test.ts@@ -0,0 +1,23 @@+import { expect, test, vi } from "vitest";+import { mcpOptions } from "./mcp";++test("documents MCP stdio startup and discovery tools", () => {+ const yargs = {+ example: vi.fn(() => yargs),+ epilogue: vi.fn(() => yargs),+ };++ mcpOptions(yargs as never);++ expect(yargs.example).toHaveBeenCalledWith(+ "$0 mcp",+ "Run a local MCP server over stdio for the configured Webstudio project"+ );+ expect(yargs.example).toHaveBeenCalledWith(+ "MCP tool: meta.index",+ "Discover the concise capability catalog after the server starts"+ );+ expect(yargs.epilogue).toHaveBeenCalledWith(+ expect.stringContaining("tools/list")+ );+});diff --git a/packages/cli/src/commands/mcp.ts b/packages/cli/src/commands/mcp.tsnew file mode 100644index 0000000000..803e839f3d--- /dev/null+++ b/packages/cli/src/commands/mcp.ts@@ -0,0 +1,121 @@+import { stdin, stdout } from "node:process";+import {+ connectProjectSessionMcpServer,+ createMcpStdioTransport,+} from "@webstudio-is/project-build/mcp";+import { diffPngFiles } from "@webstudio-is/project-build/visual/screenshot-diff";+import { publicApiOperations } from "@webstudio-is/protocol";+import { resolveApiConnection } from "../api-connection";+import { getStableErrorCode } from "../error-codes";+import { createCliProjectSession } from "../project-session";+import { executeProjectSessionApiOperation } from "../project-session-api";+import { createPreviewController } from "../preview-server";+import {+ captureScreenshotWithBrowserInstall,+ installTesseractForOcr,+} from "../screenshot";+import {+ getVisionVerificationLoop,+ getVisionWorkflowSummary,+ visualVerificationRule,+} from "../mcp-guidance";+import { apiCompatibilityHeaders } from "./api";+import type { CommonYargsArgv } from "./yargs-types";++export const mcpOptions = (yargs: CommonYargsArgv) =>+ yargs+ .example(+ "$0 mcp",+ "Run a local MCP server over stdio for the configured Webstudio project"+ )+ .example(+ "MCP tool: meta.index",+ "Discover the concise capability catalog after the server starts"+ )+ .example(+ "MCP tool: meta.guide",+ "Ask for the recommended workflow and relevant tools"+ )+ .epilogue(+ [+ "Plain `webstudio mcp` starts the stdio MCP server.",+ "After startup, MCP clients discover capabilities with tools/list, resources/list, meta.index, meta.guide, and meta.get_more_tools.",+ "stdout is reserved for MCP JSON-RPC messages while the server is running.",+ ].join("\n")+ );++export const mcp = async () => {+ const connection = await resolveApiConnection();+ const apiConnection = {+ ...connection,+ headers: apiCompatibilityHeaders,+ };+ const session = createCliProjectSession({ connection: apiConnection });+ const preview = createPreviewController({ host: "127.0.0.1", port: 5173 });+ await connectProjectSessionMcpServer({+ operations: publicApiOperations,+ createProjectSession: () => session,+ executeOperation: ({ command, input, dryRun }) =>+ executeProjectSessionApiOperation({+ command,+ input,+ connection: apiConnection,+ createProjectSession: () => session,+ dryRun,+ }),+ async startPreview(input) {+ return preview.startAndWait(input);+ },+ async getPreviewStatus() {+ return preview.status();+ },+ async captureScreenshot(input) {+ const url =+ input.url ??+ (input.path === undefined ? undefined : preview.resolveUrl(input.path));+ if (url === undefined) {+ throw new Error("MCP screenshot requires url or path.");+ }+ if (input.path !== undefined) {+ await preview.startAndWait();+ }+ const result = await captureScreenshotWithBrowserInstall({+ url,+ output: input.output,+ width: input.viewport.width,+ height: input.viewport.height,+ browser: input.browser,+ browserPath: input.browserPath,+ waitUntil: input.waitUntil,+ waitForSelector: input.waitForSelector,+ waitForTimeout: input.waitForTimeout,+ timeout: input.timeout,+ isJson: false,+ isMcp: true,+ isInteractive: false,+ confirmInstall: async () => false,+ });+ return {+ output: result.output,+ browserPath: result.browser.path,+ browser: result.browser.browser,+ viewport: result.viewport,+ elapsedMs: result.elapsedMs,+ warnings: result.warnings,+ };+ },+ async diffScreenshots(input) {+ return diffPngFiles(input);+ },+ async installOcr() {+ return installTesseractForOcr();+ },+ guidance: {+ visualVerificationRule,+ getVisionVerificationLoop,+ getVisionWorkflowSummary,+ },+ getErrorCode: getStableErrorCode,+ transport: await createMcpStdioTransport({ stdin, stdout }),+ });+};diff --git a/packages/cli/src/commands/preview.test.ts b/packages/cli/src/commands/preview.test.tsnew file mode 100644index 0000000000..725841327a--- /dev/null+++ b/packages/cli/src/commands/preview.test.ts@@ -0,0 +1,33 @@+import { expect, test } from "vitest";+import { preview, previewOptions } from "./preview";+import type { CommonYargsArgv } from "./yargs-types";++test("rejects empty preview host", async () => {+ await expect(+ preview({+ host: "",+ port: 5173,+ generate: false,+ assets: true,+ template: ["ssg"],+ })+ ).rejects.toThrow("--host must not be empty.");+});++test("documents generated app dependency setup", () => {+ const yargs = {+ option: () => yargs,+ example: () => yargs,+ epilogue: (text: string) => {+ epilogueText = text;+ return yargs;+ },+ } as unknown as CommonYargsArgv;+ let epilogueText = "";++ previewOptions(yargs);++ expect(epilogueText).toContain("does not install app dependencies");+ expect(epilogueText).toContain("npm install or pnpm install");+ expect(epilogueText).toContain("react-router or vite");+});diff --git a/packages/cli/src/commands/preview.ts b/packages/cli/src/commands/preview.tsnew file mode 100644index 0000000000..ae2f2fb68d--- /dev/null+++ b/packages/cli/src/commands/preview.ts@@ -0,0 +1,89 @@+import { access } from "node:fs/promises";+import { log } from "@clack/prompts";+import { prebuild } from "../prebuild";+import { LOCAL_DATA_FILE } from "../config";+import { HandledCliError } from "../errors";+import {+ getPreviewUrl,+ startPreviewDevServer,+ waitForPreviewExit,+} from "../preview-server";+import type {+ CommonYargsArgv,+ StrictYargsOptionsToInterface,+} from "./yargs-types";+import { buildOptions } from "./build";++export const previewOptions = (yargs: CommonYargsArgv) =>+ buildOptions(yargs)+ .option("host", {+ type: "string",+ default: "127.0.0.1",+ describe: "Host used by the generated project dev server",+ })+ .option("port", {+ type: "number",+ default: 5173,+ describe: "Port used by the generated project dev server",+ })+ .option("generate", {+ type: "boolean",+ default: true,+ describe:+ "Regenerate project files from .webstudio/data.json before starting the dev server",+ })+ .example(+ "webstudio preview --template ssg --port 5173",+ "Regenerate files and start the generated site at http://127.0.0.1:5173"+ )+ .example(+ "webstudio preview --template react-router --generate false",+ "Start an already generated React Router app without rewriting project files"+ )+ .epilogue(+ [+ "Preview runs the generated app dev server; it does not install app dependencies.",+ "For a fresh checkout, copied fixture, or newly generated app, run npm install or pnpm install in the generated project before preview.",+ "If preview exits with a missing command/package such as react-router or vite, install the generated app dependencies and retry.",+ ].join("\n")+ );++type PreviewOptions = StrictYargsOptionsToInterface<typeof previewOptions>;++const isPositivePort = (value: number) =>+ Number.isInteger(value) && value > 0 && value <= 65535;++export const preview = async (options: PreviewOptions) => {+ if (options.host.length === 0) {+ throw new Error("--host must not be empty.");+ }+ if (isPositivePort(options.port) === false) {+ throw new Error("--port must be an integer between 1 and 65535.");+ }+ try {+ await access(LOCAL_DATA_FILE);+ } catch (error: unknown) {+ if (error instanceof Error && "code" in error && error.code === "ENOENT") {+ log.error(+ "You need to link and sync a Webstudio project before previewing it. Run `webstudio link` and `webstudio sync` first."+ );+ throw new HandledCliError();+ }+ throw error;+ }++ if (options.generate) {+ await prebuild({+ assets: options.assets,+ template: options.template,+ });+ }++ const url = getPreviewUrl({ host: options.host, port: options.port });+ log.success(`Preview server starting at ${url}`);+ const server = startPreviewDevServer({+ host: options.host,+ port: options.port,+ });+ await waitForPreviewExit(server.process);+};diff --git a/packages/cli/src/commands/schema.test.ts b/packages/cli/src/commands/schema.test.tsnew file mode 100644index 0000000000..5d97825d6b--- /dev/null+++ b/packages/cli/src/commands/schema.test.ts@@ -0,0 +1,129 @@+import { afterEach, expect, test, vi } from "vitest";+import { apiCommandMetadata, cliCommandMetadata } from "./api-command-metadata";+import { schema } from "./schema";++afterEach(() => {+ vi.restoreAllMocks();+});++test("prints api command schema as json", () => {+ vi.spyOn(console, "info").mockImplementation(() => undefined);++ schema({ topic: "api", json: true });++ const output = JSON.parse(vi.mocked(console.info).mock.calls.at(-1)?.[0]);+ expect(output.projectScope).toContain("single project");+ expect(+ output.topLevelCommands.map((command: { name: string }) => command.name)+ ).toEqual([+ "init",+ "link",+ "sync",+ "build",+ "preview",+ "screenshot",+ "permissions",+ "publish",+ "domains",+ "schema",+ "man",+ "mcp",+ ]);+ expect(+ output.topLevelCommands.map((command: { name: string }) => command.name)+ ).not.toEqual(expect.arrayContaining(["publish deploy", "domains list"]));+ expect(output.commandGroups).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ name: "publish",+ commands: expect.arrayContaining([+ expect.objectContaining({ name: "publish deploy" }),+ ]),+ }),+ expect.objectContaining({+ name: "domains",+ commands: expect.arrayContaining([+ expect.objectContaining({ name: "domains list" }),+ ]),+ }),+ ])+ );+ expect(+ output.commands.map((command: { name: string }) => command.name)+ ).toEqual(cliCommandMetadata.map((metadata) => metadata.cliCommand));+ expect(output.commands).toEqual(+ expect.arrayContaining([+ expect.objectContaining({ name: "permissions", method: "query" }),+ expect.objectContaining({+ name: "publish deploy",+ operation: "publish",+ method: "mutation",+ }),+ expect.objectContaining({+ name: "domains list",+ operation: "list-domains",+ method: "query",+ }),+ ])+ );+ expect(output.commands).not.toEqual(+ expect.arrayContaining([+ expect.objectContaining({ name: "apply-patch" }),+ expect.objectContaining({ name: "list-assets" }),+ expect.objectContaining({ name: "create-page-from-template" }),+ ])+ );+ expect(output.mcp.toolCount).toBe(apiCommandMetadata.length);+ expect(output.mcp.discovery).toContain("meta.get_more_tools");+ expect(output.mcp.resources).toContain("webstudio://project/tools");+ expect(output.mcp.argumentExamples["update-styles"]).toEqual([+ {+ updates: [+ {+ instanceId: "instance-id",+ property: "color",+ value: { type: "keyword", value: "red" },+ },+ ],+ },+ ]);+ for (const command of output.commands) {+ expect(command).not.toHaveProperty("trpcPath");+ }+ expect(output.useCases).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ useCase: "List breakpoints",+ commands: ["MCP tool: list-breakpoints {}"],+ }),+ expect.objectContaining({+ useCase: "Create page from template",+ commands: [+ 'MCP tool: create-page-from-template {"templateId":"<templateId>","name":"Landing","path":"/landing"}',+ ],+ }),+ expect.objectContaining({+ useCase: "Discover CLI/API capabilities",+ commands: expect.arrayContaining(["webstudio man mcp --json"]),+ }),+ expect.objectContaining({+ useCase: "Manage marketplace metadata",+ patchNamespaces: ["marketplaceProduct"],+ }),+ ])+ );+ expect(output.patch.namespaces).toContain("dataSources");+ expect(output.session.refreshFlag).toContain("--refresh");+ expect(output.session.resultMetadata).toContain("meta.session");+});++test("requires json output", () => {+ vi.spyOn(console, "error").mockImplementation(() => undefined);++ expect(() => schema({ topic: "api", json: false })).toThrow(+ "Handled CLI error"+ );+ expect(console.error).toHaveBeenCalledWith(+ "schema currently requires --json."+ );+});diff --git a/packages/cli/src/commands/schema.ts b/packages/cli/src/commands/schema.tsnew file mode 100644index 0000000000..bc046e2907--- /dev/null+++ b/packages/cli/src/commands/schema.ts@@ -0,0 +1,135 @@+import { buildPatchNamespaces } from "@webstudio-is/protocol";+import { mcpArgumentExamples } from "@webstudio-is/project-build/mcp";+import { HandledCliError } from "../errors";+import { printJson } from "../json-output";+import { useCaseScenarios } from "./api-command-docs";+import {+ apiCommandMetadata,+ cliCommandGroupMetadata,+ cliCommandMetadata,+ formatApiUseCaseCommand,+ topLevelCliCommandMetadata,+} from "./api-command-metadata";+import type {+ CommonYargsArgv,+ StrictYargsOptionsToInterface,+} from "./yargs-types";++export const schemaOptions = (yargs: CommonYargsArgv) =>+ yargs+ .positional("topic", {+ type: "string",+ describe: "Schema topic to print",+ default: "api",+ })+ .option("json", {+ type: "boolean",+ describe: "Required. Print a machine-readable JSON schema to stdout",+ default: false,+ });++type SchemaOptions = StrictYargsOptionsToInterface<typeof schemaOptions> & {+ topic?: string;+};++const topLevelCommands = topLevelCliCommandMetadata.map(+ ({ command, description, examples }) => ({+ name: command,+ summary: description,+ examples,+ })+);++const cliCommands = cliCommandMetadata.map((command) => ({+ name: command.cliCommand,+ operation: command.operation,+ summary: command.description,+ method: command.method,+ permit: command.permit,+ requiredOptions: command.requiredOptions ?? ["json"],+ examples: (command.examples ?? []).map(formatApiUseCaseCommand),+}));++const commandGroups = cliCommandGroupMetadata.map(+ ({ command, description }) => ({+ name: command,+ summary: description,+ commands: cliCommands.filter(({ name }) => name.startsWith(`${command} `)),+ })+);++const apiSchema = {+ name: "webstudio-cli",+ version: 1,+ projectScope:+ "All high-level API commands operate on the single project configured by webstudio link or webstudio init --link.",+ requiredOutputMode:+ "Use --json. Successful responses are { ok: true, data, meta }. Failures are { ok: false, error, meta }.",+ topLevelCommands,+ commandGroups,+ commands: cliCommands,+ mcp: {+ command: "webstudio mcp",+ toolCount: apiCommandMetadata.length,+ tools:+ "MCP exposes the full project operation catalog, including fine-grained page, instance, props, styles, tokens, variables, resources, and assets tools.",+ discovery: [+ "tools/list",+ "resources/list",+ "meta.index",+ "meta.guide",+ "meta.get_more_tools",+ ],+ resources: [+ "webstudio://project/status",+ "webstudio://project/tools",+ "webstudio://project/guide",+ ],+ argumentExamples: mcpArgumentExamples,+ },+ session: {+ stateFile: ".webstudio/project-session.json",+ refreshFlag:+ "Use --refresh to refresh required namespaces before local-capable commands.",+ localReads:+ "Local-capable read commands use compatible cached namespaces and fetch only missing or stale namespaces.",+ localMutations:+ "Local-capable mutation commands build patches locally, commit with the cached build version, and update local state only after the remote commit succeeds.",+ serverOnly:+ "Server-only commands run remotely and invalidate/refetch namespaces declared by the public operation catalog.",+ resultMetadata:+ "Successful command JSON includes meta.session with operationId, buildId, version, source, committed, compatibility, namespace metadata, and diagnostics.",+ },+ useCases: useCaseScenarios,+ patch: {+ validationCommand:+ "No top-level CLI validation command. Prefer semantic MCP tools; use MCP apply-patch only for known-valid BuildPatchTransaction[] payloads.",+ writeCommand: "MCP tool: apply-patch",+ transactionInput:+ "Either BuildPatchTransaction[] or { transactions: BuildPatchTransaction[] }",+ namespaces: buildPatchNamespaces,+ operations: ["add", "remove", "replace"],+ rules: [+ "Use MCP tool: snapshot before writing and use the returned latest build version as baseVersion.",+ "Use semantic MCP read tools first, then snapshot for exact patch paths.",+ "Regenerate patches after a VERSION_CONFLICT failure.",+ ],+ },+};++export const schema = (options: SchemaOptions) => {+ try {+ if (options.json !== true) {+ throw new Error("schema currently requires --json.");+ }+ if ((options.topic ?? "api") !== "api") {+ throw new Error(+ `Unknown schema topic "${options.topic}". Available topics: api`+ );+ }+ printJson(apiSchema);+ } catch (error) {+ console.error(error instanceof Error ? error.message : String(error));+ throw new HandledCliError();+ }+};diff --git a/packages/cli/src/commands/screenshot.test.ts b/packages/cli/src/commands/screenshot.test.tsnew file mode 100644index 0000000000..baf613fb48--- /dev/null+++ b/packages/cli/src/commands/screenshot.test.ts@@ -0,0 +1,200 @@+import { mkdtemp, rm } from "node:fs/promises";+import { join } from "node:path";+import { tmpdir } from "node:os";+import { afterEach, expect, test, vi } from "vitest";+import { screenshot } from "./screenshot";+import {+ BrowserInstallUnavailableError,+ BrowserNotFoundError,+} from "../screenshot";+import { HandledCliError } from "../errors";++afterEach(() => {+ vi.restoreAllMocks();+});++test("prints json result with a browser executable path", async () => {+ const folder = await mkdtemp(join(tmpdir(), "webstudio-screenshot-test-"));+ const browserPath = join(folder, "browser");+ vi.spyOn(console, "info").mockImplementation(() => undefined);+ const captureScreenshotWithBrowserInstall = vi.fn(async () => ({+ output: join(folder, "current.png"),+ browser: {+ path: browserPath,+ source: "option" as const,+ browser: "chrome" as const,+ },+ viewport: { width: 800, height: 600 },+ elapsedMs: 12,+ warnings: [] as string[],+ }));++ try {+ await screenshot(+ {+ url: "https://example.com",+ output: join(folder, "current.png"),+ width: 800,+ height: 600,+ browser: "auto",+ browserPath,+ waitUntil: "networkidle",+ waitForSelector: "#ready",+ waitForTimeout: 500,+ timeout: 10_000,+ json: true,+ },+ { captureScreenshotWithBrowserInstall }+ );+ } finally {+ await rm(folder, { recursive: true, force: true });+ }++ expect(captureScreenshotWithBrowserInstall).toHaveBeenCalledWith(+ expect.objectContaining({+ url: "https://example.com",+ output: join(folder, "current.png"),+ width: 800,+ height: 600,+ browser: "auto",+ browserPath,+ waitUntil: "networkidle",+ waitForSelector: "#ready",+ waitForTimeout: 500,+ timeout: 10_000,+ isJson: true,+ isMcp: false,+ })+ );+ const output = JSON.parse(vi.mocked(console.info).mock.calls.at(-1)?.[0]);+ expect(output).toEqual({+ ok: true,+ data: {+ output: expect.stringContaining("current.png"),+ browserPath,+ browser: "chrome",+ viewport: { width: 800, height: 600 },+ elapsedMs: 12,+ warnings: [],+ },+ meta: { command: "screenshot" },+ });+});++test("rejects invalid screenshot readiness options", async () => {+ const captureScreenshotWithBrowserInstall = vi.fn();++ await expect(+ screenshot(+ {+ url: "https://example.com",+ width: 800,+ height: 600,+ waitUntil: "interactive",+ },+ { captureScreenshotWithBrowserInstall }+ )+ ).rejects.toThrow(+ "--wait-until must be commit, domcontentloaded, load, or networkidle."+ );++ await expect(+ screenshot(+ {+ url: "https://example.com",+ width: 800,+ height: 600,+ waitForTimeout: -1,+ },+ { captureScreenshotWithBrowserInstall }+ )+ ).rejects.toThrow("--wait-for-timeout must be a non-negative integer.");++ await expect(+ screenshot(+ {+ url: "https://example.com",+ width: 800,+ height: 600,+ waitForSelector: "",+ },+ { captureScreenshotWithBrowserInstall }+ )+ ).rejects.toThrow("--wait-for-selector must not be empty.");++ await expect(+ screenshot(+ {+ url: "https://example.com",+ width: 800,+ height: 600,+ timeout: 0,+ },+ { captureScreenshotWithBrowserInstall }+ )+ ).rejects.toThrow("--timeout must be a positive integer.");++ expect(captureScreenshotWithBrowserInstall).not.toHaveBeenCalled();+});++test("prints browser-not-found json error", async () => {+ vi.spyOn(console, "info").mockImplementation(() => undefined);+ const captureScreenshotWithBrowserInstall = vi.fn(async () => {+ throw new BrowserNotFoundError(["/usr/bin/chromium"]);+ });++ await expect(+ screenshot(+ {+ url: "https://example.com",+ width: 800,+ height: 600,+ json: true,+ },+ { captureScreenshotWithBrowserInstall }+ )+ ).rejects.toBeInstanceOf(HandledCliError);++ expect(JSON.parse(vi.mocked(console.info).mock.calls.at(-1)?.[0])).toEqual(+ expect.objectContaining({+ ok: false,+ error: expect.objectContaining({+ code: "BROWSER_NOT_FOUND",+ message: expect.stringContaining("No supported Chromium browser"),+ }),+ meta: { command: "screenshot" },+ })+ );+});++test("prints browser-install-unavailable json error", async () => {+ vi.spyOn(console, "info").mockImplementation(() => undefined);+ const captureScreenshotWithBrowserInstall = vi.fn(async () => {+ throw new BrowserInstallUnavailableError();+ });++ await expect(+ screenshot(+ {+ url: "https://example.com",+ width: 800,+ height: 600,+ json: true,+ },+ { captureScreenshotWithBrowserInstall }+ )+ ).rejects.toBeInstanceOf(HandledCliError);++ expect(JSON.parse(vi.mocked(console.info).mock.calls.at(-1)?.[0])).toEqual(+ expect.objectContaining({+ ok: false,+ error: expect.objectContaining({+ code: "BROWSER_INSTALL_UNAVAILABLE",+ message: expect.stringContaining(+ "cannot install Chromium automatically"+ ),+ }),+ meta: { command: "screenshot" },+ })+ );+});diff --git a/packages/cli/src/commands/screenshot.ts b/packages/cli/src/commands/screenshot.tsnew file mode 100644index 0000000000..e74b8333e5--- /dev/null+++ b/packages/cli/src/commands/screenshot.ts@@ -0,0 +1,251 @@+import { cancel, confirm, isCancel, log } from "@clack/prompts";+import {+ defaultScreenshotTimeout,+ defaultScreenshotWaitForTimeout,+ defaultScreenshotWaitUntil,+ isScreenshotWaitUntil,+ screenshotBrowserChoices,+ screenshotWaitUntilValues,+ type ScreenshotBrowser,+ type ScreenshotWaitUntil,+} from "@webstudio-is/project-build/visual/screenshot-browser";+import { printJson } from "../json-output";+import { HandledCliError } from "../errors";+import {+ BrowserInstallUnavailableError,+ BrowserNotFoundError,+ captureScreenshotWithBrowserInstall,+ chromeDownloadUrl,+ chromiumDownloadUrl,+ getNoBrowserFoundMessage,+} from "../screenshot";+import type {+ CommonYargsArgv,+ StrictYargsOptionsToInterface,+} from "./yargs-types";++export const screenshotOptions = (yargs: CommonYargsArgv) =>+ yargs+ .positional("url", {+ type: "string",+ describe: "URL to capture",+ })+ .option("output", {+ type: "string",+ alias: "o",+ describe:+ "PNG output path. Defaults to a webstudio-screenshot file in the system temp directory.",+ })+ .option("width", {+ type: "number",+ default: 1440,+ describe: "Viewport width in CSS pixels",+ })+ .option("height", {+ type: "number",+ default: 900,+ describe: "Viewport height in CSS pixels",+ })+ .option("browser", {+ type: "string",+ choices: screenshotBrowserChoices,+ default: "auto",+ describe:+ "Browser family to use. Auto prefers Chromium, then Chrome, Edge, and Brave.",+ })+ .option("browser-path", {+ type: "string",+ describe:+ "Explicit Chromium-family browser executable path. Also supported through WEBSTUDIO_BROWSER_PATH.",+ })+ .option("wait-until", {+ type: "string",+ choices: screenshotWaitUntilValues,+ default: defaultScreenshotWaitUntil,+ describe:+ "Page readiness event to wait for before capture. networkidle waits for the browser network idle lifecycle event.",+ })+ .option("wait-for-selector", {+ type: "string",+ describe: "CSS selector that must exist before capture.",+ })+ .option("wait-for-timeout", {+ type: "number",+ default: defaultScreenshotWaitForTimeout,+ describe:+ "Extra milliseconds to wait after page readiness, selector, fonts, and layout frames.",+ })+ .option("timeout", {+ type: "number",+ default: defaultScreenshotTimeout,+ describe: "Maximum milliseconds to wait for page readiness.",+ })+ .option("json", {+ type: "boolean",+ default: false,+ describe: "Print JSON output",+ });++type ScreenshotOptions = StrictYargsOptionsToInterface<+ typeof screenshotOptions+> & {+ url?: string;+ browser?: ScreenshotBrowser;+ waitUntil?: ScreenshotWaitUntil;+ waitForSelector?: string;+ waitForTimeout?: number;+ timeout?: number;+};++const isPositiveInteger = (value: number) =>+ Number.isInteger(value) && value > 0;++const printScreenshotError = ({+ code,+ message,+ json,+}: {+ code: "BROWSER_NOT_FOUND" | "BROWSER_INSTALL_UNAVAILABLE";+ message: string;+ json: boolean;+}) => {+ if (json) {+ printJson({+ ok: false,+ error: {+ code,+ message,+ fixes: [+ `Install Chromium: ${chromiumDownloadUrl}`,+ `Install Google Chrome: ${chromeDownloadUrl}`,+ "Pass --browser-path /path/to/chromium",+ "Set WEBSTUDIO_BROWSER_PATH=/path/to/chromium",+ ],+ },+ meta: { command: "screenshot" },+ });+ return;+ }+ log.error(message);+};++type ScreenshotCommandDependencies = {+ captureScreenshotWithBrowserInstall: typeof captureScreenshotWithBrowserInstall;+};++const defaultScreenshotCommandDependencies: ScreenshotCommandDependencies = {+ captureScreenshotWithBrowserInstall,+};++export const screenshot = async (+ rawOptions: unknown,+ dependencies = defaultScreenshotCommandDependencies+) => {+ const options = rawOptions as ScreenshotOptions;+ if (options.url === undefined || options.url.length === 0) {+ throw new Error("Please specify a URL to capture.");+ }+ if (isPositiveInteger(options.width) === false) {+ throw new Error("--width must be a positive integer.");+ }+ if (isPositiveInteger(options.height) === false) {+ throw new Error("--height must be a positive integer.");+ }+ if (+ options.waitUntil !== undefined &&+ isScreenshotWaitUntil(options.waitUntil) === false+ ) {+ throw new Error(+ "--wait-until must be commit, domcontentloaded, load, or networkidle."+ );+ }+ if (+ options.waitForTimeout !== undefined &&+ (Number.isInteger(options.waitForTimeout) === false ||+ options.waitForTimeout < 0)+ ) {+ throw new Error("--wait-for-timeout must be a non-negative integer.");+ }+ if (options.waitForSelector !== undefined && options.waitForSelector === "") {+ throw new Error("--wait-for-selector must not be empty.");+ }+ if (+ options.timeout !== undefined &&+ isPositiveInteger(options.timeout) === false+ ) {+ throw new Error("--timeout must be a positive integer.");+ }++ try {+ const result = await dependencies.captureScreenshotWithBrowserInstall({+ url: options.url,+ output: options.output,+ width: options.width,+ height: options.height,+ browser: options.browser ?? "auto",+ browserPath: options.browserPath,+ waitUntil: options.waitUntil ?? defaultScreenshotWaitUntil,+ waitForSelector: options.waitForSelector,+ waitForTimeout: options.waitForTimeout ?? defaultScreenshotWaitForTimeout,+ timeout: options.timeout ?? defaultScreenshotTimeout,+ isJson: options.json,+ isMcp: false,+ isInteractive:+ process.stdin.isTTY === true && process.stdout.isTTY === true,+ async confirmInstall(installCommand) {+ const answer = await confirm({+ message: `No supported browser was found. Install Chromium now with "${installCommand.label}"?`,+ initialValue: true,+ });+ if (isCancel(answer)) {+ cancel("Screenshot capture is cancelled.");+ throw new HandledCliError();+ }+ return answer;+ },+ });++ if (options.json) {+ printJson({+ ok: true,+ data: {+ output: result.output,+ browserPath: result.browser.path,+ browser: result.browser.browser,+ viewport: result.viewport,+ elapsedMs: result.elapsedMs,+ warnings: result.warnings,+ },+ meta: { command: "screenshot" },+ });+ return;+ }+ log.success(`Screenshot saved to ${result.output}`);+ } catch (error) {+ if (error instanceof BrowserNotFoundError) {+ printScreenshotError({+ code: "BROWSER_NOT_FOUND",+ message: getNoBrowserFoundMessage(error.checked),+ json: options.json,+ });+ throw new HandledCliError();+ }+ if (error instanceof BrowserInstallUnavailableError) {+ printScreenshotError({+ code: "BROWSER_INSTALL_UNAVAILABLE",+ message: [+ "No supported Chromium browser was found, and Webstudio cannot install Chromium automatically on this system.",+ "",+ "Install Chromium manually and try again:",+ `- Chromium: ${chromiumDownloadUrl}`,+ `- Google Chrome: ${chromeDownloadUrl}`,+ "",+ "Or pass --browser-path /path/to/chromium.",+ ].join("\n"),+ json: options.json,+ });+ throw new HandledCliError();+ }+ throw error;+ }+};diff --git a/packages/cli/src/commands/sync.test.ts b/packages/cli/src/commands/sync.test.tsindex 594c27a7b8..cd453b7887 100644--- a/packages/cli/src/commands/sync.test.ts+++ b/packages/cli/src/commands/sync.test.ts@@ -8,6 +8,7 @@ import {createPublishedProjectBundleFixture,} from "@webstudio-is/protocol/fixtures";import { createFileIfNotExists, isFileExists } from "../fs-utils";+import { resolveApiConnection } from "../api-connection";import { sync } from "./sync";const originalCwd = process.cwd();@@ -27,6 +28,7 @@ const dependencies = {loadProjectBundleByBuildId,loadProjectBundleByProjectId,readFile,+ resolveApiConnection,spinner: () => indicator,writeFile,};diff --git a/packages/cli/src/commands/sync.ts b/packages/cli/src/commands/sync.tsindex 89183174c4..2116a15142 100644--- a/packages/cli/src/commands/sync.ts+++ b/packages/cli/src/commands/sync.ts@@ -1,25 +1,15 @@import { readFile, writeFile } from "node:fs/promises";-import { cwd } from "node:process";import { join } from "node:path";-import pc from "picocolors";+import { cwd } from "node:process";import { spinner } from "@clack/prompts";-import {- bundleVersion,- publishedProjectBundle,- type PublishedProjectBundle,-} from "@webstudio-is/protocol";+import { type PublishedProjectBundle } from "@webstudio-is/protocol";import {loadProjectBundleByBuildId,loadProjectBundleByProjectId,+ toLocalProjectBundle,} from "@webstudio-is/http-client";import { createFileIfNotExists, isFileExists } from "../fs-utils";-import {- GLOBAL_CONFIG_FILE,- LOCAL_CONFIG_FILE,- LOCAL_DATA_FILE,- jsonToGlobalConfig,- jsonToLocalConfig,-} from "../config";+import { LOCAL_DATA_FILE } from "../config";import type {CommonYargsArgv,StrictYargsOptionsToInterface,@@ -27,6 +17,7 @@ import type {import { HandledCliError } from "../errors";import { apiCompatibilityHeaders, stopSpinnerWithError } from "./api";import { downloadAssetFiles } from "../asset-files";+import { resolveApiConnection } from "../api-connection";type SyncDependencies = {createFileIfNotExists: typeof createFileIfNotExists;@@ -35,6 +26,7 @@ type SyncDependencies = {loadProjectBundleByBuildId: typeof loadProjectBundleByBuildId;loadProjectBundleByProjectId: typeof loadProjectBundleByProjectId;readFile: typeof readFile;+ resolveApiConnection: typeof resolveApiConnection;spinner: typeof spinner;writeFile: typeof writeFile;};@@ -46,36 +38,11 @@ const defaultDependencies: SyncDependencies = {loadProjectBundleByBuildId,loadProjectBundleByProjectId,readFile,+ resolveApiConnection,spinner,writeFile,};-const toLocalProjectBundle = (project: PublishedProjectBundle) => {- const normalizedProject = publishedProjectBundle.parse(project);- const {- assets,- build,- bundleVersion: synchronizedBundleVersion,- origin,- page,- pages,- projectDomain,- projectTitle,- user,- } = normalizedProject;- return {- bundleVersion: synchronizedBundleVersion ?? bundleVersion,- build,- page,- pages,- assets,- user,- projectDomain,- projectTitle,- origin,- };-};-export const syncOptions = (yargs: CommonYargsArgv) =>yargs.option("buildId", {@@ -129,38 +96,23 @@ export const sync = async (throw error;}} else {- const globalConfigText = await dependencies.readFile(- GLOBAL_CONFIG_FILE,- "utf-8"- );- const globalConfig = jsonToGlobalConfig(JSON.parse(globalConfigText));-- if ((await dependencies.isFileExists(LOCAL_CONFIG_FILE)) === false) {- syncing.stop(- `Local config file is not found. Please make sure current directory is a webstudio project`,- 2- );- throw new HandledCliError();- }-- const localConfigText = await dependencies.readFile(- join(cwd(), LOCAL_CONFIG_FILE),- "utf-8"- );-- const localConfig = jsonToLocalConfig(JSON.parse(localConfigText));-- const projectConfig = globalConfig[localConfig.projectId];-- if (projectConfig === undefined) {+ let connection: Awaited<ReturnType<typeof resolveApiConnection>>;+ try {+ connection = await dependencies.resolveApiConnection(dependencies);+ } catch (error) {+ const message = error instanceof Error ? error.message : String(error);syncing.stop(- `Project config is not found, please run ${pc.dim("webstudio link")}`,+ message.includes("Local config file")+ ? "Local config file is not found. Please make sure current directory is a webstudio project"+ : message.includes("Project config")+ ? "Project config is not found, please run webstudio link"+ : message,2);throw new HandledCliError();}- const { origin, token } = projectConfig;+ const { origin, authToken, projectId } = connection;syncing.message(`Synchronizing project bundle from ${origin}`);try {@@ -168,13 +120,13 @@ export const sync = async (options.buildId !== undefined? await dependencies.loadProjectBundleByBuildId({buildId: options.buildId,- authToken: token,+ authToken,origin,headers: apiCompatibilityHeaders,}): await dependencies.loadProjectBundleByProjectId({- projectId: localConfig.projectId,- authToken: token,+ projectId,+ authToken,origin,headers: apiCompatibilityHeaders,});diff --git a/packages/cli/src/docs.generated.ts b/packages/cli/src/docs.generated.tsnew file mode 100644index 0000000000..7c896f01f4--- /dev/null+++ b/packages/cli/src/docs.generated.ts@@ -0,0 +1,16 @@+// This file is generated by scripts/generate-docs.mjs.+// Edit markdown files in src/docs instead.+export const cliDocs = {+ "api-use-cases":+ '# CLI API Use Cases\n\n## Link/configure one project\n\nCommands:\n\n- webstudio init --link <api-share-link> --json\n\nNotes:\n\n- Writes local project id and global origin/token config.\n\n## Identify current token\n\nCommands:\n\n- MCP tool: whoami {}\n\n## Check token permissions\n\nCommands:\n\n- webstudio permissions --json\n\n## Inspect project/build/version\n\nCommands:\n\n- MCP tool: inspect {}\n- MCP tool: snapshot {"include":["pages","instances","styles"]}\n\n## Discover CLI/API capabilities\n\nCommands:\n\n- webstudio schema api --json\n- webstudio man api --json\n- webstudio man llm --json\n- webstudio man mcp --json\n- MCP tool: meta.index {}\n- MCP tool: meta.guide {"brief":"Create a pricing page"}\n- MCP tool: meta.get_more_tools {"brief":"update-styles"}\n\nNotes:\n\n- Use `tools/list` for machine-readable MCP tool schemas.\n- Use `resources/list` and `resources/read` for longer MCP resources such as `webstudio://project/tools` and `webstudio://project/guide`.\n\n## Inspect and refresh MCP session cache\n\nCommands:\n\n- MCP tool: status {}\n- MCP tool: refresh {"namespaces":["pages","instances","styles"]}\n- MCP tool: reset-session {}\n\nNotes:\n\n- Use status before a task to understand the cached ProjectSession state.\n- Use refresh when project data may have changed outside the current MCP session.\n- Use reset-session when local cached state is corrupt or incompatible.\n\n## Visually verify rendered work with AI vision\n\nCommands:\n\n- MCP tool: preview.start {"host":"127.0.0.1","port":5173}\n- MCP tool: preview.status {}\n- MCP tool: screenshot {"path":"/","output":"current.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot.diff {"baselinePath":"before.png","currentPath":"current.png","outputDir":".webstudio/screenshots"}\n- MCP tool: vision.install-ocr {"confirm":true}\n\nNotes:\n\n- Use this after page/content/style mutations and after generated project files are current so a vision-capable AI can see what was actually built.\n- Use waitForSelector when the rendered app has a reliable ready marker, waitUntil:"networkidle" for network-heavy pages, and waitForTimeout only for final visual settling.\n- For a fresh checkout, copied fixture, or newly generated app, run npm install or pnpm install in the generated project before preview.start or webstudio preview.\n- If preview fails with a missing generated-app command/package such as react-router or vite, install the generated app dependencies and retry.\n- When a baseline exists, use screenshot.diff to get changed regions, OCR textAnalysis, and diff artifact paths before deciding whether the result matches.\n- If screenshot.diff reports OCR unavailable and the user agrees to install it, call vision.install-ocr {"confirm":true}; otherwise continue with pixel diff and visual inspection.\n- Compare the PNG, OCR text evidence, and diff artifacts against the user\'s intent for layout, typography, colors, spacing, imagery, and responsive framing; then iterate with focused mutations.\n- Root CLI equivalent: webstudio preview --template ssg, then webstudio screenshot <url> --output current.png.\n\n## List pages\n\nCommands:\n\n- MCP tool: list-pages {"includeFolders":true}\n\n## Read page by id\n\nCommands:\n\n- MCP tool: get-page {"pageId":"<pageId>"}\n\n## Read page by path\n\nCommands:\n\n- MCP tool: get-page-by-path {"path":"/pricing"}\n\n## Create page\n\nCommands:\n\n- MCP tool: create-page {"name":"Pricing","path":"/pricing"}\n\n## Update page settings/metadata\n\nCommands:\n\n- MCP tool: update-page {"pageId":"<pageId>","title":"Pricing","description":"Plans","status":"200"}\n- MCP tool: update-page {"pageId":"<pageId>","auth":{"login":"<login>","password":"<password>"}}\n\n## Read project settings\n\nCommands:\n\n- MCP tool: get-project-settings {}\n\n## Update project settings\n\nCommands:\n\n- MCP tool: update-project-settings {"settings":"project-settings.json contents"}\n\n## List redirects\n\nCommands:\n\n- MCP tool: list-redirects {}\n\n## Create redirect\n\nCommands:\n\n- MCP tool: create-redirect {"oldPath":"/old","newPath":"/new","status":301}\n\n## Update redirect\n\nCommands:\n\n- MCP tool: update-redirect {"oldPath":"/old","newPath":"/newer","status":302}\n- MCP tool: update-redirect {"oldPath":"/old","status":null}\n\n## Delete redirect\n\nCommands:\n\n- MCP tool: delete-redirect {"oldPath":"/old"}\n\n## List breakpoints\n\nCommands:\n\n- MCP tool: list-breakpoints {}\n\n## Create breakpoint\n\nCommands:\n\n- MCP tool: create-breakpoint {"breakpointId":"tablet","label":"Tablet","maxWidth":991}\n\n## Update breakpoint\n\nCommands:\n\n- MCP tool: update-breakpoint {"breakpointId":"tablet","label":"Tablet","maxWidth":1023}\n- MCP tool: update-breakpoint {"breakpointId":"tablet","condition":null,"minWidth":768}\n- MCP tool: update-breakpoint {"breakpointId":"tablet","minWidth":null,"maxWidth":null,"condition":"(hover: hover)"}\n\n## Delete breakpoint\n\nCommands:\n\n- MCP tool: delete-breakpoint {"breakpointId":"tablet","confirm":true}\n\n## Duplicate page\n\nCommands:\n\n- MCP tool: duplicate-page {"pageId":"<pageId>","name":"Pricing Copy","path":"/pricing-copy"}\n\n## List page templates\n\nCommands:\n\n- MCP tool: list-page-templates {}\n\n## Create page from template\n\nCommands:\n\n- MCP tool: create-page-from-template {"templateId":"<templateId>","name":"Landing","path":"/landing"}\n\n## Delete page\n\nCommands:\n\n- MCP tool: delete-page {"pageId":"<pageId>"}\n\n## List folders\n\nCommands:\n\n- MCP tool: list-folders {"includePages":true}\n\n## Create folder\n\nCommands:\n\n- MCP tool: create-folder {"name":"Blog","slug":"blog"}\n\n## Update folder\n\nCommands:\n\n- MCP tool: update-folder {"folderId":"<folderId>","name":"Blog","slug":"blog"}\n\n## Delete folder\n\nCommands:\n\n- MCP tool: delete-folder {"folderId":"<folderId>"}\n\n## List element instances\n\nCommands:\n\n- MCP tool: list-instances {"pagePath":"/","maxDepth":3}\n\n## Inspect one element instance\n\nCommands:\n\n- MCP tool: inspect-instance {"instanceId":"<instanceId>","include":["props","styles","children"]}\n\n## Append/prepend/replace child elements\n\nCommands:\n\n- MCP tool: append-instance {"parentInstanceId":"<instanceId>","children":"children.json contents"}\n\n## Move elements\n\nCommands:\n\n- MCP tool: move-instance {"moves":"moves.json contents"}\n\n## Clone element subtree\n\nCommands:\n\n- MCP tool: clone-instance {"sourceInstanceId":"<instanceId>","parentInstanceId":"<targetParentId>"}\n\n## Delete element subtree\n\nCommands:\n\n- MCP tool: delete-instance {"instanceId":"<instanceId>"}\n\n## List text/expression children\n\nCommands:\n\n- MCP tool: list-texts {"pagePath":"/"}\n\n## Update text child\n\nCommands:\n\n- MCP tool: update-text {"instanceId":"<instanceId>","childIndex":0,"text":"Launch faster"}\n\n## Update props\n\nCommands:\n\n- MCP tool: update-props {"updates":"props.json contents"}\n\n## Delete props\n\nCommands:\n\n- MCP tool: delete-props {"deletions":"props.json contents"}\n\n## Bind props to expressions/resources/actions\n\nCommands:\n\n- MCP tool: bind-props {"bindings":"bindings.json contents"}\n\n## Read styles\n\nCommands:\n\n- MCP tool: get-styles {"instanceId":"<instanceId>","includeTokens":true}\n\n## Update local styles\n\nCommands:\n\n- MCP tool: update-styles {"updates":"styles.json contents"}\n\n## Delete local styles\n\nCommands:\n\n- MCP tool: delete-styles {"deletions":"styles.json contents"}\n\n## Replace matching style values\n\nCommands:\n\n- MCP tool: replace-styles {"replacements":"replace.json contents"}\n\n## List design tokens\n\nCommands:\n\n- MCP tool: list-design-tokens {"withUsage":true}\n\n## Create design tokens\n\nCommands:\n\n- MCP tool: create-design-token {"tokens":"tokens.json contents"}\n\n## Update design token styles\n\nCommands:\n\n- MCP tool: update-design-token-styles {"styleSourceId":"<tokenId>","updates":"styles.json contents"}\n\n## Delete design token styles\n\nCommands:\n\n- MCP tool: delete-design-token-styles {"styleSourceId":"<tokenId>","deletions":"styles.json contents"}\n\n## Attach design token to instances\n\nCommands:\n\n- MCP tool: attach-design-token {"styleSourceId":"<tokenId>","instanceIds":"instances.json contents"}\n\n## Detach design token from instances\n\nCommands:\n\n- MCP tool: detach-design-token {"styleSourceId":"<tokenId>","instanceIds":"instances.json contents"}\n\n## Extract design token from local styles\n\nCommands:\n\n- MCP tool: extract-design-token {"token":"token.json contents"}\n\n## List CSS variables\n\nCommands:\n\n- MCP tool: list-css-variables {"withUsage":true}\n\n## Define CSS variables\n\nCommands:\n\n- MCP tool: define-css-variable {"variables":"vars.json contents"}\n\n## Delete CSS variables\n\nCommands:\n\n- MCP tool: delete-css-variable {"names":"names.json contents","confirm":true}\n\n## Rewrite CSS variable references\n\nCommands:\n\n- MCP tool: rewrite-css-variable-refs {"variables":"variables.json contents"}\n\n## List data variables\n\nCommands:\n\n- MCP tool: list-variables {}\n\n## Create data variable\n\nCommands:\n\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"title","value":{"type":"string","value":"Hello"}}\n\n## Update data variable\n\nCommands:\n\n- MCP tool: update-variable {"variableId":"<variableId>","value":{"type":"json","value":{"count":1}}}\n\n## Delete data variable\n\nCommands:\n\n- MCP tool: delete-variable {"variableId":"<variableId>"}\n\n## List resources\n\nCommands:\n\n- MCP tool: list-resources {}\n\n## Create resource\n\nCommands:\n\n- MCP tool: create-resource {"name":"Posts","method":"get","url":"https://api.example.com/posts"}\n\n## Update resource\n\nCommands:\n\n- MCP tool: update-resource {"resourceId":"<resourceId>","url":"https://api.example.com/posts"}\n\n## Delete resource\n\nCommands:\n\n- MCP tool: delete-resource {"resourceId":"<resourceId>"}\n\n## List assets\n\nCommands:\n\n- MCP tool: list-assets {"withUsage":true}\n\n## Upload one asset\n\nCommands:\n\n- MCP tool: upload-asset {"asset":"asset.json contents","assetsDir":".webstudio/assets"}\n\n## Upload asset batch\n\nCommands:\n\n- MCP tool: upload-assets {"assets":"assets.json contents","assetsDir":".webstudio/assets"}\n\n## Find asset usage\n\nCommands:\n\n- MCP tool: find-asset-usage {"assetId":"<assetId>"}\n\n## Replace asset references\n\nCommands:\n\n- MCP tool: replace-asset {"fromAssetId":"<oldAssetId>","toAssetId":"<newAssetId>","confirm":true}\n\n## Delete assets\n\nCommands:\n\n- MCP tool: delete-asset {"assetId":"<assetId>","confirm":true}\n\n## Publish project\n\nCommands:\n\n- webstudio publish deploy --target production --json\n\n## List publishes\n\nCommands:\n\n- webstudio publish list --json\n\n## Check publish job\n\nCommands:\n\n- webstudio publish status --job <buildId> --json\n\n## Unpublish\n\nCommands:\n\n- webstudio publish unpublish --target production --confirm --json\n\n## List domains\n\nCommands:\n\n- webstudio domains list --json\n\n## Create domain\n\nCommands:\n\n- webstudio domains create --domain example.com --json\n\n## Update domain\n\nCommands:\n\n- webstudio domains update --domain-id <domainId> --domain www.example.com --json\n\n## Delete domain\n\nCommands:\n\n- webstudio domains delete --domain-id <domainId> --confirm --json\n\n## Verify domain\n\nCommands:\n\n- webstudio domains verify --domain-id <domainId> --json\n\n## Make arbitrary store-level changes\n\nCommands:\n\n- MCP tool: inspect {}\n- MCP tool: snapshot {"include":["<namespace>"]}\n- MCP tool: apply-patch {"baseVersion":"<version>","transactions":"patch.json contents"}\n\nNotes:\n\n- Use only when no semantic command exists.\n\n## Manage marketplace metadata\n\nCommands:\n\n- MCP tool: snapshot {"include":["marketplaceProduct"]}\n- MCP tool: apply-patch {"baseVersion":"<version>","transactions":"patch.json contents"}\n\nPatch namespaces:\n\n- marketplaceProduct\n\n## Search and inspect safely\n\nCommands:\n\n- MCP tool: list-instances {"pagePath":"/","maxDepth":5}\n- MCP tool: inspect-instance {"instanceId":"<instanceId>","include":["props","styles","children"]}\n- MCP tool: list-texts {"pagePath":"/"}\n- MCP tool: list-assets {"withUsage":true}\n- MCP tool: find-asset-usage {"assetId":"<assetId>"}\n- MCP tool: snapshot {"include":["pages","instances","props","resources","assets"]}\n\nNotes:\n\n- Use this for finding elements by label, type, href/resource patterns, HTML snippets, missing accessibility metadata, or asset usage.\n\n## Refactor targeted content\n\nCommands:\n\n- MCP tool: list-instances {"pagePath":"/"}\n- MCP tool: list-texts {"pagePath":"/"}\n- MCP tool: update-text {"instanceId":"<instanceId>","childIndex":0,"text":"Launch faster"}\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: update-page {"pageId":"<pageId>","title":"Pricing","description":"Plans"}\n- MCP tool: update-resource {"resourceId":"<resourceId>","url":"https://api.example.com/posts"}\n- MCP tool: replace-asset {"fromAssetId":"<oldAssetId>","toAssetId":"<newAssetId>","confirm":true}\n- MCP tool: replace-styles {"replacements":"replace.json contents"}\n- MCP tool: rewrite-css-variable-refs {"variables":"variables.json contents"}\n\nNotes:\n\n- Use focused reads first, then mutate only matching instances, props, metadata, resource URLs, assets, or style references.\n\n## Optimize existing project\n\nCommands:\n\n- MCP tool: list-pages {"includeFolders":true}\n- MCP tool: update-page {"pageId":"<pageId>","title":"Pricing","description":"Plans"}\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: list-breakpoints {}\n- MCP tool: update-breakpoint {"breakpointId":"tablet","maxWidth":1023}\n- MCP tool: get-styles {"instanceId":"<instanceId>","includeTokens":true}\n- MCP tool: update-styles {"updates":"styles.json contents"}\n- MCP tool: attach-design-token {"styleSourceId":"<tokenId>","instanceIds":"instances.json contents"}\n- MCP tool: update-project-settings {"settings":"project-settings.json contents"}\n\nNotes:\n\n- Use this for SEO metadata, accessibility labels, responsive behavior, token consistency, and project settings.\n\n## Connect external data\n\nCommands:\n\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"title","value":{"type":"string","value":"Hello"}}\n- MCP tool: create-resource {"name":"Posts","method":"get","url":"https://api.example.com/posts"}\n- MCP tool: update-resource {"resourceId":"<resourceId>","url":"https://api.example.com/posts"}\n- MCP tool: bind-props {"bindings":"bindings.json contents"}\n- MCP tool: append-instance {"parentInstanceId":"<instanceId>","children":"children.json contents"}\n\nNotes:\n\n- Use this for CMS sections, blog listings, Ghost/headless CMS pages, n8n-style integrations, and API URLs built from variables.\n\n## Support dynamic runtime behavior\n\nCommands:\n\n- MCP tool: append-instance {"parentInstanceId":"<instanceId>","children":"children.json contents"}\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: bind-props {"bindings":"bindings.json contents"}\n- MCP tool: create-resource {"name":"Seats","method":"get","url":"https://api.example.com/seats"}\n- MCP tool: snapshot {"include":["instances","props","resources"]}\n- MCP tool: apply-patch {"baseVersion":"<version>","transactions":"patch.json contents"}\n\nNotes:\n\n- Use existing scripts/resources for behavior, then move presentational structure into editable Webstudio instances where possible.\n- There is no dedicated semantic command yet for converting script-generated UI into editable Webstudio structure.\n\n## Build authenticated pages\n\nCommands:\n\n- MCP tool: create-page {"name":"Account","path":"/account"}\n- MCP tool: update-page {"pageId":"<pageId>","auth":{"login":"<login>","password":"<password>"}}\n- MCP tool: create-resource {"name":"Session","method":"get","url":"https://api.example.com/session"}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"user","value":{"type":"json","value":{}}}\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: bind-props {"bindings":"bindings.json contents"}\n\nNotes:\n\n- Basic auth is semantic today. Provider-specific Supabase/Firebase setup still requires manual resources, props, embeds, or patches.\n\n## Generate from design input\n\nCommands:\n\n- MCP tool: create-page {"name":"Landing","path":"/landing"}\n- MCP tool: create-design-token {"tokens":"tokens.json contents"}\n- MCP tool: define-css-variable {"variables":"vars.json contents"}\n- MCP tool: append-instance {"parentInstanceId":"<instanceId>","children":"children.json contents"}\n- MCP tool: update-styles {"updates":"styles.json contents"}\n- MCP tool: preview.start {"host":"127.0.0.1","port":5173}\n- MCP tool: screenshot {"path":"/","output":"current.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n\nNotes:\n\n- Use this after external design interpretation. There is no dedicated import command for Figma, screenshots, Inception output, or design.md yet.\n\n## Cross-project maintenance\n\nCommands:\n\n- webstudio init --link <api-share-link> --json\n- webstudio permissions --json\n- webstudio mcp\n\nNotes:\n\n- Public API and CLI intentionally operate on one configured project at a time. Use an external script to loop over projects.\n\n# Known CLI Gaps\n\n## General project search and audit\n\nMissing:\nNo single semantic command searches across instance labels, props, hrefs, resource URLs, HTML embeds, asset references, and missing accessibility metadata.\n\nCurrent fallback:\nUse focused MCP reads such as list-instances, list-texts, list-assets, find-asset-usage, and snapshot.\n\nSuggested commands:\n\n- search-project\n- audit-accessibility\n- find-prop-usage\n\n## Save and manage page templates\n\nMissing:\nCLI can list page templates and create pages from existing templates, but cannot save a page as a template or update/delete templates semantically.\n\nCurrent fallback:\nUse MCP snapshot and apply-patch only when the template data model is understood.\n\nSuggested commands:\n\n- create-page-template\n- update-page-template\n- delete-page-template\n\n## Semantic marketplace metadata\n\nMissing:\nMarketplace metadata is only available through MCP snapshot/apply-patch, not dedicated semantic commands.\n\nCurrent fallback:\nUse MCP snapshot --include marketplaceProduct and apply-patch.\n\nSuggested commands:\n\n- get-marketplace\n- update-marketplace\n\n## Provider-specific authenticated pages\n\nMissing:\nCLI supports page basic auth and generic resources/props/embeds, but not guided Supabase/Firebase auth setup.\n\nCurrent fallback:\nCreate the page, resources, variables, props, and embeds manually with existing MCP semantic tools.\n\nSuggested commands:\n\n- setup-auth-page\n\n## Dynamic script/runtime integration helpers\n\nMissing:\nCLI can manipulate props/resources/embeds, but has no semantic workflow for converting script-generated UI into editable Webstudio structures.\n\nCurrent fallback:\nUse MCP append-instance, props, resources, and raw patch where necessary.\n\nSuggested commands:\n\n- integrate-runtime-ui\n\n## Generate from design input\n\nMissing:\nNo command imports Figma, screenshots, Inception output, or design.md and turns it into pages/tokens/layout.\n\nCurrent fallback:\nUse external generation, then apply semantic CLI commands or apply-patch.\n\nSuggested commands:\n\n- generate-from-design\n\n## Built-in cross-project maintenance\n\nMissing:\nPublic API and CLI intentionally operate on one configured project at a time; there is no built-in multi-project discovery or loop runner.\n\nCurrent fallback:\nRun the CLI from an external script that reconfigures one project/session at a time.\n\nSuggested commands:\n\n- none\n',+ "manual-api":+ '# Webstudio API CLI Manual\n\nThe API commands operate on the single project configured by:\n\n- .webstudio/config.json: projectId\n- global Webstudio config: origin and token\n\nRules:\n\n- Always pass --json.\n- Never pass a project id. Commands use configured project only.\n- Read ids before writing. Do not invent ids for existing records.\n- stdout is one JSON object. stderr is diagnostics.\n- Prefer MCP semantic tools for detailed project edits. Use MCP apply-patch only when no semantic tool exists.\n\n## Start\n\n{{start}}\n\n## Read First\n\n{{readFirst}}\n\n## Project Session Cache\n\n- CLI commands use one local ProjectSession snapshot for the configured project.\n- Local-capable reads use cached namespaces when compatible and fetch only missing or stale namespaces.\n- Local-capable mutations build patches from the local snapshot, then commit with the cached build version.\n- Successful mutation commits update the local snapshot only after the remote commit succeeds.\n- Server-only commands run remotely and invalidate/refetch namespaces declared by the operation catalog.\n- Use --refresh on local-capable commands to refresh required namespaces before running.\n- Successful JSON responses include meta.session with operationId, buildId, version, source, committed, compatibility, namespace freshness, and diagnostics.\n\n## CLI Capability Inventory\n\n### Top-Level Commands\n\n{{topLevelCapabilityIndex}}\n\n### High-Level API Commands By Area\n\n{{apiCapabilityIndex}}\n\n### MCP-Only Operations\n\nThese are intentionally exposed through `webstudio mcp`, not as top-level shell commands:\n\n{{mcpOnlyCommandIndex}}\n\n## Task Recipes\n\n{{taskRecipeIndex}}\n\n## Use Case Index\n\n{{useCaseIndex}}\n\n## Known CLI Gaps\n\n{{knownCliGapIndex}}\n\n## Input File Shapes\n\n{{inputFileShapeIndex}}\n\n## Raw Patch Fallback\n\napply-patch accepts either BuildPatchTransaction[] or { "transactions": BuildPatchTransaction[] }.\n\nEach transaction has:\n\n{\n"id": "unique-client-transaction-id",\n"payload": [\n{\n"namespace": "pages",\n"patches": [\n{ "op": "replace", "path": ["meta", "siteName"], "value": "New Site" }\n]\n}\n]\n}\n\nPatch paths are JSON-patch-like paths into Builder store data. Map-like namespaces use ids as the first path item.\n\nSupported namespaces:\n\n- pages: site metadata, redirects, page records, folders, compiler settings\n- instances: element instances and children, including text/expression children\n- props: element props, bindings, page references, resource bindings\n- styles: CSS declarations keyed by style declaration key\n- styleSources: local style sources and reusable design tokens\n- styleSourceSelections: instance-to-style-source connections\n- dataSources: data variables, parameters, and resource data sources\n- resources: data resource definitions\n- assets: project asset records handled by the existing asset patch path\n- breakpoints: responsive breakpoints\n- marketplaceProduct: marketplace metadata\n\nCommit raw patch:\n\nMCP tool: apply-patch\n\n## Raw Patch Examples\n\nRename the site:\n\n[\n{\n"id": "tx-site-name",\n"payload": [\n{\n"namespace": "pages",\n"patches": [\n{ "op": "add", "path": ["meta", "siteName"], "value": "Acme Studio" }\n]\n}\n]\n}\n]\n\nUpdate page title metadata:\n\n[\n{\n"id": "tx-page-title",\n"payload": [\n{\n"namespace": "pages",\n"patches": [\n{ "op": "replace", "path": ["pages", "page-id", "meta", "title"], "value": "Pricing" }\n]\n}\n]\n}\n]\n\nUpdate a text child on an element:\n\n[\n{\n"id": "tx-text",\n"payload": [\n{\n"namespace": "instances",\n"patches": [\n{ "op": "replace", "path": ["instance-id", "children", 0, "value"], "value": "Launch faster" }\n]\n}\n]\n}\n]\n\nCreate a data variable:\n\n[\n{\n"id": "tx-variable",\n"payload": [\n{\n"namespace": "dataSources",\n"patches": [\n{\n"op": "add",\n"path": ["variable-id"],\n"value": {\n"type": "variable",\n"id": "variable-id",\n"scopeInstanceId": "instance-id",\n"name": "headline",\n"value": { "type": "string", "value": "Launch faster" }\n}\n}\n]\n}\n]\n}\n]\n\nCreate a design token:\n\n[\n{\n"id": "tx-token",\n"payload": [\n{\n"namespace": "styleSources",\n"patches": [\n{ "op": "add", "path": ["token-id"], "value": { "type": "token", "id": "token-id", "name": "Brand Primary" } }\n]\n},\n{\n"namespace": "styles",\n"patches": [\n{\n"op": "add",\n"path": ["token-id:base:color:"],\n"value": {\n"styleSourceId": "token-id",\n"breakpointId": "base",\n"property": "color",\n"value": { "type": "keyword", "value": "red" }\n}\n}\n]\n}\n]\n}\n]\n\n## Safety Rules\n\n- For MCP apply-patch, read the latest version with MCP snapshot before writing.\n- Reuse ids from MCP snapshot output when updating existing records.\n- Generate new unique ids when adding records.\n- If apply-patch reports a version conflict, read the latest build and regenerate the patch.\n- Prefer semantic MCP read tools for discovery, then use MCP snapshot for exact patch paths.\n\n## Command Index\n\n{{commandIndex}}\n',+ "manual-llm":+ "# Webstudio CLI Manual for LLMs\n\nUse this order. Stop only when a command returns ok:false.\n\n## Always\n\n1. webstudio permissions --json\n2. webstudio mcp\n3. Read MCP resource webstudio://project/tools.\n4. Pick focused MCP read tool.\n5. Pick semantic MCP write tool.\n\n## Pick Read Command\n\n{{readFirst}}\n\n## Pick Write Command\n\n{{taskRecipeIndex}}\n\n## Raw Patch Only If Needed\n\n1. Use MCP tool: snapshot.\n2. Write BuildPatchTransaction[].\n3. Use MCP tool: apply-patch.\n\n## MCP Argument Examples\n\nMCP tools receive JSON argument objects, not CLI flags. Use these shapes:\n\n{{mcpArgumentExampleIndex}}\n\n## Rules\n\n- Never guess ids for existing records. Read them first.\n- Never use project ids from user input. Commands use the configured project.\n- Use --refresh before a local-capable command when cached data may be stale.\n- On VERSION_CONFLICT, read MCP snapshot again, regenerate the patch, then retry.\n- Treat stdout JSON as the API contract and stderr as diagnostics.\n- Confirm destructive commands with --confirm only when user requested deletion/unpublish/replacement.\n- Use webstudio schema api --json for machine-readable command metadata.\n\n## Known Gaps\n\n{{knownCliGapIndex}}\n",+ "manual-mcp":+ "# Webstudio MCP Manual\n\n`webstudio mcp` starts a stdio MCP server for the configured project.\n\n## Startup\n\n1. Configure a project with `webstudio init --link <api-share-link> --json`.\n2. Check capabilities with `webstudio permissions --json`.\n3. Start the server with `webstudio mcp`.\n\nWhile the server is running, stdout is reserved for MCP JSON-RPC messages. Do not print human text from the server process.\n\n## Discovery\n\nUse MCP itself after startup:\n\n- `tools/list`: machine-readable available tools\n- `resources/list`: available longer JSON resources\n- `meta.index`: concise capability catalog\n- `meta.guide`: workflow for a user goal\n- `meta.get_more_tools`: detailed params, examples, namespaces, and local/server behavior\n\nUseful resources:\n\n- `webstudio://project/status`: current ProjectSession status\n- `webstudio://project/tools`: operation catalog\n- `webstudio://project/guide`: concise discovery guide\n\n## Core Rules\n\n- Operate on the configured project only.\n- Read ids before writing.\n- Prefer semantic tools over `apply-patch`.\n- Use `status` and `refresh` when cached namespaces may be stale.\n- A mutation is durable only when `meta.session.committed` is true.\n- For visual/design work, verify the rendered result with vision before finishing.\n\n## Vision Verification Loop\n\nVision-capable AI can use MCP to see what it is building:\n\n{{mcpVisionVerificationLoopMarkdown}}\n\nGenerated app setup:\n\n{{mcpGeneratedAppDependencyNotes}}\n\n## MCP Argument Examples\n\nMCP tools receive JSON argument objects:\n\n{{mcpArgumentExampleIndex}}\n\n## Screenshot Verification\n\n{{screenshotVerificationSummary}}\n",+ "mcp-vision":+ '# MCP Vision Verification\n\n## Generated App Dependency Notes\n\n- For a fresh checkout, copied fixture, or newly generated app, run npm install or pnpm install in the generated project before preview.start or webstudio preview.\n- If preview fails with a missing generated-app command/package such as react-router or vite, install the generated app dependencies and retry.\n\n## Visual Verification Rule\n\nFor visual/design work, use preview.start and screenshot after generated project files are current and generated app dependencies are installed so vision can inspect the rendered result before finishing. When a baseline exists, use screenshot.diff to get pixel regions, OCR text changes, and diff PNG artifacts.\n\n## Vision Verification Loop\n\n- Make focused page/content/style changes with semantic MCP tools.\n- Make sure generated project files are current and generated app dependencies are installed, then call preview.start once to keep the generated site running.\n- {{dependency-notes}}\n- Call screenshot with { path: "/" } or the changed page path. Use waitForSelector when the page has a reliable ready marker, waitUntil:"networkidle" for network-heavy pages, and waitForTimeout only for final visual settling.\n- {{diff}} When a baseline PNG exists, call screenshot.diff with baselinePath, currentPath, and outputDir.\n- {{diff}} Read screenshot.diff textAnalysis: it reports OCR status plus text that appeared, disappeared, moved, changed content, or changed font/style geometry. If OCR is unavailable, ask the user for permission to install Tesseract, then call vision.install-ocr with { "confirm": true }, or rely on visual inspection.\n- Inspect the PNG and any diff artifacts with vision, then compare layout, OCR text evidence, color, spacing, imagery, and responsive framing against the user intent.\n- If the screenshot does not match, apply another focused mutation and repeat screenshot verification.\n\n## Workflow Summary With Diff\n\nFor visual/design work, make sure generated project files are current and generated app dependencies are installed, call preview.start, then screenshot({ path }); use screenshot.diff when a baseline exists, then inspect pixel regions, OCR textAnalysis, and PNG/diff artifacts with vision before finishing.\n\n## Workflow Summary Without Diff\n\nFor visual/design work, make sure generated project files are current and generated app dependencies are installed, call preview.start, then screenshot({ path }); inspect the PNG with vision before finishing.\n\n## Screenshot Verification Summary\n\nInside MCP, prefer preview.start plus screenshot({ path: "/" }) after generated project files are current and generated app dependencies are installed, so the preview server stays running for fast repeated checks. Screenshot waits for load by default, then fonts and two layout frames; pass waitForSelector for app readiness, waitUntil:"networkidle" for network-heavy pages, and waitForTimeout for final settling. When a baseline exists, use screenshot.diff for changed regions, OCR textAnalysis, and diff artifacts. Outside MCP, use webstudio preview and webstudio screenshot <url> --output current.png.\n\n## Screenshot Diff Evidence\n\n- Pixel evidence: total mismatch, changed regions, dominant color/luminance direction, diffPath, and contextDiffPath.\n- OCR evidence: textAnalysis.status, provider, and changes for appeared/disappeared/content_changed/moved/font_changed text.\n- OCR dependency: screenshot.diff uses the system tesseract binary when available. If missing, it returns ocr_unavailable_tesseract_not_found_or_failed and still returns pixel evidence.\n- OCR install: MCP cannot prompt. Ask the user first; if they agree, call vision.install-ocr with { "confirm": true }. If automatic install is unavailable, follow the returned installUrl.\n- Final judgment: OCR and pixel diff are evidence. A vision-capable model must still inspect screenshots/diff artifacts and compare the rendered result to user intent.\n',+} as const;++export type CliDocName = keyof typeof cliDocs;diff --git a/packages/cli/src/docs.ts b/packages/cli/src/docs.tsnew file mode 100644index 0000000000..8f41c53547--- /dev/null+++ b/packages/cli/src/docs.ts@@ -0,0 +1,3 @@+import { cliDocs, type CliDocName } from "./docs.generated";++export const readCliDoc = (name: CliDocName) => cliDocs[name];diff --git a/packages/cli/src/docs/api-use-cases.md b/packages/cli/src/docs/api-use-cases.mdnew file mode 100644index 0000000000..e5dd3c04de--- /dev/null+++ b/packages/cli/src/docs/api-use-cases.md@@ -0,0 +1,756 @@+# CLI API Use Cases++## Link/configure one project++Commands:++- webstudio init --link <api-share-link> --json++Notes:++- Writes local project id and global origin/token config.++## Identify current token++Commands:++- MCP tool: whoami {}++## Check token permissions++Commands:++- webstudio permissions --json++## Inspect project/build/version++Commands:++- MCP tool: inspect {}+- MCP tool: snapshot {"include":["pages","instances","styles"]}++## Discover CLI/API capabilities++Commands:++- webstudio schema api --json+- webstudio man api --json+- webstudio man llm --json+- webstudio man mcp --json+- MCP tool: meta.index {}+- MCP tool: meta.guide {"brief":"Create a pricing page"}+- MCP tool: meta.get_more_tools {"brief":"update-styles"}++Notes:++- Use `tools/list` for machine-readable MCP tool schemas.+- Use `resources/list` and `resources/read` for longer MCP resources such as `webstudio://project/tools` and `webstudio://project/guide`.++## Inspect and refresh MCP session cache++Commands:++- MCP tool: status {}+- MCP tool: refresh {"namespaces":["pages","instances","styles"]}+- MCP tool: reset-session {}++Notes:++- Use status before a task to understand the cached ProjectSession state.+- Use refresh when project data may have changed outside the current MCP session.+- Use reset-session when local cached state is corrupt or incompatible.++## Visually verify rendered work with AI vision++Commands:++- MCP tool: preview.start {"host":"127.0.0.1","port":5173}+- MCP tool: preview.status {}+- MCP tool: screenshot {"path":"/","output":"current.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}+- MCP tool: screenshot.diff {"baselinePath":"before.png","currentPath":"current.png","outputDir":".webstudio/screenshots"}+- MCP tool: vision.install-ocr {"confirm":true}++Notes:++- Use this after page/content/style mutations and after generated project files are current so a vision-capable AI can see what was actually built.+- Use waitForSelector when the rendered app has a reliable ready marker, waitUntil:"networkidle" for network-heavy pages, and waitForTimeout only for final visual settling.+- For a fresh checkout, copied fixture, or newly generated app, run npm install or pnpm install in the generated project before preview.start or webstudio preview.+- If preview fails with a missing generated-app command/package such as react-router or vite, install the generated app dependencies and retry.+- When a baseline exists, use screenshot.diff to get changed regions, OCR textAnalysis, and diff artifact paths before deciding whether the result matches.+- If screenshot.diff reports OCR unavailable and the user agrees to install it, call vision.install-ocr {"confirm":true}; otherwise continue with pixel diff and visual inspection.+- Compare the PNG, OCR text evidence, and diff artifacts against the user's intent for layout, typography, colors, spacing, imagery, and responsive framing; then iterate with focused mutations.+- Root CLI equivalent: webstudio preview --template ssg, then webstudio screenshot <url> --output current.png.++## List pages++Commands:++- MCP tool: list-pages {"includeFolders":true}++## Read page by id++Commands:++- MCP tool: get-page {"pageId":"<pageId>"}++## Read page by path++Commands:++- MCP tool: get-page-by-path {"path":"/pricing"}++## Create page++Commands:++- MCP tool: create-page {"name":"Pricing","path":"/pricing"}++## Update page settings/metadata++Commands:++- MCP tool: update-page {"pageId":"<pageId>","title":"Pricing","description":"Plans","status":"200"}+- MCP tool: update-page {"pageId":"<pageId>","auth":{"login":"<login>","password":"<password>"}}++## Read project settings++Commands:++- MCP tool: get-project-settings {}++## Update project settings++Commands:++- MCP tool: update-project-settings {"settings":"project-settings.json contents"}++## List redirects++Commands:++- MCP tool: list-redirects {}++## Create redirect++Commands:++- MCP tool: create-redirect {"oldPath":"/old","newPath":"/new","status":301}++## Update redirect++Commands:++- MCP tool: update-redirect {"oldPath":"/old","newPath":"/newer","status":302}+- MCP tool: update-redirect {"oldPath":"/old","status":null}++## Delete redirect++Commands:++- MCP tool: delete-redirect {"oldPath":"/old"}++## List breakpoints++Commands:++- MCP tool: list-breakpoints {}++## Create breakpoint++Commands:++- MCP tool: create-breakpoint {"breakpointId":"tablet","label":"Tablet","maxWidth":991}++## Update breakpoint++Commands:++- MCP tool: update-breakpoint {"breakpointId":"tablet","label":"Tablet","maxWidth":1023}+- MCP tool: update-breakpoint {"breakpointId":"tablet","condition":null,"minWidth":768}+- MCP tool: update-breakpoint {"breakpointId":"tablet","minWidth":null,"maxWidth":null,"condition":"(hover: hover)"}++## Delete breakpoint++Commands:++- MCP tool: delete-breakpoint {"breakpointId":"tablet","confirm":true}++## Duplicate page++Commands:++- MCP tool: duplicate-page {"pageId":"<pageId>","name":"Pricing Copy","path":"/pricing-copy"}++## List page templates++Commands:++- MCP tool: list-page-templates {}++## Create page from template++Commands:++- MCP tool: create-page-from-template {"templateId":"<templateId>","name":"Landing","path":"/landing"}++## Delete page++Commands:++- MCP tool: delete-page {"pageId":"<pageId>"}++## List folders++Commands:++- MCP tool: list-folders {"includePages":true}++## Create folder++Commands:++- MCP tool: create-folder {"name":"Blog","slug":"blog"}++## Update folder++Commands:++- MCP tool: update-folder {"folderId":"<folderId>","name":"Blog","slug":"blog"}++## Delete folder++Commands:++- MCP tool: delete-folder {"folderId":"<folderId>"}++## List element instances++Commands:++- MCP tool: list-instances {"pagePath":"/","maxDepth":3}++## Inspect one element instance++Commands:++- MCP tool: inspect-instance {"instanceId":"<instanceId>","include":["props","styles","children"]}++## Append/prepend/replace child elements++Commands:++- MCP tool: append-instance {"parentInstanceId":"<instanceId>","children":"children.json contents"}++## Move elements++Commands:++- MCP tool: move-instance {"moves":"moves.json contents"}++## Clone element subtree++Commands:++- MCP tool: clone-instance {"sourceInstanceId":"<instanceId>","parentInstanceId":"<targetParentId>"}++## Delete element subtree++Commands:++- MCP tool: delete-instance {"instanceId":"<instanceId>"}++## List text/expression children++Commands:++- MCP tool: list-texts {"pagePath":"/"}++## Update text child++Commands:++- MCP tool: update-text {"instanceId":"<instanceId>","childIndex":0,"text":"Launch faster"}++## Update props++Commands:++- MCP tool: update-props {"updates":"props.json contents"}++## Delete props++Commands:++- MCP tool: delete-props {"deletions":"props.json contents"}++## Bind props to expressions/resources/actions++Commands:++- MCP tool: bind-props {"bindings":"bindings.json contents"}++## Read styles++Commands:++- MCP tool: get-styles {"instanceId":"<instanceId>","includeTokens":true}++## Update local styles++Commands:++- MCP tool: update-styles {"updates":"styles.json contents"}++## Delete local styles++Commands:++- MCP tool: delete-styles {"deletions":"styles.json contents"}++## Replace matching style values++Commands:++- MCP tool: replace-styles {"replacements":"replace.json contents"}++## List design tokens++Commands:++- MCP tool: list-design-tokens {"withUsage":true}++## Create design tokens++Commands:++- MCP tool: create-design-token {"tokens":"tokens.json contents"}++## Update design token styles++Commands:++- MCP tool: update-design-token-styles {"styleSourceId":"<tokenId>","updates":"styles.json contents"}++## Delete design token styles++Commands:++- MCP tool: delete-design-token-styles {"styleSourceId":"<tokenId>","deletions":"styles.json contents"}++## Attach design token to instances++Commands:++- MCP tool: attach-design-token {"styleSourceId":"<tokenId>","instanceIds":"instances.json contents"}++## Detach design token from instances++Commands:++- MCP tool: detach-design-token {"styleSourceId":"<tokenId>","instanceIds":"instances.json contents"}++## Extract design token from local styles++Commands:++- MCP tool: extract-design-token {"token":"token.json contents"}++## List CSS variables++Commands:++- MCP tool: list-css-variables {"withUsage":true}++## Define CSS variables++Commands:++- MCP tool: define-css-variable {"variables":"vars.json contents"}++## Delete CSS variables++Commands:++- MCP tool: delete-css-variable {"names":"names.json contents","confirm":true}++## Rewrite CSS variable references++Commands:++- MCP tool: rewrite-css-variable-refs {"variables":"variables.json contents"}++## List data variables++Commands:++- MCP tool: list-variables {}++## Create data variable++Commands:++- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"title","value":{"type":"string","value":"Hello"}}++## Update data variable++Commands:++- MCP tool: update-variable {"variableId":"<variableId>","value":{"type":"json","value":{"count":1}}}++## Delete data variable++Commands:++- MCP tool: delete-variable {"variableId":"<variableId>"}++## List resources++Commands:++- MCP tool: list-resources {}++## Create resource++Commands:++- MCP tool: create-resource {"name":"Posts","method":"get","url":"https://api.example.com/posts"}++## Update resource++Commands:++- MCP tool: update-resource {"resourceId":"<resourceId>","url":"https://api.example.com/posts"}++## Delete resource++Commands:++- MCP tool: delete-resource {"resourceId":"<resourceId>"}++## List assets++Commands:++- MCP tool: list-assets {"withUsage":true}++## Upload one asset++Commands:++- MCP tool: upload-asset {"asset":"asset.json contents","assetsDir":".webstudio/assets"}++## Upload asset batch++Commands:++- MCP tool: upload-assets {"assets":"assets.json contents","assetsDir":".webstudio/assets"}++## Find asset usage++Commands:++- MCP tool: find-asset-usage {"assetId":"<assetId>"}++## Replace asset references++Commands:++- MCP tool: replace-asset {"fromAssetId":"<oldAssetId>","toAssetId":"<newAssetId>","confirm":true}++## Delete assets++Commands:++- MCP tool: delete-asset {"assetId":"<assetId>","confirm":true}++## Publish project++Commands:++- webstudio publish deploy --target production --json++## List publishes++Commands:++- webstudio publish list --json++## Check publish job++Commands:++- webstudio publish status --job <buildId> --json++## Unpublish++Commands:++- webstudio publish unpublish --target production --confirm --json++## List domains++Commands:++- webstudio domains list --json++## Create domain++Commands:++- webstudio domains create --domain example.com --json++## Update domain++Commands:++- webstudio domains update --domain-id <domainId> --domain www.example.com --json++## Delete domain++Commands:++- webstudio domains delete --domain-id <domainId> --confirm --json++## Verify domain++Commands:++- webstudio domains verify --domain-id <domainId> --json++## Make arbitrary store-level changes++Commands:++- MCP tool: inspect {}+- MCP tool: snapshot {"include":["<namespace>"]}+- MCP tool: apply-patch {"baseVersion":"<version>","transactions":"patch.json contents"}++Notes:++- Use only when no semantic command exists.++## Manage marketplace metadata++Commands:++- MCP tool: snapshot {"include":["marketplaceProduct"]}+- MCP tool: apply-patch {"baseVersion":"<version>","transactions":"patch.json contents"}++Patch namespaces:++- marketplaceProduct++## Search and inspect safely++Commands:++- MCP tool: list-instances {"pagePath":"/","maxDepth":5}+- MCP tool: inspect-instance {"instanceId":"<instanceId>","include":["props","styles","children"]}+- MCP tool: list-texts {"pagePath":"/"}+- MCP tool: list-assets {"withUsage":true}+- MCP tool: find-asset-usage {"assetId":"<assetId>"}+- MCP tool: snapshot {"include":["pages","instances","props","resources","assets"]}++Notes:++- Use this for finding elements by label, type, href/resource patterns, HTML snippets, missing accessibility metadata, or asset usage.++## Refactor targeted content++Commands:++- MCP tool: list-instances {"pagePath":"/"}+- MCP tool: list-texts {"pagePath":"/"}+- MCP tool: update-text {"instanceId":"<instanceId>","childIndex":0,"text":"Launch faster"}+- MCP tool: update-props {"updates":"props.json contents"}+- MCP tool: update-page {"pageId":"<pageId>","title":"Pricing","description":"Plans"}+- MCP tool: update-resource {"resourceId":"<resourceId>","url":"https://api.example.com/posts"}+- MCP tool: replace-asset {"fromAssetId":"<oldAssetId>","toAssetId":"<newAssetId>","confirm":true}+- MCP tool: replace-styles {"replacements":"replace.json contents"}+- MCP tool: rewrite-css-variable-refs {"variables":"variables.json contents"}++Notes:++- Use focused reads first, then mutate only matching instances, props, metadata, resource URLs, assets, or style references.++## Optimize existing project++Commands:++- MCP tool: list-pages {"includeFolders":true}+- MCP tool: update-page {"pageId":"<pageId>","title":"Pricing","description":"Plans"}+- MCP tool: update-props {"updates":"props.json contents"}+- MCP tool: list-breakpoints {}+- MCP tool: update-breakpoint {"breakpointId":"tablet","maxWidth":1023}+- MCP tool: get-styles {"instanceId":"<instanceId>","includeTokens":true}+- MCP tool: update-styles {"updates":"styles.json contents"}+- MCP tool: attach-design-token {"styleSourceId":"<tokenId>","instanceIds":"instances.json contents"}+- MCP tool: update-project-settings {"settings":"project-settings.json contents"}++Notes:++- Use this for SEO metadata, accessibility labels, responsive behavior, token consistency, and project settings.++## Connect external data++Commands:++- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"title","value":{"type":"string","value":"Hello"}}+- MCP tool: create-resource {"name":"Posts","method":"get","url":"https://api.example.com/posts"}+- MCP tool: update-resource {"resourceId":"<resourceId>","url":"https://api.example.com/posts"}+- MCP tool: bind-props {"bindings":"bindings.json contents"}+- MCP tool: append-instance {"parentInstanceId":"<instanceId>","children":"children.json contents"}++Notes:++- Use this for CMS sections, blog listings, Ghost/headless CMS pages, n8n-style integrations, and API URLs built from variables.++## Support dynamic runtime behavior++Commands:++- MCP tool: append-instance {"parentInstanceId":"<instanceId>","children":"children.json contents"}+- MCP tool: update-props {"updates":"props.json contents"}+- MCP tool: bind-props {"bindings":"bindings.json contents"}+- MCP tool: create-resource {"name":"Seats","method":"get","url":"https://api.example.com/seats"}+- MCP tool: snapshot {"include":["instances","props","resources"]}+- MCP tool: apply-patch {"baseVersion":"<version>","transactions":"patch.json contents"}++Notes:++- Use existing scripts/resources for behavior, then move presentational structure into editable Webstudio instances where possible.+- There is no dedicated semantic command yet for converting script-generated UI into editable Webstudio structure.++## Build authenticated pages++Commands:++- MCP tool: create-page {"name":"Account","path":"/account"}+- MCP tool: update-page {"pageId":"<pageId>","auth":{"login":"<login>","password":"<password>"}}+- MCP tool: create-resource {"name":"Session","method":"get","url":"https://api.example.com/session"}+- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"user","value":{"type":"json","value":{}}}+- MCP tool: update-props {"updates":"props.json contents"}+- MCP tool: bind-props {"bindings":"bindings.json contents"}++Notes:++- Basic auth is semantic today. Provider-specific Supabase/Firebase setup still requires manual resources, props, embeds, or patches.++## Generate from design input++Commands:++- MCP tool: create-page {"name":"Landing","path":"/landing"}+- MCP tool: create-design-token {"tokens":"tokens.json contents"}+- MCP tool: define-css-variable {"variables":"vars.json contents"}+- MCP tool: append-instance {"parentInstanceId":"<instanceId>","children":"children.json contents"}+- MCP tool: update-styles {"updates":"styles.json contents"}+- MCP tool: preview.start {"host":"127.0.0.1","port":5173}+- MCP tool: screenshot {"path":"/","output":"current.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}++Notes:++- Use this after external design interpretation. There is no dedicated import command for Figma, screenshots, Inception output, or design.md yet.++## Cross-project maintenance++Commands:++- webstudio init --link <api-share-link> --json+- webstudio permissions --json+- webstudio mcp++Notes:++- Public API and CLI intentionally operate on one configured project at a time. Use an external script to loop over projects.++# Known CLI Gaps++## General project search and audit++Missing:+No single semantic command searches across instance labels, props, hrefs, resource URLs, HTML embeds, asset references, and missing accessibility metadata.++Current fallback:+Use focused MCP reads such as list-instances, list-texts, list-assets, find-asset-usage, and snapshot.++Suggested commands:++- search-project+- audit-accessibility+- find-prop-usage++## Save and manage page templates++Missing:+CLI can list page templates and create pages from existing templates, but cannot save a page as a template or update/delete templates semantically.++Current fallback:+Use MCP snapshot and apply-patch only when the template data model is understood.++Suggested commands:++- create-page-template+- update-page-template+- delete-page-template++## Semantic marketplace metadata++Missing:+Marketplace metadata is only available through MCP snapshot/apply-patch, not dedicated semantic commands.++Current fallback:+Use MCP snapshot --include marketplaceProduct and apply-patch.++Suggested commands:++- get-marketplace+- update-marketplace++## Provider-specific authenticated pages++Missing:+CLI supports page basic auth and generic resources/props/embeds, but not guided Supabase/Firebase auth setup.++Current fallback:+Create the page, resources, variables, props, and embeds manually with existing MCP semantic tools.++Suggested commands:++- setup-auth-page++## Dynamic script/runtime integration helpers++Missing:+CLI can manipulate props/resources/embeds, but has no semantic workflow for converting script-generated UI into editable Webstudio structures.++Current fallback:+Use MCP append-instance, props, resources, and raw patch where necessary.++Suggested commands:++- integrate-runtime-ui++## Generate from design input++Missing:+No command imports Figma, screenshots, Inception output, or design.md and turns it into pages/tokens/layout.++Current fallback:+Use external generation, then apply semantic CLI commands or apply-patch.++Suggested commands:++- generate-from-design++## Built-in cross-project maintenance++Missing:+Public API and CLI intentionally operate on one configured project at a time; there is no built-in multi-project discovery or loop runner.++Current fallback:+Run the CLI from an external script that reconfigures one project/session at a time.++Suggested commands:++- nonediff --git a/packages/cli/src/docs/manual-api.md b/packages/cli/src/docs/manual-api.mdnew file mode 100644index 0000000000..70c47dd1e5--- /dev/null+++ b/packages/cli/src/docs/manual-api.md@@ -0,0 +1,221 @@+# Webstudio API CLI Manual++The API commands operate on the single project configured by:++- .webstudio/config.json: projectId+- global Webstudio config: origin and token++Rules:++- Always pass --json.+- Never pass a project id. Commands use configured project only.+- Read ids before writing. Do not invent ids for existing records.+- stdout is one JSON object. stderr is diagnostics.+- Prefer MCP semantic tools for detailed project edits. Use MCP apply-patch only when no semantic tool exists.++## Start++{{start}}++## Read First++{{readFirst}}++## Project Session Cache++- CLI commands use one local ProjectSession snapshot for the configured project.+- Local-capable reads use cached namespaces when compatible and fetch only missing or stale namespaces.+- Local-capable mutations build patches from the local snapshot, then commit with the cached build version.+- Successful mutation commits update the local snapshot only after the remote commit succeeds.+- Server-only commands run remotely and invalidate/refetch namespaces declared by the operation catalog.+- Use --refresh on local-capable commands to refresh required namespaces before running.+- Successful JSON responses include meta.session with operationId, buildId, version, source, committed, compatibility, namespace freshness, and diagnostics.++## CLI Capability Inventory++### Top-Level Commands++{{topLevelCapabilityIndex}}++### High-Level API Commands By Area++{{apiCapabilityIndex}}++### MCP-Only Operations++These are intentionally exposed through `webstudio mcp`, not as top-level shell commands:++{{mcpOnlyCommandIndex}}++## Task Recipes++{{taskRecipeIndex}}++## Use Case Index++{{useCaseIndex}}++## Known CLI Gaps++{{knownCliGapIndex}}++## Input File Shapes++{{inputFileShapeIndex}}++## Raw Patch Fallback++apply-patch accepts either BuildPatchTransaction[] or { "transactions": BuildPatchTransaction[] }.++Each transaction has:++{+"id": "unique-client-transaction-id",+"payload": [+{+"namespace": "pages",+"patches": [+{ "op": "replace", "path": ["meta", "siteName"], "value": "New Site" }+]+}+]+}++Patch paths are JSON-patch-like paths into Builder store data. Map-like namespaces use ids as the first path item.++Supported namespaces:++- pages: site metadata, redirects, page records, folders, compiler settings+- instances: element instances and children, including text/expression children+- props: element props, bindings, page references, resource bindings+- styles: CSS declarations keyed by style declaration key+- styleSources: local style sources and reusable design tokens+- styleSourceSelections: instance-to-style-source connections+- dataSources: data variables, parameters, and resource data sources+- resources: data resource definitions+- assets: project asset records handled by the existing asset patch path+- breakpoints: responsive breakpoints+- marketplaceProduct: marketplace metadata++Commit raw patch:++MCP tool: apply-patch++## Raw Patch Examples++Rename the site:++[+{+"id": "tx-site-name",+"payload": [+{+"namespace": "pages",+"patches": [+{ "op": "add", "path": ["meta", "siteName"], "value": "Acme Studio" }+]+}+]+}+]++Update page title metadata:++[+{+"id": "tx-page-title",+"payload": [+{+"namespace": "pages",+"patches": [+{ "op": "replace", "path": ["pages", "page-id", "meta", "title"], "value": "Pricing" }+]+}+]+}+]++Update a text child on an element:++[+{+"id": "tx-text",+"payload": [+{+"namespace": "instances",+"patches": [+{ "op": "replace", "path": ["instance-id", "children", 0, "value"], "value": "Launch faster" }+]+}+]+}+]++Create a data variable:++[+{+"id": "tx-variable",+"payload": [+{+"namespace": "dataSources",+"patches": [+{+"op": "add",+"path": ["variable-id"],+"value": {+"type": "variable",+"id": "variable-id",+"scopeInstanceId": "instance-id",+"name": "headline",+"value": { "type": "string", "value": "Launch faster" }+}+}+]+}+]+}+]++Create a design token:++[+{+"id": "tx-token",+"payload": [+{+"namespace": "styleSources",+"patches": [+{ "op": "add", "path": ["token-id"], "value": { "type": "token", "id": "token-id", "name": "Brand Primary" } }+]+},+{+"namespace": "styles",+"patches": [+{+"op": "add",+"path": ["token-id:base:color:"],+"value": {+"styleSourceId": "token-id",+"breakpointId": "base",+"property": "color",+"value": { "type": "keyword", "value": "red" }+}+}+]+}+]+}+]++## Safety Rules++- For MCP apply-patch, read the latest version with MCP snapshot before writing.+- Reuse ids from MCP snapshot output when updating existing records.+- Generate new unique ids when adding records.+- If apply-patch reports a version conflict, read the latest build and regenerate the patch.+- Prefer semantic MCP read tools for discovery, then use MCP snapshot for exact patch paths.++## Command Index++{{commandIndex}}diff --git a/packages/cli/src/docs/manual-llm.md b/packages/cli/src/docs/manual-llm.mdnew file mode 100644index 0000000000..f4940f347b--- /dev/null+++ b/packages/cli/src/docs/manual-llm.md@@ -0,0 +1,45 @@+# Webstudio CLI Manual for LLMs++Use this order. Stop only when a command returns ok:false.++## Always++1. webstudio permissions --json+2. webstudio mcp+3. Read MCP resource webstudio://project/tools.+4. Pick focused MCP read tool.+5. Pick semantic MCP write tool.++## Pick Read Command++{{readFirst}}++## Pick Write Command++{{taskRecipeIndex}}++## Raw Patch Only If Needed++1. Use MCP tool: snapshot.+2. Write BuildPatchTransaction[].+3. Use MCP tool: apply-patch.++## MCP Argument Examples++MCP tools receive JSON argument objects, not CLI flags. Use these shapes:++{{mcpArgumentExampleIndex}}++## Rules++- Never guess ids for existing records. Read them first.+- Never use project ids from user input. Commands use the configured project.+- Use --refresh before a local-capable command when cached data may be stale.+- On VERSION_CONFLICT, read MCP snapshot again, regenerate the patch, then retry.+- Treat stdout JSON as the API contract and stderr as diagnostics.+- Confirm destructive commands with --confirm only when user requested deletion/unpublish/replacement.+- Use webstudio schema api --json for machine-readable command metadata.++## Known Gaps++{{knownCliGapIndex}}diff --git a/packages/cli/src/docs/manual-mcp.md b/packages/cli/src/docs/manual-mcp.mdnew file mode 100644index 0000000000..1f09053f57--- /dev/null+++ b/packages/cli/src/docs/manual-mcp.md@@ -0,0 +1,56 @@+# Webstudio MCP Manual++`webstudio mcp` starts a stdio MCP server for the configured project.++## Startup++1. Configure a project with `webstudio init --link <api-share-link> --json`.+2. Check capabilities with `webstudio permissions --json`.+3. Start the server with `webstudio mcp`.++While the server is running, stdout is reserved for MCP JSON-RPC messages. Do not print human text from the server process.++## Discovery++Use MCP itself after startup:++- `tools/list`: machine-readable available tools+- `resources/list`: available longer JSON resources+- `meta.index`: concise capability catalog+- `meta.guide`: workflow for a user goal+- `meta.get_more_tools`: detailed params, examples, namespaces, and local/server behavior++Useful resources:++- `webstudio://project/status`: current ProjectSession status+- `webstudio://project/tools`: operation catalog+- `webstudio://project/guide`: concise discovery guide++## Core Rules++- Operate on the configured project only.+- Read ids before writing.+- Prefer semantic tools over `apply-patch`.+- Use `status` and `refresh` when cached namespaces may be stale.+- A mutation is durable only when `meta.session.committed` is true.+- For visual/design work, verify the rendered result with vision before finishing.++## Vision Verification Loop++Vision-capable AI can use MCP to see what it is building:++{{mcpVisionVerificationLoopMarkdown}}++Generated app setup:++{{mcpGeneratedAppDependencyNotes}}++## MCP Argument Examples++MCP tools receive JSON argument objects:++{{mcpArgumentExampleIndex}}++## Screenshot Verification++{{screenshotVerificationSummary}}diff --git a/packages/cli/src/docs/mcp-vision.md b/packages/cli/src/docs/mcp-vision.mdnew file mode 100644index 0000000000..ba4f31a667--- /dev/null+++ b/packages/cli/src/docs/mcp-vision.md@@ -0,0 +1,41 @@+# MCP Vision Verification++## Generated App Dependency Notes++- For a fresh checkout, copied fixture, or newly generated app, run npm install or pnpm install in the generated project before preview.start or webstudio preview.+- If preview fails with a missing generated-app command/package such as react-router or vite, install the generated app dependencies and retry.++## Visual Verification Rule++For visual/design work, use preview.start and screenshot after generated project files are current and generated app dependencies are installed so vision can inspect the rendered result before finishing. When a baseline exists, use screenshot.diff to get pixel regions, OCR text changes, and diff PNG artifacts.++## Vision Verification Loop++- Make focused page/content/style changes with semantic MCP tools.+- Make sure generated project files are current and generated app dependencies are installed, then call preview.start once to keep the generated site running.+- {{dependency-notes}}+- Call screenshot with { path: "/" } or the changed page path. Use waitForSelector when the page has a reliable ready marker, waitUntil:"networkidle" for network-heavy pages, and waitForTimeout only for final visual settling.+- {{diff}} When a baseline PNG exists, call screenshot.diff with baselinePath, currentPath, and outputDir.+- {{diff}} Read screenshot.diff textAnalysis: it reports OCR status plus text that appeared, disappeared, moved, changed content, or changed font/style geometry. If OCR is unavailable, ask the user for permission to install Tesseract, then call vision.install-ocr with { "confirm": true }, or rely on visual inspection.+- Inspect the PNG and any diff artifacts with vision, then compare layout, OCR text evidence, color, spacing, imagery, and responsive framing against the user intent.+- If the screenshot does not match, apply another focused mutation and repeat screenshot verification.++## Workflow Summary With Diff++For visual/design work, make sure generated project files are current and generated app dependencies are installed, call preview.start, then screenshot({ path }); use screenshot.diff when a baseline exists, then inspect pixel regions, OCR textAnalysis, and PNG/diff artifacts with vision before finishing.++## Workflow Summary Without Diff++For visual/design work, make sure generated project files are current and generated app dependencies are installed, call preview.start, then screenshot({ path }); inspect the PNG with vision before finishing.++## Screenshot Verification Summary++Inside MCP, prefer preview.start plus screenshot({ path: "/" }) after generated project files are current and generated app dependencies are installed, so the preview server stays running for fast repeated checks. Screenshot waits for load by default, then fonts and two layout frames; pass waitForSelector for app readiness, waitUntil:"networkidle" for network-heavy pages, and waitForTimeout for final settling. When a baseline exists, use screenshot.diff for changed regions, OCR textAnalysis, and diff artifacts. Outside MCP, use webstudio preview and webstudio screenshot <url> --output current.png.++## Screenshot Diff Evidence++- Pixel evidence: total mismatch, changed regions, dominant color/luminance direction, diffPath, and contextDiffPath.+- OCR evidence: textAnalysis.status, provider, and changes for appeared/disappeared/content_changed/moved/font_changed text.+- OCR dependency: screenshot.diff uses the system tesseract binary when available. If missing, it returns ocr_unavailable_tesseract_not_found_or_failed and still returns pixel evidence.+- OCR install: MCP cannot prompt. Ask the user first; if they agree, call vision.install-ocr with { "confirm": true }. If automatic install is unavailable, follow the returned installUrl.+- Final judgment: OCR and pixel diff are evidence. A vision-capable model must still inspect screenshots/diff artifacts and compare the rendered result to user intent.diff --git a/packages/cli/src/error-codes.test.ts b/packages/cli/src/error-codes.test.tsnew file mode 100644index 0000000000..64c5d5a7a8--- /dev/null+++ b/packages/cli/src/error-codes.test.ts@@ -0,0 +1,18 @@+import { describe, expect, test } from "vitest";+import { getStableErrorCode } from "./error-codes";++describe("getStableErrorCode", () => {+ test("reads direct stable error codes", () => {+ expect(+ getStableErrorCode(Object.assign(new Error("Busy"), { code: "BUSY" }))+ ).toBe("BUSY");+ });++ test("reads http-client wrapped error codes", () => {+ expect(+ getStableErrorCode(+ Object.assign(new Error("Not found"), { data: { code: "NOT_FOUND" } })+ )+ ).toBe("NOT_FOUND");+ });+});diff --git a/packages/cli/src/error-codes.ts b/packages/cli/src/error-codes.tsnew file mode 100644index 0000000000..64ff329a0f--- /dev/null+++ b/packages/cli/src/error-codes.ts@@ -0,0 +1,14 @@+import { getApiErrorCode } from "@webstudio-is/http-client";++export const getStableErrorCode = (error: unknown) => {+ const apiErrorCode = getApiErrorCode(error);+ if (apiErrorCode !== undefined) {+ return apiErrorCode;+ }+ if (typeof error === "object" && error !== null && "code" in error) {+ const code = (error as { code?: unknown }).code;+ if (typeof code === "string") {+ return code;+ }+ }+};diff --git a/packages/cli/src/fs-utils.test.ts b/packages/cli/src/fs-utils.test.tsindex 8ce07497cb..d6005db7a7 100644--- a/packages/cli/src/fs-utils.test.ts+++ b/packages/cli/src/fs-utils.test.ts@@ -1,8 +1,8 @@import { afterEach, beforeEach, expect, test } from "vitest";-import { mkdtemp, rm, writeFile } from "node:fs/promises";+import { mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises";import { join } from "node:path";import { tmpdir } from "node:os";-import { loadJSONFile } from "./fs-utils";+import { loadJSONFile, writeFileAtomic } from "./fs-utils";const originalCwd = process.cwd();let tempDir: string;@@ -32,3 +32,10 @@ test("throws for malformed JSON file", async () => {await expect(loadJSONFile("data.json")).rejects.toThrow();});++test("writes files atomically without leaving temporary files", async () => {+ await writeFileAtomic("nested/data.txt", "hello");++ await expect(readFile("nested/data.txt", "utf8")).resolves.toBe("hello");+ await expect(readdir("nested")).resolves.toEqual(["data.txt"]);+});diff --git a/packages/cli/src/fs-utils.ts b/packages/cli/src/fs-utils.tsindex 6adbdc7748..7379c5a939 100644--- a/packages/cli/src/fs-utils.ts+++ b/packages/cli/src/fs-utils.ts@@ -1,7 +1,10 @@import { dirname } from "node:path";+import { randomUUID } from "node:crypto";import {access,mkdir,+ rename,+ rm,writeFile,constants,readFile,@@ -39,6 +42,18 @@ export const createFolderIfNotExists = async (folderPath: string) => {}};+export const writeFileAtomic = async (filePath: string, content: string) => {+ const temporaryFilePath = `${filePath}.${process.pid}.${randomUUID()}.tmp`;+ await createFolderIfNotExists(dirname(filePath));+ try {+ await writeFile(temporaryFilePath, content, "utf8");+ await rename(temporaryFilePath, filePath);+ } catch (error) {+ await rm(temporaryFilePath, { force: true });+ throw error;+ }+};+export const loadJSONFile = async <T>(filePath: string): Promise<T | null> => {try {const content = await readFile(filePath, "utf8");diff --git a/packages/cli/src/json-output.test.ts b/packages/cli/src/json-output.test.tsnew file mode 100644index 0000000000..828cd08e63--- /dev/null+++ b/packages/cli/src/json-output.test.ts@@ -0,0 +1,19 @@+import { afterEach, expect, test, vi } from "vitest";+import { printJson } from "./json-output";++afterEach(() => {+ vi.restoreAllMocks();+});++test("prints pretty JSON", () => {+ vi.spyOn(console, "info").mockImplementation(() => undefined);++ printJson({ ok: true, data: { value: 1 } });++ expect(vi.mocked(console.info).mock.calls.at(-1)?.[0]).toBe(`{+ "ok": true,+ "data": {+ "value": 1+ }+}`);+});diff --git a/packages/cli/src/json-output.ts b/packages/cli/src/json-output.tsnew file mode 100644index 0000000000..6a86ea96ab--- /dev/null+++ b/packages/cli/src/json-output.ts@@ -0,0 +1,3 @@+export const printJson = (value: unknown) => {+ console.info(JSON.stringify(value, undefined, 2));+};diff --git a/packages/cli/src/mcp-guidance.test.ts b/packages/cli/src/mcp-guidance.test.tsnew file mode 100644index 0000000000..8dc3ecdaa9--- /dev/null+++ b/packages/cli/src/mcp-guidance.test.ts@@ -0,0 +1,37 @@+import { expect, test } from "vitest";+import {+ generatedAppDependencyNotes,+ getVisionVerificationLoop,+ getVisionWorkflowSummary,+ screenshotVerificationSummary,+ visualVerificationRule,+} from "./mcp-guidance";++test("documents generated app setup for visual verification", () => {+ expect(generatedAppDependencyNotes).toEqual([+ expect.stringContaining("npm install or pnpm install"),+ expect.stringContaining("react-router or vite"),+ ]);+ expect(visualVerificationRule).toContain("generated app dependencies");+ expect(screenshotVerificationSummary).toContain("preview.start");+});++test("builds vision loop with optional screenshot diff guidance", () => {+ const visionLoopWithDiff = getVisionVerificationLoop({ includeDiff: true });++ expect(getVisionVerificationLoop({ includeDiff: false })).not.toEqual(+ expect.arrayContaining([expect.stringContaining("screenshot.diff")])+ );+ expect(visionLoopWithDiff).toEqual(+ expect.arrayContaining([expect.stringContaining("screenshot.diff")])+ );+ expect(visionLoopWithDiff).toEqual(+ expect.arrayContaining([expect.stringContaining("vision.install-ocr")])+ );+ expect(getVisionWorkflowSummary({ includeDiff: false })).not.toContain(+ "screenshot.diff"+ );+ expect(getVisionWorkflowSummary({ includeDiff: true })).toContain(+ "screenshot.diff"+ );+});diff --git a/packages/cli/src/mcp-guidance.ts b/packages/cli/src/mcp-guidance.tsnew file mode 100644index 0000000000..172b34576d--- /dev/null+++ b/packages/cli/src/mcp-guidance.ts@@ -0,0 +1,63 @@+import { readCliDoc } from "./docs";++const mcpVisionMarkdown = readCliDoc("mcp-vision");++const getSection = (markdown: string, heading: string) => {+ const lines = markdown.split(/\r?\n/);+ const startIndex = lines.findIndex((line) => line === `## ${heading}`);+ if (startIndex === -1) {+ throw new Error(`Missing markdown section "${heading}".`);+ }+ const endIndex = lines.findIndex(+ (line, index) => index > startIndex && line.startsWith("## ")+ );+ return lines+ .slice(startIndex + 1, endIndex === -1 ? undefined : endIndex)+ .join("\n")+ .trim();+};++const getParagraph = (heading: string) =>+ getSection(mcpVisionMarkdown, heading);++const getListItems = (heading: string) =>+ getSection(mcpVisionMarkdown, heading)+ .split(/\r?\n/)+ .filter((line) => line.startsWith("- "))+ .map((line) => line.slice(2).trim());++export const generatedAppDependencyNotes = getListItems(+ "Generated App Dependency Notes"+);++export const visualVerificationRule = getParagraph("Visual Verification Rule");++const visionVerificationLoopItems = getListItems("Vision Verification Loop");++export const getVisionVerificationLoop = ({+ includeDiff,+}: {+ includeDiff: boolean;+}) =>+ visionVerificationLoopItems.flatMap((step) => {+ if (step === "{{dependency-notes}}") {+ return generatedAppDependencyNotes;+ }+ if (step.startsWith("{{diff}} ")) {+ return includeDiff ? [step.slice("{{diff}} ".length)] : [];+ }+ return [step];+ });++export const getVisionWorkflowSummary = ({+ includeDiff,+}: {+ includeDiff: boolean;+}) =>+ includeDiff+ ? getParagraph("Workflow Summary With Diff")+ : getParagraph("Workflow Summary Without Diff");++export const screenshotVerificationSummary = getParagraph(+ "Screenshot Verification Summary"+);diff --git a/packages/cli/src/preview-server.test.ts b/packages/cli/src/preview-server.test.tsnew file mode 100644index 0000000000..a00287a4f2--- /dev/null+++ b/packages/cli/src/preview-server.test.ts@@ -0,0 +1,183 @@+import { expect, test, vi } from "vitest";+import {+ createPreviewController,+ getPreviewDevArgs,+ getPreviewUrl,+ startPreviewDevServer,+ waitForPreviewReady,+ type PreviewServerDependencies,+} from "./preview-server";++const createDependencies = (+ overrides: Partial<PreviewServerDependencies> = {}+): PreviewServerDependencies => ({+ spawn: vi.fn(),+ fetch: vi.fn(async () => new Response("", { status: 200 })),+ sleep: vi.fn(async () => undefined),+ ...overrides,+});++const createPreviewProcess = (+ overrides: Partial<ReturnType<typeof startPreviewDevServer>["process"]> = {}+) =>+ ({+ pid: 123,+ killed: false,+ exitCode: null,+ signalCode: null,+ once: vi.fn(),+ ...overrides,+ }) as ReturnType<typeof startPreviewDevServer>["process"];++test("builds preview urls", () => {+ expect(getPreviewUrl({ host: "127.0.0.1", port: 5173, path: "/" })).toBe(+ "http://127.0.0.1:5173/"+ );+ expect(+ getPreviewUrl({ host: "127.0.0.1", port: 5173, path: "/pricing" })+ ).toBe("http://127.0.0.1:5173/pricing");+});++test("builds npm dev args with host and port", () => {+ expect(getPreviewDevArgs({ host: "127.0.0.1", port: 5173 })).toEqual([+ "run",+ "dev",+ "--",+ "--host",+ "127.0.0.1",+ "--port",+ "5173",+ ]);+});++test("starts generated project dev server with inherited stdio", () => {+ const process = {} as ReturnType<typeof startPreviewDevServer>["process"];+ const spawn = vi.fn(() => process);++ expect(+ startPreviewDevServer(+ { host: "127.0.0.1", port: 5173 },+ createDependencies({ spawn: spawn as never })+ )+ ).toEqual({+ url: "http://127.0.0.1:5173/",+ process,+ });+ expect(spawn).toHaveBeenCalledWith(+ "npm",+ ["run", "dev", "--", "--host", "127.0.0.1", "--port", "5173"],+ { stdio: "inherit" }+ );+});++test("preview controller reuses a running server", () => {+ const process = createPreviewProcess();+ const spawn = vi.fn(() => process);+ const controller = createPreviewController(+ { host: "127.0.0.1", port: 5173 },+ createDependencies({ spawn: spawn as never })+ );++ expect(controller.start()).toEqual({+ url: "http://127.0.0.1:5173/",+ pid: 123,+ running: true,+ });+ expect(controller.start()).toEqual({+ url: "http://127.0.0.1:5173/",+ pid: 123,+ running: true,+ });+ expect(controller.resolveUrl("/pricing")).toBe(+ "http://127.0.0.1:5173/pricing"+ );+ expect(spawn).toHaveBeenCalledTimes(1);+ expect(spawn).toHaveBeenCalledWith(+ "npm",+ ["run", "dev", "--", "--host", "127.0.0.1", "--port", "5173"],+ { stdio: ["ignore", "ignore", "ignore"] }+ );+});++test("preview controller rejects incompatible start options while running", () => {+ const process = createPreviewProcess();+ const controller = createPreviewController(+ { host: "127.0.0.1", port: 5173 },+ createDependencies({ spawn: vi.fn(() => process) as never })+ );++ controller.start();++ expect(() => controller.start({ port: 3000 })).toThrow(+ "Preview server is already running at http://127.0.0.1:5173/"+ );+});++test("preview controller reuses custom running options when start has no options", () => {+ const process = createPreviewProcess();+ const controller = createPreviewController(+ { host: "127.0.0.1", port: 5173 },+ createDependencies({ spawn: vi.fn(() => process) as never })+ );++ expect(controller.start({ port: 3000 })).toEqual({+ url: "http://127.0.0.1:3000/",+ pid: 123,+ running: true,+ });+ expect(controller.start()).toEqual({+ url: "http://127.0.0.1:3000/",+ pid: 123,+ running: true,+ });+});++test("waits for preview server readiness", async () => {+ const fetch = vi+ .fn()+ .mockRejectedValueOnce(new Error("not ready"))+ .mockResolvedValueOnce(new Response("", { status: 200 }));+ const sleep = vi.fn(async () => undefined);++ await waitForPreviewReady(+ "http://127.0.0.1:5173/",+ { timeoutMs: 1000, intervalMs: 5 },+ createDependencies({ fetch, sleep })+ );++ expect(fetch).toHaveBeenCalledTimes(2);+ expect(sleep).toHaveBeenCalledWith(5);+});++test("preview controller waits when starting through startAndWait", async () => {+ const process = createPreviewProcess();+ const fetch = vi.fn(async () => new Response("", { status: 200 }));+ const controller = createPreviewController(+ { host: "127.0.0.1", port: 5173 },+ createDependencies({ spawn: vi.fn(() => process) as never, fetch })+ );++ await expect(controller.startAndWait()).resolves.toEqual({+ url: "http://127.0.0.1:5173/",+ pid: 123,+ running: true,+ });+ expect(fetch).toHaveBeenCalledWith("http://127.0.0.1:5173/", {+ method: "GET",+ signal: expect.any(AbortSignal),+ });+});++test("preview controller fails immediately when the dev server exits before readiness", async () => {+ const process = createPreviewProcess({ exitCode: 1 });+ const fetch = vi.fn(async () => new Response("", { status: 200 }));+ const controller = createPreviewController(+ { host: "127.0.0.1", port: 5173 },+ createDependencies({ spawn: vi.fn(() => process) as never, fetch })+ );++ await expect(controller.startAndWait()).rejects.toThrow(+ "Preview server exited before it became ready at http://127.0.0.1:5173/."+ );+ expect(fetch).not.toHaveBeenCalled();+});diff --git a/packages/cli/src/preview-server.ts b/packages/cli/src/preview-server.tsnew file mode 100644index 0000000000..afc955740e--- /dev/null+++ b/packages/cli/src/preview-server.ts@@ -0,0 +1,177 @@+import {+ spawn,+ type ChildProcess,+ type StdioOptions,+} from "node:child_process";++export type PreviewServerOptions = {+ host: string;+ port: number;+};++export type PreviewServerResult = {+ url: string;+ process: ChildProcess;+};++export type PreviewServerDependencies = {+ spawn: typeof spawn;+ fetch: typeof fetch;+ sleep: (ms: number) => Promise<void>;+};++export const defaultPreviewServerDependencies: PreviewServerDependencies = {+ spawn,+ fetch,+ sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),+};++export const getPreviewUrl = ({+ host,+ port,+ path = "/",+}: PreviewServerOptions & { path?: string }) =>+ new URL(path, `http://${host}:${port}`).toString();++export const getPreviewDevArgs = ({ host, port }: PreviewServerOptions) => [+ "run",+ "dev",+ "--",+ "--host",+ host,+ "--port",+ String(port),+];++export const startPreviewDevServer = (+ options: PreviewServerOptions & { stdio?: StdioOptions },+ dependencies = defaultPreviewServerDependencies+): PreviewServerResult => {+ const process = dependencies.spawn("npm", getPreviewDevArgs(options), {+ stdio: options.stdio ?? "inherit",+ });+ return {+ url: getPreviewUrl(options),+ process,+ };+};++export const waitForPreviewExit = async (process: ChildProcess) => {+ const code = await new Promise<number | null>((resolve, reject) => {+ process.once("error", reject);+ process.once("exit", resolve);+ });+ if (code !== 0 && code !== null) {+ throw new Error(`Preview server exited with code ${code}.`);+ }+};++export type PreviewControllerResult = {+ url: string;+ pid?: number;+ running: boolean;+};++export const waitForPreviewReady = async (+ url: string,+ {+ timeoutMs = 30_000,+ intervalMs = 250,+ isRunning,+ }: {+ timeoutMs?: number;+ intervalMs?: number;+ isRunning?: () => boolean;+ } = {},+ dependencies = defaultPreviewServerDependencies+) => {+ const deadline = Date.now() + timeoutMs;+ while (Date.now() <= deadline) {+ if (isRunning?.() === false) {+ throw new Error(+ `Preview server exited before it became ready at ${url}.`+ );+ }+ try {+ const attemptTimeoutMs = Math.max(+ 1,+ Math.min(5000, deadline - Date.now())+ );+ const response = await dependencies.fetch(url, {+ method: "GET",+ signal: AbortSignal.timeout(attemptTimeoutMs),+ });+ if (response.status < 500) {+ return;+ }+ } catch {+ // Server is still starting.+ }+ await dependencies.sleep(intervalMs);+ }+ throw new Error(`Preview server did not become ready at ${url}.`);+};++export const createPreviewController = (+ defaults: PreviewServerOptions,+ dependencies = defaultPreviewServerDependencies+) => {+ let server: PreviewServerResult | undefined;+ let currentOptions = defaults;+ const isRunning = () =>+ server !== undefined &&+ server.process.killed === false &&+ server.process.exitCode === null &&+ server.process.signalCode === null;+ const getStatus = (): PreviewControllerResult => ({+ url: getPreviewUrl(currentOptions),+ pid: server?.process.pid,+ running: isRunning(),+ });+ const start = (+ options: Partial<PreviewServerOptions> = {}+ ): PreviewControllerResult => {+ const running = isRunning();+ const nextOptions = {+ host: options.host ?? (running ? currentOptions.host : defaults.host),+ port: options.port ?? (running ? currentOptions.port : defaults.port),+ };+ if (running) {+ if (+ nextOptions.host !== currentOptions.host ||+ nextOptions.port !== currentOptions.port+ ) {+ throw new Error(+ `Preview server is already running at ${getPreviewUrl(currentOptions)}. Stop it before starting a different preview server.`+ );+ }+ return getStatus();+ }+ currentOptions = nextOptions;+ server = startPreviewDevServer(+ {+ ...nextOptions,+ stdio: ["ignore", "ignore", "ignore"],+ },+ dependencies+ );+ server.process.once("exit", () => {+ server = undefined;+ });+ return getStatus();+ };+ return {+ start,+ async startAndWait(+ options: Partial<PreviewServerOptions> = {}+ ): Promise<PreviewControllerResult> {+ const result = start(options);+ await waitForPreviewReady(result.url, { isRunning }, dependencies);+ return result;+ },+ status: getStatus,+ resolveUrl(path = "/") {+ return getPreviewUrl({ ...currentOptions, path });+ },+ };+};diff --git a/packages/cli/src/project-session-api.test.ts b/packages/cli/src/project-session-api.test.tsnew file mode 100644index 0000000000..284fc7e284--- /dev/null+++ b/packages/cli/src/project-session-api.test.ts@@ -0,0 +1,224 @@+import { describe, expect, test, vi } from "vitest";+import { executeProjectSessionApiOperation } from "./project-session-api";++type CreateProjectSession = NonNullable<+ Parameters<+ typeof executeProjectSessionApiOperation+ >[0]["createProjectSession"]+>;++describe("project session api adapter", () => {+ test("routes local-capable commands through project session runtime", async () => {+ const session = {+ initialize: vi.fn(async () => undefined),+ read: vi.fn(async () => ({+ operationId: "pages.list",+ projectId: "project-1",+ source: "local",+ result: ["page"],+ state: { committed: false, freshness: {} },+ namespaces: {+ read: ["pages"],+ write: [],+ invalidated: [],+ missing: [],+ },+ diagnostics: [],+ })),+ mutate: vi.fn(),+ refresh: vi.fn(),+ executeServerOperation: vi.fn(),+ };+ const createProjectSession = vi.fn(+ () => session+ ) as unknown as CreateProjectSession;++ const result = await executeProjectSessionApiOperation({+ command: "list-pages",+ input: { includeFolders: true },+ connection: {+ projectId: "project-1",+ origin: "https://example.com",+ authToken: "token",+ },+ createProjectSession,+ });++ expect(session.read).toHaveBeenCalledWith(+ "pages.list",+ { projectId: "project-1", includeFolders: true },+ { permit: "view" }+ );+ expect(result.result).toEqual(["page"]);+ });++ test("keeps configured project id for local-capable commands", async () => {+ const session = {+ initialize: vi.fn(async () => undefined),+ read: vi.fn(async () => ({+ operationId: "pages.list",+ projectId: "project-1",+ source: "local",+ result: [],+ state: { committed: false, freshness: {} },+ namespaces: {+ read: ["pages"],+ write: [],+ invalidated: [],+ missing: [],+ },+ diagnostics: [],+ })),+ mutate: vi.fn(),+ refresh: vi.fn(),+ executeServerOperation: vi.fn(),+ };++ await executeProjectSessionApiOperation({+ command: "list-pages",+ input: { projectId: "other-project" },+ connection: {+ projectId: "project-1",+ origin: "https://example.com",+ authToken: "token",+ },+ createProjectSession: vi.fn(+ () => session+ ) as unknown as CreateProjectSession,+ });++ expect(session.read).toHaveBeenCalledWith(+ "pages.list",+ { projectId: "project-1" },+ { permit: "view" }+ );+ });++ test("routes server-only commands through project session transport", async () => {+ const session = {+ initialize: vi.fn(async () => undefined),+ read: vi.fn(),+ mutate: vi.fn(),+ executeServerOperation: vi.fn(async () => ({+ operationId: "auth.me",+ projectId: "project-1",+ source: "server",+ result: { actor: "token" },+ state: { committed: true, freshness: {} },+ namespaces: { read: [], write: [], invalidated: [], missing: [] },+ diagnostics: [],+ })),+ refresh: vi.fn(),+ };+ const createProjectSession = vi.fn(+ () => session+ ) as unknown as CreateProjectSession;++ const result = await executeProjectSessionApiOperation({+ command: "whoami",+ input: {},+ connection: {+ projectId: "project-1",+ origin: "https://example.com",+ authToken: "token",+ },+ createProjectSession,+ });++ expect(session.executeServerOperation).toHaveBeenCalledWith(+ {+ id: "auth.me",+ invalidatesNamespaces: [],+ refetchInvalidatedNamespaces: false,+ },+ {}+ );+ expect(result.result).toEqual({ actor: "token" });+ });++ test("refreshes local namespaces before local-capable commands when requested", async () => {+ const session = {+ initialize: vi.fn(async () => undefined),+ refresh: vi.fn(async () => undefined),+ read: vi.fn(async () => ({+ operationId: "pages.list",+ projectId: "project-1",+ source: "local",+ result: ["page"],+ state: { committed: false, freshness: {} },+ namespaces: {+ read: ["pages"],+ write: [],+ invalidated: [],+ missing: [],+ },+ diagnostics: [],+ })),+ mutate: vi.fn(),+ executeServerOperation: vi.fn(),+ };++ await executeProjectSessionApiOperation({+ command: "list-pages",+ input: {},+ connection: {+ projectId: "project-1",+ origin: "https://example.com",+ authToken: "token",+ },+ createProjectSession: vi.fn(+ () => session+ ) as unknown as CreateProjectSession,+ refresh: true,+ });++ expect(session.refresh).toHaveBeenCalledWith(["pages"]);+ });++ test("preserves project session diagnostic code on operation errors", async () => {+ const session = {+ initialize: vi.fn(async () => undefined),+ read: vi.fn(async () => ({+ operationId: "pages.list",+ projectId: "project-1",+ source: "local",+ result: undefined,+ state: { committed: false, freshness: {} },+ namespaces: {+ read: ["pages"],+ write: [],+ invalidated: [],+ missing: [],+ },+ diagnostics: [+ {+ level: "error",+ code: "PROJECT_SESSION_BUSY",+ message: "Project session snapshot changed on disk.",+ },+ ],+ })),+ mutate: vi.fn(),+ refresh: vi.fn(),+ executeServerOperation: vi.fn(),+ };++ await expect(+ executeProjectSessionApiOperation({+ command: "list-pages",+ input: {},+ connection: {+ projectId: "project-1",+ origin: "https://example.com",+ authToken: "token",+ },+ createProjectSession: vi.fn(+ () => session+ ) as unknown as CreateProjectSession,+ })+ ).rejects.toMatchObject({+ code: "PROJECT_SESSION_BUSY",+ message: "Project session snapshot changed on disk.",+ });+ });+});diff --git a/packages/cli/src/project-session-api.ts b/packages/cli/src/project-session-api.tsnew file mode 100644index 0000000000..e5ab4bb347--- /dev/null+++ b/packages/cli/src/project-session-api.ts@@ -0,0 +1,154 @@+import {+ getPublicApiOperation,+ type PublicApiCommand,+} from "@webstudio-is/protocol";+import {+ runtimeOperationContracts,+ type RuntimeOperationId,+} from "@webstudio-is/project-build/contracts/builder-runtime";+import type { BuilderNamespace } from "@webstudio-is/project-build/contracts/namespaces";+import type { ProjectSessionEnvelope } from "@webstudio-is/project-build/project-session";+import { createCliProjectSession } from "./project-session";++export type ProjectSessionApiConnection = {+ projectId: string;+ origin: string;+ authToken: string;+ headers?: Record<string, string | undefined>;+};++export type ProjectSessionApiCommand = PublicApiCommand;++type CreateProjectSession = typeof createCliProjectSession;++const uniqueNamespaces = (+ namespaces: readonly BuilderNamespace[]+): readonly BuilderNamespace[] => [...new Set(namespaces)];++const runtimeOperationIds = new Set<string>(+ runtimeOperationContracts.map((contract) => contract.id)+);++const isRuntimeOperationId = (id: string): id is RuntimeOperationId =>+ runtimeOperationIds.has(id);++const getRuntimeOperationId = (+ command: ProjectSessionApiCommand+): RuntimeOperationId | undefined => {+ const operation = getPublicApiOperation(command);+ return operation.runtimeOperationId !== undefined &&+ isRuntimeOperationId(operation.runtimeOperationId)+ ? operation.runtimeOperationId+ : undefined;+};++const getSessionError = (envelope: {+ diagnostics: readonly { level: string; code?: string; message: string }[];+}) => envelope.diagnostics.find((diagnostic) => diagnostic.level === "error");++const createProjectSessionApiError = (diagnostic: {+ code?: string;+ message: string;+}) => {+ const error = new Error(diagnostic.message) as Error & { code?: string };+ if (diagnostic.code !== undefined) {+ error.name = diagnostic.code;+ error.code = diagnostic.code;+ }+ return error;+};++const withProjectId = (+ input: unknown,+ projectId: string+): Record<string, unknown> => ({+ ...(typeof input === "object" && input !== null+ ? (input as Record<string, unknown>)+ : {}),+ projectId,+});++export const isProjectSessionEnvelope = (+ value: unknown+): value is ProjectSessionEnvelope =>+ typeof value === "object" &&+ value !== null &&+ "operationId" in value &&+ "projectId" in value &&+ "state" in value &&+ "namespaces" in value &&+ "diagnostics" in value;++export const getProjectSessionMeta = (envelope: ProjectSessionEnvelope) => ({+ operationId: envelope.operationId,+ projectId: envelope.projectId,+ buildId: envelope.buildId,+ version: envelope.version,+ source: envelope.source,+ committed: envelope.state.committed,+ compatibility: envelope.state.compatibility,+ namespaces: envelope.namespaces,+ diagnostics: envelope.diagnostics,+});++export const executeProjectSessionApiOperation = async ({+ command,+ input,+ connection,+ createProjectSession = createCliProjectSession,+ dryRun = false,+ refresh = false,+}: {+ command: ProjectSessionApiCommand;+ input: unknown;+ connection: ProjectSessionApiConnection;+ createProjectSession?: CreateProjectSession;+ dryRun?: boolean;+ refresh?: boolean;+}) => {+ const runtimeOperationId = getRuntimeOperationId(command);+ const operation = getPublicApiOperation(command);+ if (+ dryRun === true &&+ (runtimeOperationId === undefined || operation.method !== "mutation")+ ) {+ throw new Error(`${command} does not support --dry-run.`);+ }+ const session = createProjectSession({ connection });+ await session.initialize();+ if (refresh && runtimeOperationId !== undefined) {+ await session.refresh(+ uniqueNamespaces([+ ...operation.readNamespaces,+ ...operation.writeNamespaces,+ ])+ );+ }+ const envelope =+ runtimeOperationId === undefined+ ? await session.executeServerOperation(+ {+ id: operation.id,+ invalidatesNamespaces: operation.invalidatesNamespaces,+ refetchInvalidatedNamespaces:+ operation.invalidatesNamespaces.length > 0,+ },+ input+ )+ : operation.method === "query"+ ? await session.read(+ runtimeOperationId,+ withProjectId(input, connection.projectId),+ { permit: operation.permit }+ )+ : await session.mutate(+ runtimeOperationId,+ withProjectId(input, connection.projectId),+ { permit: operation.permit, dryRun }+ );+ const error = getSessionError(envelope);+ if (error !== undefined) {+ throw createProjectSessionApiError(error);+ }+ return envelope;+};diff --git a/packages/cli/src/project-session.test.ts b/packages/cli/src/project-session.test.tsnew file mode 100644index 0000000000..0d009206bd--- /dev/null+++ b/packages/cli/src/project-session.test.ts@@ -0,0 +1,286 @@+import { mkdtemp, readFile, rm } from "node:fs/promises";+import { join } from "node:path";+import { tmpdir } from "node:os";+import { afterEach, describe, expect, test, vi } from "vitest";+import { createBuilderStateFromSnapshot } from "@webstudio-is/project-build/state/adapters";+import { createBuilderStateFreshness } from "@webstudio-is/project-build/state/freshness";+import {+ createCliProjectSessionStorage,+ createCliProjectSessionTransport,+} from "./project-session";++const temporaryDirectories: string[] = [];++const createTemporaryDirectory = async () => {+ const directory = await mkdtemp(join(tmpdir(), "webstudio-session-"));+ temporaryDirectories.push(directory);+ return directory;+};++afterEach(async () => {+ vi.unstubAllGlobals();+ await Promise.all(+ temporaryDirectories+ .splice(0)+ .map((directory) => rm(directory, { recursive: true, force: true }))+ );+});++describe("cli project session storage", () => {+ test("persists builder state snapshots as JSON and checks revisions", async () => {+ const directory = await createTemporaryDirectory();+ const path = join(directory, ".webstudio", "project-session.json");+ const storage = createCliProjectSessionStorage(path);+ const state = createBuilderStateFromSnapshot({+ pages: {+ homePageId: "home",+ rootFolderId: "root",+ pages: new Map([+ [+ "home",+ {+ id: "home",+ name: "Home",+ path: "",+ title: "Home",+ rootInstanceId: "body",+ meta: {},+ },+ ],+ ]),+ folders: new Map([+ ["root", { id: "root", name: "Root", slug: "", children: ["home"] }],+ ]),+ },+ instances: [+ [+ "body",+ { type: "instance", id: "body", component: "Body", children: [] },+ ],+ ],+ });++ const first = await storage.save(+ {+ projectId: "project-1",+ buildId: "build-1",+ version: 1,+ state,+ freshness: createBuilderStateFreshness({ state, version: 1 }),+ compatibilityVersion: "test",+ compatibility: {+ sessionVersion: "test",+ runtimeContractVersion: "test-runtime",+ projectSchemaVersion: "test-schema",+ },+ },+ {}+ );++ const persisted = await storage.load();+ expect(persisted?.state.pages?.pages.has("home")).toBe(true);+ expect(persisted?.state.instances?.has("body")).toBe(true);+ const saved = JSON.parse(await readFile(path, "utf-8"));++ expect(saved.state.pages.pages).toEqual([+ {+ id: "home",+ name: "Home",+ path: "",+ title: "Home",+ rootInstanceId: "body",+ meta: {},+ },+ ]);+ expect(saved.state.pages.folders).toEqual([+ { id: "root", name: "Root", slug: "", children: ["home"] },+ ]);+ expect(saved.state.instances).toEqual([+ [+ "body",+ { type: "instance", id: "body", component: "Body", children: [] },+ ],+ ]);++ await expect(+ storage.save(+ {+ ...persisted!,+ version: 2,+ },+ { expectedRevision: "stale" }+ )+ ).rejects.toThrow("changed on disk");++ await expect(+ storage.save(+ {+ ...persisted!,+ version: 2,+ },+ { expectedRevision: first?.revision }+ )+ ).resolves.toEqual({ revision: expect.any(String) });+ });+});++describe("cli project session transport", () => {+ test("adapts public API build snapshots into project-session state", async () => {+ const transport = createCliProjectSessionTransport({+ connection: {+ projectId: "project-1",+ origin: "https://example.com",+ authToken: "token",+ },+ getBuildSnapshot: async (input) => {+ expect(input.include).toEqual(["pages", "folders", "instances"]);+ return {+ projectId: "project-1",+ buildId: "build-1",+ version: 1,+ pages: [+ {+ id: "home",+ name: "Home",+ path: "",+ title: "Home",+ rootInstanceId: "body",+ meta: {},+ },+ ],+ homePageId: "home",+ rootFolderId: "root",+ meta: { siteName: "Acme" },+ compiler: { atomicStyles: true },+ redirects: [{ old: "/old", new: "/new", status: "301" }],+ folders: [+ {+ id: "root",+ name: "Root",+ slug: "",+ children: ["home"],+ },+ ],+ instances: [+ {+ type: "instance",+ id: "body",+ component: "Body",+ children: [],+ },+ ],+ };+ },+ });++ const snapshot = await transport.fetchNamespaces({+ projectId: "project-1",+ namespaces: ["pages", "instances"],+ });++ expect(snapshot.state.pages?.pages.get("home")?.name).toBe("Home");+ expect(snapshot.state.pages?.meta).toEqual({ siteName: "Acme" });+ expect(snapshot.state.pages?.compiler).toEqual({ atomicStyles: true });+ expect(snapshot.state.pages?.redirects).toEqual([+ { old: "/old", new: "/new", status: "301" },+ ]);+ expect(snapshot.state.pages?.folders.get("root")?.children).toEqual([+ "home",+ ]);+ expect(snapshot.state.instances?.get("body")?.component).toBe("Body");+ });++ test("adapts injected permission reader to project session transport", async () => {+ const transport = createCliProjectSessionTransport({+ connection: {+ projectId: "project-1",+ origin: "https://example.com",+ authToken: "token",+ },+ getPermissions: async (input) => {+ expect(input).toEqual({ projectId: "project-1" });+ return {+ canView: true,+ canEdit: false,+ canBuild: false,+ canAdmin: false,+ canUseApi: true,+ };+ },+ });++ await expect(+ transport.getPermissions?.({ projectId: "project-1" })+ ).resolves.toEqual({+ canView: true,+ canEdit: false,+ canBuild: false,+ canAdmin: false,+ canUseApi: true,+ });+ });++ test("reports transport compatibility metadata", async () => {+ const transport = createCliProjectSessionTransport({+ connection: {+ projectId: "project-1",+ origin: "https://example.com",+ authToken: "token",+ headers: { "x-webstudio-client-version": "1.2.3" },+ },+ });++ await expect(+ transport.getCompatibility?.({ projectId: "project-1" })+ ).resolves.toEqual(+ expect.objectContaining({+ sessionVersion: "cli-project-session-v1",+ apiCompatibilityVersion: "1.2.3",+ })+ );+ });++ test("keeps configured project id for default server operation transport", async () => {+ let requestBody = "";+ let requestUrl = "";+ const fetch = vi.fn(async (request: URL | RequestInfo) => {+ if (request instanceof Request) {+ requestUrl = request.url;+ requestBody = await request.clone().text();+ } else {+ requestUrl = String(request);+ }+ return new Response(+ JSON.stringify([+ {+ result: {+ data: {+ id: "project-1",+ buildId: "build-1",+ version: 1,+ },+ },+ },+ ]),+ { headers: { "content-type": "application/json" } }+ );+ });+ vi.stubGlobal("fetch", fetch);+ const transport = createCliProjectSessionTransport({+ connection: {+ projectId: "project-1",+ origin: "https://example.com",+ authToken: "token",+ },+ });++ await transport.executeServerOperation?.({+ operationId: "projects.get",+ input: { projectId: "other-project" },+ });++ const requestText = `${requestUrl}\n${requestBody}`;+ expect(requestText).toContain("project-1");+ expect(requestText).not.toContain("other-project");+ });+});diff --git a/packages/cli/src/project-session.ts b/packages/cli/src/project-session.tsnew file mode 100644index 0000000000..9f1b7bf6c6--- /dev/null+++ b/packages/cli/src/project-session.ts@@ -0,0 +1,317 @@+import { readFile, rm } from "node:fs/promises";+import { dirname, join } from "node:path";+import { cwd } from "node:process";+import { migratePages } from "@webstudio-is/project-migrations/pages";+import * as httpClient from "@webstudio-is/http-client";+import { publicApiOperations } from "@webstudio-is/protocol";+import {+ createProjectSession,+ createDefaultProjectSessionCompatibility,+ type ProjectSessionCompatibility,+ type ProjectSessionPersistedSnapshot,+ type ProjectSessionPermissions,+ type ProjectSessionRemoteSnapshot,+ type ProjectSessionStorage,+ type ProjectSessionTransport,+} from "@webstudio-is/project-build/project-session";+import type { BuilderNamespace } from "@webstudio-is/project-build/contracts/namespaces";+import {+ createBuilderStateFromBuildData,+ createBuilderStateFromSerializedSnapshot,+ createSerializedBuilderStateSnapshotFromState,+ type BuilderBuildDataSnapshot,+ type SerializedBuilderStateSnapshot,+} from "@webstudio-is/project-build/state/adapters";+import type { BuilderStateFreshness } from "@webstudio-is/project-build/state/freshness";+import { LOCAL_CONFIG_FILE } from "./config";+import { getStableErrorCode } from "./error-codes";+import { writeFileAtomic } from "./fs-utils";++type ApiConnection = {+ projectId: string;+ origin: string;+ authToken: string;+ headers?: Record<string, string | undefined>;+};++type PublicBuildSnapshot = Omit<+ BuilderBuildDataSnapshot,+ "dataSources" | "pages"+> & {+ projectId: string;+ buildId: string;+ version: number;+ homePageId?: string;+ rootFolderId?: string;+ pages?: unknown;+ folders?: unknown;+ meta?: unknown;+ compiler?: unknown;+ redirects?: unknown;+ dataSources?: BuilderBuildDataSnapshot["dataSources"];+ variables?: BuilderBuildDataSnapshot["dataSources"];+};++type PersistedCliProjectSessionSnapshot = Omit<+ ProjectSessionPersistedSnapshot,+ "state"+> & {+ state: SerializedBuilderStateSnapshot;+};++const sessionFile = join(dirname(LOCAL_CONFIG_FILE), "project-session.json");+const compatibilityVersion = "cli-project-session-v1";++const createCliProjectSessionCompatibility = (+ connection: ApiConnection+): ProjectSessionCompatibility => ({+ ...createDefaultProjectSessionCompatibility(compatibilityVersion),+ apiCompatibilityVersion: connection.headers?.["x-webstudio-client-version"],+});++const toPublicApiInclude = (namespaces: readonly BuilderNamespace[]) => [+ ...new Set(+ namespaces.flatMap((namespace) => {+ if (namespace === "dataSources") {+ return ["variables"];+ }+ if (namespace === "pages") {+ return ["pages", "folders"];+ }+ return [namespace];+ })+ ),+];++const toPages = (snapshot: PublicBuildSnapshot) => {+ if (snapshot.pages === undefined) {+ return undefined;+ }+ return migratePages({+ homePageId: snapshot.homePageId,+ rootFolderId: snapshot.rootFolderId,+ pages: snapshot.pages,+ folders: snapshot.folders,+ meta: snapshot.meta,+ compiler: snapshot.compiler,+ redirects: snapshot.redirects,+ });+};++const toRemoteSnapshot = (+ snapshot: PublicBuildSnapshot+): ProjectSessionRemoteSnapshot => ({+ projectId: snapshot.projectId,+ buildId: snapshot.buildId,+ version: snapshot.version,+ state: createBuilderStateFromBuildData({+ ...snapshot,+ pages: toPages(snapshot),+ dataSources: snapshot.dataSources ?? snapshot.variables ?? [],+ }),+});++const publicOperationById = new Map(+ publicApiOperations.map((operation) => [operation.id, operation])+);++const executePublicServerOperation = async ({+ connection,+ operationId,+ input,+}: {+ connection: ApiConnection;+ operationId: string;+ input: unknown;+}) => {+ const operation = publicOperationById.get(operationId);+ if (operation === undefined) {+ throw new Error(`Unknown public API operation "${operationId}".`);+ }+ const client = httpClient[operation.client as keyof typeof httpClient] as+ | ((input: Record<string, unknown>) => Promise<unknown>)+ | undefined;+ if (typeof client !== "function") {+ throw new Error(+ `Public API operation "${operationId}" has no http-client function.`+ );+ }+ return await client({+ ...connection,+ ...(input as Record<string, unknown>),+ projectId: connection.projectId,+ });+};++const withMappedRemoteError = async <Result>(task: () => Promise<Result>) => {+ try {+ return await task();+ } catch (error) {+ const code = getStableErrorCode(error);+ if (code === undefined) {+ throw error;+ }+ const mapped = new Error(+ error instanceof Error ? error.message : String(error)+ ) as Error & { code: string };+ mapped.name = code;+ mapped.code = code;+ throw mapped;+ }+};++const parsePersistedSnapshot = (+ value: PersistedCliProjectSessionSnapshot+): ProjectSessionPersistedSnapshot => ({+ ...value,+ state: createBuilderStateFromSerializedSnapshot(value.state),+});++const serializePersistedSnapshot = (+ snapshot: ProjectSessionPersistedSnapshot+): PersistedCliProjectSessionSnapshot => ({+ ...snapshot,+ state: createSerializedBuilderStateSnapshotFromState(snapshot.state),+});++export const createCliProjectSessionStorage = (+ path = join(cwd(), sessionFile)+): ProjectSessionStorage => ({+ async load() {+ try {+ const value = JSON.parse(await readFile(path, "utf-8"));+ return parsePersistedSnapshot(value);+ } catch (error) {+ if (+ error instanceof Error &&+ "code" in error &&+ (error as { code?: unknown }).code === "ENOENT"+ ) {+ return undefined;+ }+ throw error;+ }+ },+ async save(snapshot, options) {+ const current = await this.load();+ if (+ options.expectedRevision !== undefined &&+ current?.revision !== options.expectedRevision+ ) {+ throw new Error("Project session snapshot changed on disk.");+ }+ const revision = crypto.randomUUID();+ await writeFileAtomic(+ path,+ `${JSON.stringify(+ serializePersistedSnapshot({ ...snapshot, revision }),+ undefined,+ 2+ )}\n`+ );+ return { revision };+ },+ async clear() {+ await rm(path, { force: true });+ },+});++export const createCliProjectSessionTransport = ({+ connection,+ executeServerOperation,+ getBuildSnapshot = httpClient.getBuildSnapshot,+ getPermissions,+}: {+ connection: ApiConnection;+ executeServerOperation?: ProjectSessionTransport["executeServerOperation"];+ getBuildSnapshot?: typeof httpClient.getBuildSnapshot;+ getPermissions?: ProjectSessionTransport["getPermissions"];+}): ProjectSessionTransport => ({+ async getCompatibility() {+ return createCliProjectSessionCompatibility(connection);+ },+ async fetchNamespaces({ namespaces }) {+ const snapshot = (await withMappedRemoteError(() =>+ getBuildSnapshot({+ ...connection,+ include: toPublicApiInclude(namespaces),+ })+ )) as PublicBuildSnapshot;+ return toRemoteSnapshot(snapshot);+ },+ async commitPatch({ baseVersion, transactions }) {+ return (await withMappedRemoteError(() =>+ httpClient.applyBuildPatch({+ ...connection,+ baseVersion,+ transactions,+ })+ )) as { version: number };+ },+ getPermissions:+ getPermissions ??+ (async () => {+ const permissions =+ await withMappedRemoteError<ProjectSessionPermissions>(+ () =>+ httpClient.getProjectPermissions(+ connection+ ) as Promise<ProjectSessionPermissions>+ );+ return {+ canView: permissions.canView,+ canEdit: permissions.canEdit,+ canBuild: permissions.canBuild,+ canAdmin: permissions.canAdmin,+ canUseApi: permissions.canUseApi,+ };+ }),+ executeServerOperation:+ executeServerOperation ??+ (async <Result>({+ operationId,+ input,+ }: {+ operationId: string;+ input: unknown;+ }) =>+ (await withMappedRemoteError(() =>+ executePublicServerOperation({ connection, operationId, input })+ )) as Result),+});++export const createCliProjectSession = ({+ connection,+ storage = createCliProjectSessionStorage(),+ executeServerOperation,+ getPermissions,+ createId = () => crypto.randomUUID(),+ now = () => new Date(),+}: {+ connection: ApiConnection;+ storage?: ProjectSessionStorage;+ executeServerOperation?: ProjectSessionTransport["executeServerOperation"];+ getPermissions?: ProjectSessionTransport["getPermissions"];+ createId?: () => string;+ now?: () => Date;+}) =>+ createProjectSession({+ projectId: connection.projectId,+ transport: createCliProjectSessionTransport({+ connection,+ executeServerOperation,+ getPermissions,+ }),+ storage,+ compatibilityVersion,+ runtimeContext: { createId, now },+ });++export type CliProjectSession = ReturnType<typeof createCliProjectSession>;++export type CliProjectSessionSnapshot = {+ projectId: string;+ buildId: string;+ version: number;+ freshness: BuilderStateFreshness;+};diff --git a/packages/cli/src/screenshot-browser-cdp.test.ts b/packages/cli/src/screenshot-browser-cdp.test.tsnew file mode 100644index 0000000000..2c9784d14e--- /dev/null+++ b/packages/cli/src/screenshot-browser-cdp.test.ts@@ -0,0 +1,328 @@+import { Buffer } from "node:buffer";+import { expect, test, vi } from "vitest";+import {+ captureBrowserScreenshot,+ type BrowserScreenshotDependencies,+} from "./screenshot-browser-cdp";++class FakeBrowserProcess {+ readonly listeners = new Map<string, Array<(value?: unknown) => void>>();+ kill = vi.fn(() => {+ this.emit("exit", 0);+ return true;+ });+ once = vi.fn((event: string, listener: (value?: unknown) => void) => {+ const listeners = this.listeners.get(event) ?? [];+ listeners.push(listener);+ this.listeners.set(event, listeners);+ return this;+ });+ emit = (event: string, value?: unknown) => {+ const listeners = this.listeners.get(event) ?? [];+ this.listeners.delete(event);+ for (const listener of listeners) {+ listener(value);+ }+ };+}++class FakeWebSocket {+ readonly sentMethods: string[] = [];+ readonly listeners = new Map<+ string,+ Array<(event: { data?: string }) => void>+ >();++ constructor() {+ setTimeout(() => this.emit("open"), 0);+ }++ addEventListener = (+ event: string,+ listener: (event: { data?: string }) => void+ ) => {+ const listeners = this.listeners.get(event) ?? [];+ listeners.push(listener);+ this.listeners.set(event, listeners);+ };++ close = vi.fn();++ send = (data: string) => {+ const message = JSON.parse(data) as {+ id: number;+ method: string;+ params?: Record<string, unknown>;+ };+ this.sentMethods.push(message.method);+ const respond = (result: unknown = {}) => {+ this.emit("message", {+ data: JSON.stringify({ id: message.id, result }),+ });+ };+ if (+ message.method === "Runtime.evaluate" &&+ typeof message.params?.expression === "string" &&+ message.params.expression.includes("document.querySelector")+ ) {+ setTimeout(() => respond({ result: { value: true } }), 0);+ return;+ }+ if (message.method === "Page.captureScreenshot") {+ setTimeout(+ () =>+ respond({+ data: Buffer.from("fake-png").toString("base64"),+ }),+ 0+ );+ return;+ }+ setTimeout(() => {+ respond();+ if (message.method === "Page.navigate") {+ this.emit("message", {+ data: JSON.stringify({+ method: "Page.lifecycleEvent",+ params: { name: "networkIdle" },+ }),+ });+ }+ }, 0);+ };++ emit = (event: string, payload: { data?: string } = {}) => {+ for (const listener of this.listeners.get(event) ?? []) {+ listener(payload);+ }+ };+}++class HangingWebSocket extends FakeWebSocket {+ send = () => {+ this.sentMethods.push("unanswered");+ };+}++class NavigationErrorWebSocket extends FakeWebSocket {+ send = (data: string) => {+ const message = JSON.parse(data) as {+ id: number;+ method: string;+ params?: Record<string, unknown>;+ };+ this.sentMethods.push(message.method);+ if (message.method === "Page.navigate") {+ setTimeout(+ () =>+ this.emit("message", {+ data: JSON.stringify({+ id: message.id,+ result: { errorText: "Cannot navigate to invalid URL" },+ }),+ }),+ 0+ );+ return;+ }+ setTimeout(+ () =>+ this.emit("message", {+ data: JSON.stringify({ id: message.id, result: {} }),+ }),+ 0+ );+ };+}++const createDependencies = ({+ browserProcess = new FakeBrowserProcess(),+ socket = new FakeWebSocket(),+ fetch,+}: {+ browserProcess?: FakeBrowserProcess;+ socket?: FakeWebSocket;+ fetch?: BrowserScreenshotDependencies["fetch"];+} = {}): BrowserScreenshotDependencies => {+ const defaultFetch = vi.fn(async (url: string) => ({+ json: async () =>+ url.endsWith("/json/list")+ ? [+ {+ type: "page",+ webSocketDebuggerUrl: "ws://127.0.0.1:9222/page/1",+ },+ ]+ : {},+ })) as unknown as typeof globalThis.fetch;+ return {+ spawnBrowser: vi.fn(+ () => browserProcess+ ) as unknown as BrowserScreenshotDependencies["spawnBrowser"],+ mkdtemp: vi.fn(+ async () => "/tmp/webstudio-browser-test"+ ) as unknown as BrowserScreenshotDependencies["mkdtemp"],+ readFile: vi.fn(+ async () => "9222\n/devtools/browser/1\n"+ ) as unknown as BrowserScreenshotDependencies["readFile"],+ writeFile: vi.fn(async () => undefined),+ rm: vi.fn(async () => undefined),+ fetch: fetch ?? defaultFetch,+ createWebSocket: vi.fn(() => socket as unknown as WebSocket),+ };+};++test("captures through DevTools with lifecycle and selector waits", async () => {+ const browserProcess = new FakeBrowserProcess();+ const socket = new FakeWebSocket();+ const dependencies = createDependencies({ browserProcess, socket });++ await captureBrowserScreenshot(+ {+ url: "https://example.com",+ output: "/tmp/current.png",+ width: 800,+ height: 600,+ browserPath: "/usr/bin/chromium",+ uid: 0,+ waitUntil: "networkidle",+ waitForSelector: "#ready",+ waitForTimeout: 0,+ timeout: 1000,+ },+ dependencies+ );++ expect(dependencies.spawnBrowser).toHaveBeenCalledWith(+ "/usr/bin/chromium",+ expect.arrayContaining([+ "--headless=new",+ "--remote-debugging-port=0",+ "--user-data-dir=/tmp/webstudio-browser-test",+ "--window-size=800,600",+ "--no-sandbox",+ "about:blank",+ ])+ );+ expect(dependencies.fetch).toHaveBeenCalledWith(+ "http://127.0.0.1:9222/json/new?about:blank",+ { method: "PUT" }+ );+ expect(dependencies.fetch).toHaveBeenCalledWith(+ "http://127.0.0.1:9222/json/list"+ );+ expect(dependencies.createWebSocket).toHaveBeenCalledWith(+ "ws://127.0.0.1:9222/page/1"+ );+ expect(socket.sentMethods).toEqual(+ expect.arrayContaining([+ "Page.enable",+ "Runtime.enable",+ "Page.setLifecycleEventsEnabled",+ "Emulation.setDeviceMetricsOverride",+ "Page.navigate",+ "Runtime.evaluate",+ "Page.captureScreenshot",+ ])+ );+ expect(dependencies.writeFile).toHaveBeenCalledWith(+ "/tmp/current.png",+ Buffer.from("fake-png")+ );+ expect(socket.close).toHaveBeenCalled();+ expect(browserProcess.kill).toHaveBeenCalled();+ expect(dependencies.rm).toHaveBeenCalledWith("/tmp/webstudio-browser-test", {+ recursive: true,+ force: true,+ });+});++test("times out when browser DevTools commands stop responding", async () => {+ const browserProcess = new FakeBrowserProcess();+ const socket = new HangingWebSocket();+ const dependencies = createDependencies({ browserProcess, socket });++ await expect(+ captureBrowserScreenshot(+ {+ url: "https://example.com",+ output: "/tmp/current.png",+ width: 800,+ height: 600,+ browserPath: "/usr/bin/chromium",+ waitUntil: "load",+ waitForTimeout: 0,+ timeout: 10,+ },+ dependencies+ )+ ).rejects.toThrow("Browser command Page.enable did not finish within 10ms.");++ expect(browserProcess.kill).toHaveBeenCalled();+ expect(dependencies.rm).toHaveBeenCalledWith("/tmp/webstudio-browser-test", {+ recursive: true,+ force: true,+ });+});++test("times out when browser page target creation does not respond", async () => {+ const browserProcess = new FakeBrowserProcess();+ const dependencies = createDependencies({+ browserProcess,+ fetch: vi.fn(+ async () => await new Promise<Response>(() => undefined)+ ) as unknown as BrowserScreenshotDependencies["fetch"],+ });++ await expect(+ captureBrowserScreenshot(+ {+ url: "https://example.com",+ output: "/tmp/current.png",+ width: 800,+ height: 600,+ browserPath: "/usr/bin/chromium",+ waitUntil: "load",+ waitForTimeout: 0,+ timeout: 10,+ },+ dependencies+ )+ ).rejects.toThrow("Browser page target could not be created within 10ms.");++ expect(browserProcess.kill).toHaveBeenCalled();+ expect(dependencies.rm).toHaveBeenCalledWith("/tmp/webstudio-browser-test", {+ recursive: true,+ force: true,+ });+});++test("reports browser navigation errors directly", async () => {+ const browserProcess = new FakeBrowserProcess();+ const socket = new NavigationErrorWebSocket();+ const dependencies = createDependencies({ browserProcess, socket });++ await expect(+ captureBrowserScreenshot(+ {+ url: "invalid-url",+ output: "/tmp/current.png",+ width: 800,+ height: 600,+ browserPath: "/usr/bin/chromium",+ waitUntil: "load",+ waitForTimeout: 0,+ timeout: 1000,+ },+ dependencies+ )+ ).rejects.toThrow(+ "Browser navigation failed: Cannot navigate to invalid URL"+ );++ expect(browserProcess.kill).toHaveBeenCalled();+ expect(dependencies.rm).toHaveBeenCalledWith("/tmp/webstudio-browser-test", {+ recursive: true,+ force: true,+ });+});diff --git a/packages/cli/src/screenshot-browser-cdp.ts b/packages/cli/src/screenshot-browser-cdp.tsnew file mode 100644index 0000000000..1b4a7f1453--- /dev/null+++ b/packages/cli/src/screenshot-browser-cdp.ts@@ -0,0 +1,453 @@+import { Buffer } from "node:buffer";+import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { spawn, type ChildProcess } from "node:child_process";+import type { ScreenshotWaitUntil } from "@webstudio-is/project-build/visual/screenshot-browser";++type BrowserProcess = Pick<ChildProcess, "kill" | "once">;++export type BrowserScreenshotOptions = {+ browserPath: string;+ output: string;+ width: number;+ height: number;+ url: string;+ uid?: number;+ waitUntil: ScreenshotWaitUntil;+ waitForSelector?: string;+ waitForTimeout: number;+ timeout: number;+};++export type BrowserScreenshotDependencies = {+ spawnBrowser: (file: string, args: readonly string[]) => BrowserProcess;+ readFile: typeof readFile;+ writeFile: typeof writeFile;+ mkdtemp: typeof mkdtemp;+ rm: typeof rm;+ fetch: typeof fetch;+ createWebSocket: (url: string) => WebSocket;+};++export const defaultBrowserScreenshotDependencies: BrowserScreenshotDependencies =+ {+ spawnBrowser(file, args) {+ return spawn(file, [...args], { stdio: "ignore" });+ },+ readFile,+ writeFile,+ mkdtemp,+ rm,+ fetch,+ createWebSocket(url) {+ return new WebSocket(url);+ },+ };++const lifecycleEventByWaitUntil: Record<ScreenshotWaitUntil, string> = {+ commit: "commit",+ domcontentloaded: "DOMContentLoaded",+ load: "load",+ networkidle: "networkIdle",+};++const delay = (ms: number) =>+ new Promise<void>((resolveDelay) => setTimeout(resolveDelay, ms));++const createTimeoutError = (message: string, timeout: number) =>+ new Error(`${message} within ${timeout}ms.`);++const withDeadline = async <Result>(+ promise: Promise<Result>,+ message: string,+ timeout: number+): Promise<Result> => {+ let timeoutId: NodeJS.Timeout | undefined;+ const timeoutPromise = new Promise<never>((_, reject) => {+ timeoutId = setTimeout(() => {+ reject(createTimeoutError(message, timeout));+ }, timeout);+ });+ try {+ return await Promise.race([promise, timeoutPromise]);+ } finally {+ if (timeoutId !== undefined) {+ clearTimeout(timeoutId);+ }+ }+};++type CdpMessage = {+ id?: number;+ method?: string;+ params?: unknown;+ result?: unknown;+ error?: { message?: string };+};++class CdpSession {+ #nextId = 1;+ #callbacks = new Map<+ number,+ {+ resolve: (value: unknown) => void;+ reject: (error: Error) => void;+ }+ >();+ #listeners = new Map<string, Set<(params: unknown) => void>>();++ readonly #socket: WebSocket;++ constructor(socket: WebSocket) {+ this.#socket = socket;+ this.#socket.addEventListener("message", (event) => {+ const message = JSON.parse(String(event.data)) as CdpMessage;+ if (message.id !== undefined) {+ const callback = this.#callbacks.get(message.id);+ if (callback === undefined) {+ return;+ }+ this.#callbacks.delete(message.id);+ if (message.error !== undefined) {+ callback.reject(new Error(message.error.message ?? "CDP failed."));+ return;+ }+ callback.resolve(message.result);+ return;+ }+ if (message.method !== undefined) {+ for (const listener of this.#listeners.get(message.method) ?? []) {+ listener(message.params);+ }+ }+ });+ }++ static connect = async (+ url: string,+ dependencies: BrowserScreenshotDependencies,+ timeout: number+ ) => {+ const socket = dependencies.createWebSocket(url);+ await withDeadline(+ new Promise<void>((resolveConnection, rejectConnection) => {+ socket.addEventListener("open", () => resolveConnection(), {+ once: true,+ });+ socket.addEventListener(+ "error",+ () => rejectConnection(new Error("Could not connect to browser.")),+ { once: true }+ );+ }),+ "Browser DevTools connection did not open",+ timeout+ );+ return new CdpSession(socket);+ };++ close = () => {+ this.#socket.close();+ };++ on = (method: string, listener: (params: unknown) => void) => {+ let listeners = this.#listeners.get(method);+ if (listeners === undefined) {+ listeners = new Set();+ this.#listeners.set(method, listeners);+ }+ listeners.add(listener);+ return () => {+ listeners.delete(listener);+ };+ };++ send = async <Result = unknown>(+ method: string,+ params: Record<string, unknown> = {}+ ): Promise<Result> => {+ const id = this.#nextId;+ this.#nextId += 1;+ const result = new Promise<Result>((resolveSend, rejectSend) => {+ this.#callbacks.set(id, {+ resolve: (value) => resolveSend(value as Result),+ reject: rejectSend,+ });+ });+ this.#socket.send(JSON.stringify({ id, method, params }));+ return await result;+ };+}++const waitForDevToolsPort = async (+ userDataDir: string,+ dependencies: BrowserScreenshotDependencies,+ timeout: number+) =>+ await withDeadline(+ (async () => {+ const portFile = join(userDataDir, "DevToolsActivePort");+ while (true) {+ try {+ const [port, browserPath] = (+ await dependencies.readFile(portFile, "utf8")+ )+ .trim()+ .split(/\r?\n/);+ if (port !== undefined && browserPath !== undefined) {+ return { port, browserPath };+ }+ } catch {+ // Keep polling until Chromium creates DevToolsActivePort.+ }+ await delay(50);+ }+ })(),+ "Browser DevTools endpoint was not created",+ timeout+ );++const getPageWebSocketUrl = async ({+ port,+ dependencies,+ timeout,+}: {+ port: string;+ dependencies: BrowserScreenshotDependencies;+ timeout: number;+}) => {+ await withDeadline(+ dependencies.fetch(`http://127.0.0.1:${port}/json/new?about:blank`, {+ method: "PUT",+ }),+ "Browser page target could not be created",+ timeout+ );+ const targets = (await withDeadline(+ dependencies+ .fetch(`http://127.0.0.1:${port}/json/list`)+ .then((response) => response.json()),+ "Browser targets were not available",+ timeout+ )) as Array<{ type?: string; webSocketDebuggerUrl?: string }>;+ const target = targets.find(+ (candidate) =>+ candidate.type === "page" &&+ typeof candidate.webSocketDebuggerUrl === "string"+ );+ if (target?.webSocketDebuggerUrl === undefined) {+ throw new Error("Browser did not expose a page target.");+ }+ return target.webSocketDebuggerUrl;+};++const waitForLifecycleEvent = async (+ cdp: CdpSession,+ waitUntil: ScreenshotWaitUntil,+ timeout: number+) => {+ if (waitUntil === "commit") {+ return;+ }+ const expected = lifecycleEventByWaitUntil[waitUntil];+ await withDeadline(+ new Promise<void>((resolveLifecycle) => {+ const dispose = cdp.on("Page.lifecycleEvent", (params) => {+ if (+ typeof params === "object" &&+ params !== null &&+ "name" in params &&+ params.name === expected+ ) {+ dispose();+ resolveLifecycle();+ }+ });+ }),+ `Page did not reach ${waitUntil}`,+ timeout+ );+};++const waitForSelector = async (+ cdp: CdpSession,+ selector: string,+ timeout: number+) => {+ await withDeadline(+ (async () => {+ while (true) {+ const result = await cdp.send<{ result?: { value?: boolean } }>(+ "Runtime.evaluate",+ {+ expression: `document.querySelector(${JSON.stringify(selector)}) !== null`,+ returnByValue: true,+ }+ );+ if (result.result?.value === true) {+ return;+ }+ await delay(100);+ }+ })(),+ `Selector ${selector} was not found`,+ timeout+ );+};++const waitForFontsAndFrames = async (cdp: CdpSession, timeout: number) => {+ await withDeadline(+ cdp.send("Runtime.evaluate", {+ expression: `+ Promise.resolve(document.fonts?.ready).then(+ () => new Promise((resolve) => {+ requestAnimationFrame(() => requestAnimationFrame(resolve));+ })+ )+ `,+ awaitPromise: true,+ }),+ "Page fonts and animation frames were not ready",+ timeout+ );+};++const createBrowserLaunchArgs = ({+ userDataDir,+ width,+ height,+ uid,+}: {+ userDataDir: string;+ width: number;+ height: number;+ uid?: number;+}) => [+ "--headless=new",+ "--disable-gpu",+ "--hide-scrollbars",+ "--remote-debugging-port=0",+ `--user-data-dir=${userDataDir}`,+ `--window-size=${width},${height}`,+ "--no-first-run",+ "--no-default-browser-check",+ ...(uid === 0 ? ["--no-sandbox"] : []),+ "about:blank",+];++export const captureBrowserScreenshot = async (+ options: BrowserScreenshotOptions,+ dependencies = defaultBrowserScreenshotDependencies+) => {+ const userDataDir = await dependencies.mkdtemp(+ join(tmpdir(), "webstudio-browser-")+ );+ const browserProcess = dependencies.spawnBrowser(+ options.browserPath,+ createBrowserLaunchArgs({+ userDataDir,+ width: options.width,+ height: options.height,+ uid: options.uid,+ })+ );+ const browserClosed = new Promise<void>((resolveClosed) => {+ browserProcess.once("exit", () => resolveClosed());+ browserProcess.once("error", () => resolveClosed());+ });+ let cdp: CdpSession | undefined;+ try {+ await Promise.race([+ new Promise<never>((_, reject) => {+ browserProcess.once("error", reject);+ browserProcess.once("exit", (code) => {+ reject(+ new Error(+ `Browser exited before screenshot capture completed${+ code === null ? "." : ` with code ${code}.`+ }`+ )+ );+ });+ }),+ (async () => {+ const { port } = await waitForDevToolsPort(+ userDataDir,+ dependencies,+ options.timeout+ );+ const pageWebSocketUrl = await getPageWebSocketUrl({+ port,+ dependencies,+ timeout: options.timeout,+ });+ cdp = await CdpSession.connect(+ pageWebSocketUrl,+ dependencies,+ options.timeout+ );+ const send = async <Result = unknown>(+ method: string,+ params: Record<string, unknown> = {}+ ) =>+ await withDeadline(+ cdp?.send<Result>(method, params) ??+ Promise.reject(new Error("Browser DevTools session is closed.")),+ `Browser command ${method} did not finish`,+ options.timeout+ );+ await Promise.all([+ send("Page.enable"),+ send("Runtime.enable"),+ send("Page.setLifecycleEventsEnabled", { enabled: true }),+ send("Emulation.setDeviceMetricsOverride", {+ width: options.width,+ height: options.height,+ deviceScaleFactor: 1,+ mobile: false,+ }),+ ]);+ const lifecycle = waitForLifecycleEvent(+ cdp,+ options.waitUntil,+ options.timeout+ );+ const navigation = await send<{ errorText?: string }>("Page.navigate", {+ url: options.url,+ });+ if (navigation.errorText !== undefined) {+ throw new Error(`Browser navigation failed: ${navigation.errorText}`);+ }+ await lifecycle;+ if (options.waitForSelector !== undefined) {+ await waitForSelector(cdp, options.waitForSelector, options.timeout);+ }+ await waitForFontsAndFrames(cdp, options.timeout);+ if (options.waitForTimeout > 0) {+ await delay(options.waitForTimeout);+ }+ const screenshot = await send<{ data: string }>(+ "Page.captureScreenshot",+ {+ format: "png",+ captureBeyondViewport: false,+ }+ );+ await dependencies.writeFile(+ options.output,+ Buffer.from(screenshot.data, "base64")+ );+ })(),+ ]);+ } finally {+ cdp?.close();+ browserProcess.kill();+ await withDeadline(+ browserClosed,+ "Browser process did not exit after screenshot capture",+ 2000+ ).catch(() => undefined);+ await dependencies.rm(userDataDir, { recursive: true, force: true });+ }+};diff --git a/packages/cli/src/screenshot.test.ts b/packages/cli/src/screenshot.test.tsnew file mode 100644index 0000000000..a1b7352c74--- /dev/null+++ b/packages/cli/src/screenshot.test.ts@@ -0,0 +1,663 @@+import { describe, expect, test, vi } from "vitest";+import { constants } from "node:fs";+import {+ BrowserNotFoundError,+ BrowserInstallUnavailableError,+ captureScreenshot,+ captureScreenshotWithBrowserInstall,+ getChromiumInstallCommand,+ getNoBrowserFoundMessage,+ installTesseractForOcr,+ resolveScreenshotBrowser,+ shouldOfferBrowserInstall,+ tesseractInstallUrl,+ type ScreenshotDependencies,+} from "./screenshot";++const createDependencies = (+ overrides: Partial<ScreenshotDependencies> = {}+): ScreenshotDependencies => ({+ env: {},+ platform: "linux",+ access: vi.fn(async () => undefined),+ mkdir: vi.fn(async () => undefined),+ which: vi.fn(async () => undefined),+ getChromeLauncherInstallations: vi.fn(() => []),+ spawnBrowser: vi.fn(() => ({+ kill: vi.fn(),+ once: vi.fn(),+ })),+ readFile: vi.fn(),+ writeFile: vi.fn(),+ mkdtemp: vi.fn(+ async () => "/tmp/webstudio-browser"+ ) as unknown as ScreenshotDependencies["mkdtemp"],+ rm: vi.fn(async () => undefined),+ fetch: vi.fn(),+ createWebSocket: vi.fn(),+ captureBrowserScreenshot: vi.fn(async () => undefined),+ installCommand: vi.fn(async () => undefined),+ getuid: vi.fn(() => 1000),+ now: vi.fn(() => 123),+ ...overrides,+});++describe("resolveScreenshotBrowser", () => {+ test("uses explicit browser path before discovered browsers", async () => {+ const dependencies = createDependencies({+ which: vi.fn(async (command) =>+ command === "chromium" ? "/usr/bin/chromium" : undefined+ ),+ });++ await expect(+ resolveScreenshotBrowser(+ {+ browser: "auto",+ browserPath: "/custom/chromium",+ },+ dependencies+ )+ ).resolves.toEqual({+ path: "/custom/chromium",+ source: "option",+ browser: "chromium",+ });+ expect(dependencies.access).toHaveBeenCalledWith(+ "/custom/chromium",+ constants.X_OK+ );+ expect(dependencies.access).not.toHaveBeenCalledWith(+ "/usr/bin/chromium",+ constants.X_OK+ );+ });++ test("uses browser path from environment", async () => {+ const dependencies = createDependencies({+ env: { WEBSTUDIO_BROWSER_PATH: "/env/brave-browser" },+ });++ await expect(+ resolveScreenshotBrowser({ browser: "auto" }, dependencies)+ ).resolves.toEqual({+ path: "/env/brave-browser",+ source: "env",+ browser: "brave",+ });+ });++ test("prefers Chromium over Chrome and chrome-launcher fallback", async () => {+ const dependencies = createDependencies({+ which: vi.fn(async (command) => {+ if (command === "chromium") {+ return "/usr/local/bin/chromium";+ }+ if (command === "google-chrome") {+ return "/usr/local/bin/google-chrome";+ }+ return undefined;+ }),+ getChromeLauncherInstallations: vi.fn(() => [+ "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",+ ]),+ });++ await expect(+ resolveScreenshotBrowser({ browser: "auto" }, dependencies)+ ).resolves.toEqual({+ path: "/usr/local/bin/chromium",+ source: "path",+ browser: "chromium",+ });+ expect(dependencies.access).toHaveBeenCalledWith(+ "/usr/local/bin/chromium",+ constants.X_OK+ );+ });++ test("throws with checked paths when no browser is executable", async () => {+ const dependencies = createDependencies({+ access: vi.fn(async () => {+ throw new Error("missing");+ }),+ which: vi.fn(async (command) =>+ command === "chromium" ? "/usr/bin/chromium" : undefined+ ),+ getChromeLauncherInstallations: vi.fn(() => ["/opt/google/chrome"]),+ });++ await expect(+ resolveScreenshotBrowser({ browser: "auto" }, dependencies)+ ).rejects.toMatchObject({+ checked: expect.arrayContaining([+ "/usr/bin/chromium",+ "/opt/google/chrome",+ ]),+ });+ });+});++describe("OCR installation", () => {+ test("does not install Tesseract when already available", async () => {+ const dependencies = createDependencies({+ which: vi.fn(async (command) =>+ command === "tesseract" ? "/usr/bin/tesseract" : undefined+ ),+ });++ await expect(installTesseractForOcr(dependencies)).resolves.toEqual({+ installed: false,+ alreadyAvailable: true,+ command: undefined,+ tesseractPath: "/usr/bin/tesseract",+ installUrl: tesseractInstallUrl,+ warnings: [],+ });+ expect(dependencies.installCommand).not.toHaveBeenCalled();+ });++ test("installs Tesseract and verifies availability", async () => {+ let installed = false;+ const dependencies = createDependencies({+ which: vi.fn(async (command) => {+ if (command === "apt" || command === "sudo") {+ return `/usr/bin/${command}`;+ }+ if (command === "tesseract" && installed) {+ return "/usr/bin/tesseract";+ }+ return undefined;+ }),+ installCommand: vi.fn(async () => {+ installed = true;+ }),+ });++ await expect(installTesseractForOcr(dependencies)).resolves.toEqual({+ installed: true,+ alreadyAvailable: false,+ command: "sudo apt install -y tesseract-ocr",+ tesseractPath: "/usr/bin/tesseract",+ installUrl: tesseractInstallUrl,+ warnings: [],+ });+ expect(dependencies.installCommand).toHaveBeenCalledWith("sudo", [+ "apt",+ "install",+ "-y",+ "tesseract-ocr",+ ]);+ });++ test("returns actionable result when Tesseract cannot be installed automatically", async () => {+ const dependencies = createDependencies({+ which: vi.fn(async () => undefined),+ });++ await expect(installTesseractForOcr(dependencies)).resolves.toEqual({+ installed: false,+ alreadyAvailable: false,+ command: undefined,+ tesseractPath: undefined,+ installUrl: tesseractInstallUrl,+ warnings: ["ocr_install_unavailable_on_this_system"],+ });+ });+});++test("formats actionable browser installation guidance", () => {+ expect(getNoBrowserFoundMessage(["/usr/bin/chromium"])).toContain(+ "No supported Chromium browser was found."+ );+ expect(getNoBrowserFoundMessage(["/usr/bin/chromium"])).toContain(+ "https://www.chromium.org/getting-involved/download-chromium/"+ );+ expect(getNoBrowserFoundMessage(["/usr/bin/chromium"])).toContain(+ "--browser-path"+ );+ expect(getNoBrowserFoundMessage(["/usr/bin/chromium"])).toContain(+ "WEBSTUDIO_BROWSER_PATH"+ );+});++describe("captureScreenshot", () => {+ test("captures with browser readiness defaults", async () => {+ const captureBrowserScreenshot = vi.fn(async () => undefined);+ const dependencies = createDependencies({+ which: vi.fn(async (command) =>+ command === "chromium" ? "/usr/bin/chromium" : undefined+ ),+ captureBrowserScreenshot,+ });++ await expect(+ captureScreenshot(+ {+ url: "https://example.com",+ width: 1440,+ height: 900,+ browser: "auto",+ },+ dependencies+ )+ ).resolves.toMatchObject({+ output: expect.stringContaining("webstudio-screenshot-123.png"),+ browser: { path: "/usr/bin/chromium", browser: "chromium" },+ viewport: { width: 1440, height: 900 },+ elapsedMs: 0,+ warnings: [],+ });+ expect(captureBrowserScreenshot).toHaveBeenCalledWith({+ browserPath: "/usr/bin/chromium",+ output: "/tmp/webstudio-screenshot-123.png",+ width: 1440,+ height: 900,+ url: "https://example.com",+ uid: 1000,+ waitUntil: "load",+ waitForSelector: undefined,+ waitForTimeout: 250,+ timeout: 30000,+ });+ expect(dependencies.mkdir).toHaveBeenCalledWith("/tmp", {+ recursive: true,+ });+ });++ test("passes explicit readiness options to browser capture", async () => {+ const captureBrowserScreenshot = vi.fn(async () => undefined);+ const dependencies = createDependencies({+ which: vi.fn(async (command) =>+ command === "chromium" ? "/usr/bin/chromium" : undefined+ ),+ captureBrowserScreenshot,+ });++ await captureScreenshot(+ {+ url: "https://example.com",+ width: 1440,+ height: 900,+ browser: "auto",+ waitUntil: "networkidle",+ waitForSelector: "#ready",+ waitForTimeout: 500,+ timeout: 10_000,+ },+ dependencies+ );++ expect(captureBrowserScreenshot).toHaveBeenCalledWith(+ expect.objectContaining({+ waitUntil: "networkidle",+ waitForSelector: "#ready",+ waitForTimeout: 500,+ timeout: 10_000,+ })+ );+ });++ test("creates the output directory before launching the browser", async () => {+ const mkdir = vi.fn(async () => undefined);+ const dependencies = createDependencies({+ which: vi.fn(async (command) =>+ command === "chromium" ? "/usr/bin/chromium" : undefined+ ),+ mkdir,+ });++ await captureScreenshot(+ {+ url: "https://example.com",+ output: "nested/current.png",+ width: 1440,+ height: 900,+ browser: "auto",+ },+ dependencies+ );++ expect(mkdir).toHaveBeenCalledWith(expect.stringContaining("nested"), {+ recursive: true,+ });+ });+});++describe("browser installation", () => {+ test("does not offer install in json, mcp, ci, or non-interactive contexts", () => {+ expect(+ shouldOfferBrowserInstall({+ isInteractive: true,+ isJson: true,+ isMcp: false,+ env: {},+ })+ ).toBe(false);+ expect(+ shouldOfferBrowserInstall({+ isInteractive: true,+ isJson: false,+ isMcp: true,+ env: {},+ })+ ).toBe(false);+ expect(+ shouldOfferBrowserInstall({+ isInteractive: true,+ isJson: false,+ isMcp: false,+ env: { CI: "true" },+ })+ ).toBe(false);+ expect(+ shouldOfferBrowserInstall({+ isInteractive: false,+ isJson: false,+ isMcp: false,+ env: {},+ })+ ).toBe(false);+ });++ test("returns platform install command for Chromium", async () => {+ const dependencies = createDependencies({+ which: vi.fn(async (command) =>+ command === "apt" || command === "sudo"+ ? `/usr/bin/${command}`+ : undefined+ ),+ });++ await expect(getChromiumInstallCommand(dependencies)).resolves.toEqual({+ command: "sudo",+ args: ["apt", "install", "-y", "chromium"],+ label: "sudo apt install -y chromium",+ });+ });++ test("does not offer Linux install command without sudo for non-root users", async () => {+ const dependencies = createDependencies({+ which: vi.fn(async (command) =>+ command === "apt" ? "/usr/bin/apt" : undefined+ ),+ });++ await expect(getChromiumInstallCommand(dependencies)).resolves.toBe(+ undefined+ );+ });++ test("uses root apt command without sudo", async () => {+ const dependencies = createDependencies({+ getuid: vi.fn(() => 0),+ which: vi.fn(async (command) =>+ command === "apt" ? "/usr/bin/apt" : undefined+ ),+ });++ await expect(getChromiumInstallCommand(dependencies)).resolves.toEqual({+ command: "apt",+ args: ["install", "-y", "chromium"],+ label: "apt install -y chromium",+ });+ });++ test("uses apt-get when apt is unavailable", async () => {+ const dependencies = createDependencies({+ which: vi.fn(async (command) => {+ if (command === "sudo") {+ return "/usr/bin/sudo";+ }+ if (command === "apt-get") {+ return "/usr/bin/apt-get";+ }+ return undefined;+ }),+ });++ await expect(getChromiumInstallCommand(dependencies)).resolves.toEqual({+ command: "sudo",+ args: ["apt-get", "install", "-y", "chromium"],+ label: "sudo apt-get install -y chromium",+ });+ });++ test("uses Homebrew install command on macOS", async () => {+ const dependencies = createDependencies({+ platform: "darwin",+ which: vi.fn(async (command) =>+ command === "brew" ? "/opt/homebrew/bin/brew" : undefined+ ),+ });++ await expect(getChromiumInstallCommand(dependencies)).resolves.toEqual({+ command: "brew",+ args: ["install", "--cask", "chromium"],+ label: "brew install --cask chromium",+ });+ });++ test("installs Chromium after confirmation and retries capture", async () => {+ let installed = false;+ const installCommand = vi.fn(async () => {+ installed = true;+ });+ const captureBrowserScreenshot = vi.fn(async () => undefined);+ const dependencies = createDependencies({+ access: vi.fn(async (path) => {+ if (path.startsWith("/usr/bin/") && installed === false) {+ throw new Error("missing");+ }+ }),+ which: vi.fn(async (command) => {+ if (command === "apt") {+ return "/usr/bin/apt";+ }+ if (command === "sudo") {+ return "/usr/bin/sudo";+ }+ if (command === "chromium") {+ return "/usr/bin/chromium";+ }+ return undefined;+ }),+ captureBrowserScreenshot,+ installCommand,+ });+ const confirmInstall = vi.fn(async () => true);++ await expect(+ captureScreenshotWithBrowserInstall(+ {+ url: "https://example.com",+ width: 1440,+ height: 900,+ browser: "auto",+ isJson: false,+ isMcp: false,+ isInteractive: true,+ confirmInstall,+ },+ dependencies+ )+ ).resolves.toMatchObject({+ browser: { path: "/usr/bin/chromium" },+ });+ expect(confirmInstall).toHaveBeenCalledOnce();+ expect(installCommand).toHaveBeenCalledWith("sudo", [+ "apt",+ "install",+ "-y",+ "chromium",+ ]);+ expect(captureBrowserScreenshot).toHaveBeenCalledWith(+ expect.objectContaining({+ browserPath: "/usr/bin/chromium",+ url: "https://example.com",+ })+ );+ });++ test("keeps original browser-not-found error when install is declined", async () => {+ const dependencies = createDependencies({+ access: vi.fn(async () => {+ throw new Error("missing");+ }),+ which: vi.fn(async (command) => {+ if (command === "apt") {+ return "/usr/bin/apt";+ }+ if (command === "sudo") {+ return "/usr/bin/sudo";+ }+ return undefined;+ }),+ });++ await expect(+ captureScreenshotWithBrowserInstall(+ {+ url: "https://example.com",+ width: 1440,+ height: 900,+ browser: "auto",+ isJson: false,+ isMcp: false,+ isInteractive: true,+ confirmInstall: vi.fn(async () => false),+ },+ dependencies+ )+ ).rejects.toBeInstanceOf(BrowserNotFoundError);+ expect(dependencies.installCommand).not.toHaveBeenCalled();+ });++ test("propagates install confirmation errors", async () => {+ const expectedError = new Error("cancelled");+ const dependencies = createDependencies({+ access: vi.fn(async () => {+ throw new Error("missing");+ }),+ which: vi.fn(async (command) => {+ if (command === "apt") {+ return "/usr/bin/apt";+ }+ if (command === "sudo") {+ return "/usr/bin/sudo";+ }+ return undefined;+ }),+ });++ await expect(+ captureScreenshotWithBrowserInstall(+ {+ url: "https://example.com",+ width: 1440,+ height: 900,+ browser: "auto",+ isJson: false,+ isMcp: false,+ isInteractive: true,+ confirmInstall: vi.fn(async () => {+ throw expectedError;+ }),+ },+ dependencies+ )+ ).rejects.toBe(expectedError);+ });++ test("rethrows browser not found when install is not allowed", async () => {+ const dependencies = createDependencies({+ access: vi.fn(async () => {+ throw new Error("missing");+ }),+ });++ await expect(+ captureScreenshotWithBrowserInstall(+ {+ url: "https://example.com",+ width: 1440,+ height: 900,+ browser: "auto",+ isJson: true,+ isMcp: false,+ isInteractive: true,+ confirmInstall: vi.fn(async () => true),+ },+ dependencies+ )+ ).rejects.toBeInstanceOf(BrowserNotFoundError);+ });++ test("reports unavailable browser auto-install separately", async () => {+ const dependencies = createDependencies({+ access: vi.fn(async () => {+ throw new Error("missing");+ }),+ which: vi.fn(async () => undefined),+ });++ await expect(+ captureScreenshotWithBrowserInstall(+ {+ url: "https://example.com",+ width: 1440,+ height: 900,+ browser: "auto",+ isJson: false,+ isMcp: false,+ isInteractive: true,+ confirmInstall: vi.fn(async () => true),+ },+ dependencies+ )+ ).rejects.toBeInstanceOf(BrowserInstallUnavailableError);+ expect(dependencies.installCommand).not.toHaveBeenCalled();+ });++ test("rethrows browser not found when install succeeds but rediscovery fails", async () => {+ const dependencies = createDependencies({+ access: vi.fn(async () => {+ throw new Error("missing");+ }),+ which: vi.fn(async (command) => {+ if (command === "apt") {+ return "/usr/bin/apt";+ }+ if (command === "sudo") {+ return "/usr/bin/sudo";+ }+ if (command === "chromium") {+ return "/usr/bin/chromium";+ }+ return undefined;+ }),+ });++ await expect(+ captureScreenshotWithBrowserInstall(+ {+ url: "https://example.com",+ width: 1440,+ height: 900,+ browser: "auto",+ isJson: false,+ isMcp: false,+ isInteractive: true,+ confirmInstall: vi.fn(async () => true),+ },+ dependencies+ )+ ).rejects.toBeInstanceOf(BrowserNotFoundError);+ expect(dependencies.installCommand).toHaveBeenCalledWith("sudo", [+ "apt",+ "install",+ "-y",+ "chromium",+ ]);+ });+});diff --git a/packages/cli/src/screenshot.ts b/packages/cli/src/screenshot.tsnew file mode 100644index 0000000000..85d50ecc2b--- /dev/null+++ b/packages/cli/src/screenshot.ts@@ -0,0 +1,592 @@+import { constants } from "node:fs";+import { access, mkdir } from "node:fs/promises";+import { tmpdir } from "node:os";+import { dirname, resolve } from "node:path";+import { execFile, spawn } from "node:child_process";+import { promisify } from "node:util";+import { Launcher } from "chrome-launcher";+import {+ defaultScreenshotTimeout,+ defaultScreenshotWaitForTimeout,+ defaultScreenshotWaitUntil,+ type ScreenshotBrowser,+ type ScreenshotWaitUntil,+} from "@webstudio-is/project-build/visual/screenshot-browser";+import {+ captureBrowserScreenshot,+ defaultBrowserScreenshotDependencies,+ type BrowserScreenshotDependencies,+ type BrowserScreenshotOptions,+} from "./screenshot-browser-cdp";++const execFileAsync = promisify(execFile);++export type BrowserCandidate = {+ path: string;+ source: "option" | "env" | "path" | "platform" | "chrome-launcher";+ browser: Exclude<ScreenshotBrowser, "auto">;+};++export class BrowserNotFoundError extends Error {+ readonly checked: readonly string[];++ constructor(checked: readonly string[]) {+ super("No supported Chromium browser was found.");+ this.name = "BrowserNotFoundError";+ this.checked = checked;+ }+}++export class BrowserInstallUnavailableError extends Error {+ constructor() {+ super("Chromium cannot be installed automatically on this system.");+ this.name = "BrowserInstallUnavailableError";+ }+}++export type ScreenshotDependencies = {+ env: NodeJS.ProcessEnv;+ platform: NodeJS.Platform;+ access: (path: string, mode?: number) => Promise<void>;+ mkdir: (path: string, options: { recursive: true }) => Promise<unknown>;+ which: (command: string) => Promise<string | undefined>;+ getChromeLauncherInstallations: () => string[];+} & BrowserScreenshotDependencies & {+ captureBrowserScreenshot?: (+ options: BrowserScreenshotOptions+ ) => Promise<void>;+ installCommand: (file: string, args: readonly string[]) => Promise<void>;+ getuid: () => number | undefined;+ now: () => number;+ };++export const defaultScreenshotDependencies: ScreenshotDependencies = {+ env: process.env,+ platform: process.platform,+ access,+ mkdir,+ async which(command) {+ const lookup = process.platform === "win32" ? "where" : "which";+ try {+ const { stdout } = await execFileAsync(lookup, [command]);+ return stdout.split(/\r?\n/).find((path) => path.length > 0);+ } catch {+ return undefined;+ }+ },+ getChromeLauncherInstallations() {+ try {+ return Launcher.getInstallations();+ } catch {+ return [];+ }+ },+ ...defaultBrowserScreenshotDependencies,+ async installCommand(file, args) {+ await new Promise<void>((resolve, reject) => {+ const child = spawn(file, [...args], { stdio: "inherit" });+ child.once("error", reject);+ child.once("exit", (code) => {+ if (code === 0) {+ resolve();+ return;+ }+ reject(new Error(`${file} ${args.join(" ")} exited with code ${code}`));+ });+ });+ },+ getuid: () => process.getuid?.(),+ now: () => Date.now(),+};++export const chromiumDownloadUrl =+ "https://www.chromium.org/getting-involved/download-chromium/";++export const chromeDownloadUrl = "https://www.google.com/chrome/";++export const tesseractInstallUrl =+ "https://tesseract-ocr.github.io/tessdoc/Installation.html";++const pathCommandCandidates = [+ { command: "chromium", browser: "chromium" },+ { command: "chromium-browser", browser: "chromium" },+ { command: "google-chrome", browser: "chrome" },+ { command: "google-chrome-stable", browser: "chrome" },+ { command: "msedge", browser: "edge" },+ { command: "microsoft-edge", browser: "edge" },+ { command: "brave-browser", browser: "brave" },+ { command: "brave", browser: "brave" },+] as const;++const platformPathCandidates: Record<+ NodeJS.Platform,+ readonly BrowserCandidate[]+> = {+ aix: [],+ android: [],+ darwin: [+ {+ path: "/Applications/Chromium.app/Contents/MacOS/Chromium",+ source: "platform",+ browser: "chromium",+ },+ {+ path: "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",+ source: "platform",+ browser: "chrome",+ },+ {+ path: "/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge",+ source: "platform",+ browser: "edge",+ },+ {+ path: "/Applications/Brave Browser.app/Contents/MacOS/Brave Browser",+ source: "platform",+ browser: "brave",+ },+ ],+ freebsd: [],+ haiku: [],+ linux: [+ { path: "/usr/bin/chromium", source: "platform", browser: "chromium" },+ {+ path: "/usr/bin/chromium-browser",+ source: "platform",+ browser: "chromium",+ },+ { path: "/usr/bin/google-chrome", source: "platform", browser: "chrome" },+ {+ path: "/usr/bin/google-chrome-stable",+ source: "platform",+ browser: "chrome",+ },+ { path: "/usr/bin/msedge", source: "platform", browser: "edge" },+ {+ path: "/usr/bin/microsoft-edge",+ source: "platform",+ browser: "edge",+ },+ { path: "/usr/bin/brave-browser", source: "platform", browser: "brave" },+ ],+ openbsd: [],+ sunos: [],+ win32: [+ {+ path: "C:\\Program Files\\Chromium\\Application\\chrome.exe",+ source: "platform",+ browser: "chromium",+ },+ {+ path: "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe",+ source: "platform",+ browser: "chrome",+ },+ {+ path: "C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe",+ source: "platform",+ browser: "edge",+ },+ {+ path: "C:\\Program Files\\BraveSoftware\\Brave-Browser\\Application\\brave.exe",+ source: "platform",+ browser: "brave",+ },+ ],+ cygwin: [],+ netbsd: [],+};++const browserPreference: Record<Exclude<ScreenshotBrowser, "auto">, number> = {+ chromium: 0,+ chrome: 1,+ edge: 2,+ brave: 3,+};++const inferBrowser = (path: string): Exclude<ScreenshotBrowser, "auto"> => {+ const normalized = path.toLowerCase();+ if (normalized.includes("chromium")) {+ return "chromium";+ }+ if (normalized.includes("edge") || normalized.includes("msedge")) {+ return "edge";+ }+ if (normalized.includes("brave")) {+ return "brave";+ }+ return "chrome";+};++const matchesBrowser = (+ candidate: BrowserCandidate,+ browser: ScreenshotBrowser+) => browser === "auto" || candidate.browser === browser;++const isExecutable = async (+ path: string,+ dependencies: ScreenshotDependencies+) => {+ try {+ await dependencies.access(path, constants.X_OK);+ return true;+ } catch {+ return false;+ }+};++const uniqueCandidates = (candidates: readonly BrowserCandidate[]) => {+ const seen = new Set<string>();+ return candidates.filter((candidate) => {+ if (seen.has(candidate.path)) {+ return false;+ }+ seen.add(candidate.path);+ return true;+ });+};++export const resolveScreenshotBrowser = async (+ options: {+ browser: ScreenshotBrowser;+ browserPath?: string;+ },+ dependencies = defaultScreenshotDependencies+): Promise<BrowserCandidate> => {+ const checked: string[] = [];+ const candidates: BrowserCandidate[] = [];++ if (options.browserPath !== undefined) {+ candidates.push({+ path: options.browserPath,+ source: "option",+ browser:+ options.browser === "auto"+ ? inferBrowser(options.browserPath)+ : options.browser,+ });+ }++ const envBrowserPath = dependencies.env.WEBSTUDIO_BROWSER_PATH;+ if (envBrowserPath !== undefined && envBrowserPath.length > 0) {+ candidates.push({+ path: envBrowserPath,+ source: "env",+ browser:+ options.browser === "auto"+ ? inferBrowser(envBrowserPath)+ : options.browser,+ });+ }++ for (const { command, browser } of pathCommandCandidates) {+ if (options.browser !== "auto" && options.browser !== browser) {+ continue;+ }+ const path = await dependencies.which(command);+ if (path !== undefined) {+ candidates.push({ path, source: "path", browser });+ }+ }++ candidates.push(+ ...(platformPathCandidates[dependencies.platform] ?? []).filter(+ (candidate) => matchesBrowser(candidate, options.browser)+ )+ );++ candidates.push(+ ...dependencies+ .getChromeLauncherInstallations()+ .map((path) => ({+ path,+ source: "chrome-launcher" as const,+ browser: inferBrowser(path),+ }))+ .filter((candidate) => matchesBrowser(candidate, options.browser))+ .sort(+ (left, right) =>+ browserPreference[left.browser] - browserPreference[right.browser]+ )+ );++ for (const candidate of uniqueCandidates(candidates)) {+ checked.push(candidate.path);+ if (await isExecutable(candidate.path, dependencies)) {+ return candidate;+ }+ }++ throw new BrowserNotFoundError(checked);+};++export const getNoBrowserFoundMessage = (checked: readonly string[]) =>+ [+ "No supported Chromium browser was found.",+ "",+ "Install Chromium and try again:",+ `- Chromium: ${chromiumDownloadUrl}`,+ `- Google Chrome: ${chromeDownloadUrl}`,+ "",+ "Or pass an explicit browser binary:",+ "- webstudio screenshot <url> --browser-path /path/to/chromium",+ "- WEBSTUDIO_BROWSER_PATH=/path/to/chromium webstudio screenshot <url>",+ "",+ checked.length === 0+ ? "No browser paths were found to check."+ : `Checked paths:\n${checked.map((path) => `- ${path}`).join("\n")}`,+ ].join("\n");++type InstallCommand = {+ command: string;+ args: readonly string[];+ label: string;+};++export type ChromiumInstallCommand = InstallCommand;++const getHomebrewOrAptInstallCommand = async (+ {+ brewArgs,+ aptPackage,+ }: {+ brewArgs: readonly string[];+ aptPackage: string;+ },+ dependencies = defaultScreenshotDependencies+): Promise<InstallCommand | undefined> => {+ if (dependencies.platform === "darwin") {+ if ((await dependencies.which("brew")) !== undefined) {+ return {+ command: "brew",+ args: brewArgs,+ label: `brew ${brewArgs.join(" ")}`,+ };+ }+ return undefined;+ }++ if (dependencies.platform !== "linux") {+ return undefined;+ }++ const isRoot = dependencies.getuid() === 0;+ const sudo = isRoot ? undefined : await dependencies.which("sudo");+ if (isRoot === false && sudo === undefined) {+ return undefined;+ }++ const getLinuxCommand = (packageManager: "apt" | "apt-get") => {+ const command = isRoot ? packageManager : "sudo";+ const args = isRoot+ ? ["install", "-y", aptPackage]+ : [packageManager, "install", "-y", aptPackage];+ return {+ command,+ args,+ label: `${command} ${args.join(" ")}`,+ };+ };++ if ((await dependencies.which("apt")) !== undefined) {+ return getLinuxCommand("apt");+ }++ if ((await dependencies.which("apt-get")) !== undefined) {+ return getLinuxCommand("apt-get");+ }++ return undefined;+};++export const getChromiumInstallCommand = async (+ dependencies = defaultScreenshotDependencies+): Promise<ChromiumInstallCommand | undefined> => {+ return getHomebrewOrAptInstallCommand(+ {+ brewArgs: ["install", "--cask", "chromium"],+ aptPackage: "chromium",+ },+ dependencies+ );+};++const getTesseractInstallCommand = async (+ dependencies = defaultScreenshotDependencies+): Promise<InstallCommand | undefined> => {+ return getHomebrewOrAptInstallCommand(+ {+ brewArgs: ["install", "tesseract"],+ aptPackage: "tesseract-ocr",+ },+ dependencies+ );+};++export const installTesseractForOcr = async (+ dependencies = defaultScreenshotDependencies+) => {+ const existing = await dependencies.which("tesseract");+ if (existing !== undefined) {+ return {+ installed: false,+ alreadyAvailable: true,+ command: undefined,+ tesseractPath: existing,+ installUrl: tesseractInstallUrl,+ warnings: [] as string[],+ };+ }+ const installCommand = await getTesseractInstallCommand(dependencies);+ if (installCommand === undefined) {+ return {+ installed: false,+ alreadyAvailable: false,+ command: undefined,+ tesseractPath: undefined,+ installUrl: tesseractInstallUrl,+ warnings: ["ocr_install_unavailable_on_this_system"],+ };+ }+ await dependencies.installCommand(+ installCommand.command,+ installCommand.args+ );+ const tesseractPath = await dependencies.which("tesseract");+ return {+ installed: true,+ alreadyAvailable: false,+ command: installCommand.label,+ tesseractPath,+ installUrl: tesseractInstallUrl,+ warnings:+ tesseractPath === undefined+ ? ["tesseract_not_found_after_install"]+ : ([] as string[]),+ };+};++export const shouldOfferBrowserInstall = ({+ isInteractive,+ isJson,+ isMcp,+ env,+}: {+ isInteractive: boolean;+ isJson: boolean;+ isMcp: boolean;+ env: NodeJS.ProcessEnv;+}) =>+ isInteractive === true &&+ isJson === false &&+ isMcp === false &&+ env.CI !== "true";++export const getScreenshotOutputPath = ({+ output,+ now,+}: {+ output?: string;+ now: number;+}) => resolve(output ?? `${tmpdir()}/webstudio-screenshot-${now}.png`);++export const captureScreenshot = async (+ options: {+ url: string;+ output?: string;+ width: number;+ height: number;+ browser: ScreenshotBrowser;+ browserPath?: string;+ waitUntil?: ScreenshotWaitUntil;+ waitForSelector?: string;+ waitForTimeout?: number;+ timeout?: number;+ },+ dependencies = defaultScreenshotDependencies+) => {+ const startedAt = dependencies.now();+ const browser = await resolveScreenshotBrowser(options, dependencies);+ const output = getScreenshotOutputPath({+ output: options.output,+ now: startedAt,+ });+ await dependencies.mkdir(dirname(output), { recursive: true });+ const browserScreenshotOptions = {+ browserPath: browser.path,+ output,+ width: options.width,+ height: options.height,+ url: options.url,+ uid: dependencies.getuid(),+ waitUntil: options.waitUntil ?? defaultScreenshotWaitUntil,+ waitForSelector: options.waitForSelector,+ waitForTimeout: options.waitForTimeout ?? defaultScreenshotWaitForTimeout,+ timeout: options.timeout ?? defaultScreenshotTimeout,+ };+ if (dependencies.captureBrowserScreenshot !== undefined) {+ await dependencies.captureBrowserScreenshot(browserScreenshotOptions);+ } else {+ await captureBrowserScreenshot(browserScreenshotOptions, dependencies);+ }+ return {+ output,+ browser,+ viewport: {+ width: options.width,+ height: options.height,+ },+ elapsedMs: dependencies.now() - startedAt,+ warnings: [] as string[],+ };+};++export const captureScreenshotWithBrowserInstall = async (+ options: {+ url: string;+ output?: string;+ width: number;+ height: number;+ browser: ScreenshotBrowser;+ browserPath?: string;+ waitUntil?: ScreenshotWaitUntil;+ waitForSelector?: string;+ waitForTimeout?: number;+ timeout?: number;+ isJson: boolean;+ isMcp: boolean;+ isInteractive: boolean;+ confirmInstall: (command: ChromiumInstallCommand) => Promise<boolean>;+ },+ dependencies = defaultScreenshotDependencies+) => {+ try {+ return await captureScreenshot(options, dependencies);+ } catch (error) {+ if (error instanceof BrowserNotFoundError === false) {+ throw error;+ }+ if (+ shouldOfferBrowserInstall({+ isInteractive: options.isInteractive,+ isJson: options.isJson,+ isMcp: options.isMcp,+ env: dependencies.env,+ }) === false+ ) {+ throw error;+ }+ const installCommand = await getChromiumInstallCommand(dependencies);+ if (installCommand === undefined) {+ throw new BrowserInstallUnavailableError();+ }+ if ((await options.confirmInstall(installCommand)) === false) {+ throw error;+ }+ await dependencies.installCommand(+ installCommand.command,+ installCommand.args+ );+ return captureScreenshot(options, dependencies);+ }+};diff --git a/packages/cli/templates/saas-helpers/package.json b/packages/cli/templates/saas-helpers/package.jsonindex 1e57b5955b..7586073411 100644--- a/packages/cli/templates/saas-helpers/package.json+++ b/packages/cli/templates/saas-helpers/package.json@@ -2,8 +2,5 @@"dependencies": {"worktop": "0.8.0-next.18","zod": "^3.24.2"- },- "devDependencies": {- "fast-glob": "^3.3.2"}}diff --git a/packages/cli/templates/saas-helpers/vite.config.ts b/packages/cli/templates/saas-helpers/vite.config.tsindex fa01ca299d..938c8bec6f 100644--- a/packages/cli/templates/saas-helpers/vite.config.ts+++ b/packages/cli/templates/saas-helpers/vite.config.ts@@ -4,20 +4,21 @@ import {} from "@remix-run/dev";import { defineConfig } from "vite";-import { existsSync } from "node:fs";-// @ts-ignore-import path from "node:path";-// @ts-ignore-import fg from "fast-glob";+import { existsSync, readdirSync } from "node:fs";-const rootDir = ["..", "../..", "../../.."]- .map((dir) => path.join(__dirname, dir))- .find((dir) => existsSync(path.join(dir, ".git")));+const rootDir = ["..", "../..", "../../.."].find((dir) =>+ existsSync(`${dir}/.git`)+);const hasPrivateFolders =- fg.sync([path.join(rootDir ?? "", "packages/*/private-src/*")], {- ignore: ["**/node_modules/**"],- }).length > 0;+ rootDir !== undefined &&+ existsSync(`${rootDir}/packages`) &&+ readdirSync(`${rootDir}/packages`, { withFileTypes: true }).some((entry) => {+ return (+ entry.isDirectory() &&+ existsSync(`${rootDir}/packages/${entry.name}/private-src`)+ );+ });const conditions = hasPrivateFolders? ["webstudio-private", "webstudio"]diff --git a/packages/cli/tsconfig.json b/packages/cli/tsconfig.jsonindex a4c264384a..c80b0d16f1 100644--- a/packages/cli/tsconfig.json+++ b/packages/cli/tsconfig.json@@ -1,6 +1,6 @@{"extends": "@webstudio-is/tsconfig/base.json",- "include": ["**/*.ts", "**/*.tsx", "**/*.mjs"],+ "include": ["**/*.ts", "**/*.tsx", "**/*.mjs", "../../@types/**/*.d.ts"],"compilerOptions": {"lib": ["DOM", "DOM.Iterable", "ESNext"],"types": ["vite/client", "@webstudio-is/react-sdk/placeholder"],diff --git a/packages/cli/vite.config.ts b/packages/cli/vite.config.tsindex 6533ee61dc..4caa161417 100644--- a/packages/cli/vite.config.ts+++ b/packages/cli/vite.config.ts@@ -5,36 +5,23 @@ import {} from "vite";import pkg from "./package.json";-const isExternal = (id: string, importer: string | undefined) => {- if (id.startsWith("@webstudio-is/")) {- return false;- }- if (id.startsWith("node:")) {- return true;- }+const externalDependencies = new Set(+ Object.keys(pkg.dependencies).filter((name) => {+ return name.startsWith("@webstudio-is/") === false;+ })+);++const getPackageName = (id: string) => {if (id.startsWith("@")) {- const packageName = id.split("/").slice(0, 2).join("/");- if (packageName in pkg.dependencies === false) {- throw Error(- `${packageName} imported from ${importer} is not found in direct dependencies`- );- }- return true;+ return id.split("/").slice(0, 2).join("/");}- if (id.includes(".") === false) {- const [packageName] = id.split("/");- if (packageName in pkg.dependencies === false) {- throw Error(- `${packageName} imported from ${importer} is not found in direct dependencies`- );- }- return true;- }- return false;+ return id.split("/")[0];};+const isExternal = (id: string) =>+ id.startsWith("node:") || externalDependencies.has(getPackageName(id));+export default defineConfig({- // resolve webstudio condition in testsresolve: {conditions: ["webstudio", ...defaultClientConditions],},diff --git a/packages/design-system/vitest.config.ts b/packages/design-system/vitest.config.tsindex 859af910b9..a6784d6647 100644--- a/packages/design-system/vitest.config.ts+++ b/packages/design-system/vitest.config.ts@@ -4,7 +4,6 @@ export default defineConfig({resolve: {conditions: ["webstudio", "browser", "development|production"],},- // resolve webstudio condition in testsssr: {resolve: {conditions: ["webstudio", "node", "development|production"],diff --git a/packages/domain/src/index.server.ts b/packages/domain/src/index.server.tsindex de6f4b1d04..8bfd32d430 100644--- a/packages/domain/src/index.server.ts+++ b/packages/domain/src/index.server.ts@@ -1,2 +1,3 @@export * from "./trpc";export * from "./db";+export * from "./project-domain-api.server";diff --git a/packages/domain/src/project-domain-api.server.test.ts b/packages/domain/src/project-domain-api.server.test.tsnew file mode 100644index 0000000000..7abcbb34d2--- /dev/null+++ b/packages/domain/src/project-domain-api.server.test.ts@@ -0,0 +1,346 @@+import { expect, test, vi } from "vitest";+import {+ createTestServer,+ db,+ empty,+ json,+ testContext,+} from "@webstudio-is/postgrest/testing";+import { http } from "msw";+import type { AppContext } from "@webstudio-is/trpc-interface/index.server";+import {+ getProjectPublishJob,+ listProjectPublishes,+ publishProject,+ publishStaticProject,+ unpublishProjectDomains,+} from "./project-domain-api.server";++const server = createTestServer();+const context = testContext as unknown as AppContext;+const postgrestUrl = "http://test-postgrest";++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 loadedProject = {+ id: "project-1",+ userId: "user-1",+ title: "Project One",+ domain: "project.wstd.io",+ createdAt: "2024-01-01T00:00:00.000Z",+ isDeleted: false,+ marketplaceApprovalStatus: "UNLISTED" as const,+ previewImageAssetId: null,+ tags: [],+ workspaceId: null,+ previewImageAsset: null,+ latestBuildVirtual: null,+ latestStaticBuild: null,+ domainsVirtual: [+ {+ id: "project-domain-1",+ projectId: "project-1",+ domainId: "domain-1",+ domain: "example.com",+ status: "ACTIVE" as const,+ verified: true,+ domainTxtRecord: null,+ expectedTxtRecord: "webstudio=domain-1",+ cname: "proxy.webstudio.is",+ error: null,+ createdAt: "2024-01-01T00:00:00.000Z",+ updatedAt: "2024-01-02T00:00:00.000Z",+ latestBuildVirtual: null,+ },+ ],+};++const projectResponse = {+ ...loadedProject,+ latestStaticBuild: [],+};++const projectHandler = db.get("Project", ({ request }) => {+ const url = new URL(request.url);+ if (url.searchParams.has("userId")) {+ return json({ id: "project-1" });+ }+ return json(projectResponse);+});++const createPublishContext = (+ publish = vi.fn().mockResolvedValue({ success: true })+) =>+ ({+ ...testContext,+ authorization: { type: "user", userId: "user-1" },+ deployment: {+ deploymentTrpc: {+ publish: {+ mutate: publish,+ },+ unpublish: {+ mutate: vi.fn().mockResolvedValue({ success: true }),+ },+ },+ env: {+ BUILDER_ORIGIN: "https://apps.webstudio.is",+ GITHUB_REF_NAME: "main",+ GITHUB_SHA: "sha-1",+ PUBLISHER_HOST: "wstd.io",+ },+ },+ }) as unknown as AppContext;++const productionBuildHandler = (+ onRequest: (body: { project_id: string; deployment: string }) => void+) =>+ http.post(+ `${postgrestUrl}/rpc/create_production_build`,+ async ({ request }) => {+ onRequest(+ (await request.json()) as { project_id: string; deployment: string }+ );+ return json("build-prod");+ }+ );++test("publishes saas project through shared domain service", async () => {+ const publish = vi.fn().mockResolvedValue({ success: true });+ let productionBuildRequest:+ | { project_id: string; deployment: string }+ | undefined;+ server.use(+ projectHandler,+ productionBuildHandler((body) => {+ productionBuildRequest = body;+ })+ );++ await expect(+ publishProject(+ { project: loadedProject, domains: ["project.wstd.io", "example.com"] },+ createPublishContext(publish)+ )+ ).resolves.toMatchObject({+ build: { id: "build-prod" },+ deploymentNotImplemented: false,+ });++ expect(productionBuildRequest?.project_id).toBe("project-1");+ expect(JSON.parse(productionBuildRequest?.deployment ?? "")).toEqual({+ destination: "saas",+ domains: ["project.wstd.io", "example.com"],+ assetsDomain: "project.wstd.io",+ excludeWstdDomainFromSearch: true,+ });+ expect(publish).toHaveBeenCalledWith({+ builderOrigin: "https://apps.webstudio.is",+ githubSha: "sha-1",+ buildId: "build-prod",+ branchName: "main",+ destination: "saas",+ logProjectName: "Project One - project-1",+ });+});++test("reports local-dev publish when deployment publisher is unavailable", async () => {+ server.use(+ projectHandler,+ productionBuildHandler(() => {})+ );++ await expect(+ publishProject(+ { project: loadedProject, domains: ["project.wstd.io"] },+ createPublishContext(+ vi.fn().mockResolvedValue({ success: false, error: "NOT_IMPLEMENTED" })+ )+ )+ ).resolves.toMatchObject({+ build: { id: "build-prod" },+ deploymentNotImplemented: true,+ });+});++test("publishes static project through shared domain service", async () => {+ const publish = vi.fn().mockResolvedValue({ success: true });+ let productionBuildRequest:+ | { project_id: string; deployment: string }+ | undefined;+ server.use(+ projectHandler,+ productionBuildHandler((body) => {+ productionBuildRequest = body;+ })+ );++ await expect(+ publishStaticProject(+ {+ projectId: "project-1",+ name: "project.zip",+ templates: [],+ },+ createPublishContext(publish)+ )+ ).resolves.toMatchObject({+ success: true,+ name: "project.zip",+ build: { id: "build-prod" },+ });++ expect(JSON.parse(productionBuildRequest?.deployment ?? "")).toEqual({+ destination: "static",+ name: "project.zip",+ assetsDomain: "project.wstd.io",+ templates: [],+ });+ expect(publish).toHaveBeenCalledWith({+ builderOrigin: "https://apps.webstudio.is",+ githubSha: "sha-1",+ buildId: "build-prod",+ branchName: "main",+ destination: "static",+ logProjectName: "Project One - project-1",+ });+});++test("clears publish records even when deployment unpublish fails", async () => {+ let deletedBuildId: string | undefined;+ server.use(+ ownershipHandler,+ db.get("Build", () =>+ json([+ {+ id: "build-prod",+ deployment: JSON.stringify({+ destination: "saas",+ domains: ["example"],+ }),+ },+ ])+ ),+ db.delete("Build", ({ request }) => {+ const url = new URL(request.url);+ deletedBuildId = url.searchParams.get("id")?.replace("eq.", "");+ return empty({ status: 204 });+ })+ );+ const context = {+ ...testContext,+ authorization: { type: "user", userId: "user-1" },+ deployment: {+ deploymentTrpc: {+ unpublish: {+ mutate: vi+ .fn()+ .mockResolvedValue({ success: false, error: "Cloudflare failed" }),+ },+ },+ env: { PUBLISHER_HOST: "wstd.io" },+ },+ } as unknown as AppContext;++ await expect(+ unpublishProjectDomains(+ {+ projectId: "project-1",+ domains: ["example.wstd.io"],+ },+ context+ )+ ).rejects.toThrow("Failed to unpublish example.wstd.io: Cloudflare failed");++ expect(deletedBuildId).toBe("build-prod");+});++test("lists non-static project publishes", async () => {+ server.use(+ db.get("Build", () =>+ json([+ {+ id: "build-prod",+ version: 3,+ createdAt: "2024-01-03T00:00:00.000Z",+ deployment: JSON.stringify({+ destination: "saas",+ domains: ["example.com", "www.example.com"],+ }),+ },+ {+ id: "build-static",+ version: 2,+ createdAt: "2024-01-02T00:00:00.000Z",+ deployment: JSON.stringify({+ destination: "static",+ name: "project.zip",+ }),+ },+ {+ id: "build-removed",+ version: 1,+ createdAt: "2024-01-01T00:00:00.000Z",+ deployment: null,+ },+ ])+ )+ );++ await expect(listProjectPublishes("project-1", context)).resolves.toEqual({+ publishes: [+ {+ id: "build-prod",+ jobId: "build-prod",+ version: 3,+ target: "production",+ domains: ["example.com", "www.example.com"],+ createdAt: "2024-01-03T00:00:00.000Z",+ },+ ],+ });+});++test("returns publish job status from deployment record", async () => {+ server.use(+ db.get("Build", () =>+ json({+ id: "build-prod",+ version: 3,+ createdAt: "2024-01-03T00:00:00.000Z",+ deployment: JSON.stringify({+ destination: "saas",+ domains: ["example.com"],+ }),+ })+ )+ );++ await expect(+ getProjectPublishJob(+ { projectId: "project-1", jobId: "build-prod" },+ context+ )+ ).resolves.toEqual({+ id: "build-prod",+ version: 3,+ status: "success",+ domains: ["example.com"],+ createdAt: "2024-01-03T00:00:00.000Z",+ completedAt: "2024-01-03T00:00:00.000Z",+ });+});++test("returns undefined when publish job is missing", async () => {+ server.use(db.get("Build", () => empty({ status: 204 })));++ await expect(+ getProjectPublishJob({ projectId: "project-1", jobId: "missing" }, context)+ ).resolves.toBeUndefined();+});diff --git a/packages/domain/src/project-domain-api.server.ts b/packages/domain/src/project-domain-api.server.tsnew file mode 100644index 0000000000..2f0be31dac--- /dev/null+++ b/packages/domain/src/project-domain-api.server.ts@@ -0,0 +1,401 @@+import { nanoid } from "nanoid";+import { z } from "zod";+import * as projectApi from "@webstudio-is/project/index.server";+import {+ createProductionBuild,+ parseDeployment,+ unpublishBuild,+} from "@webstudio-is/project-build/index.server";+import {+ templates as templateSchema,+ type Deployment,+} from "@webstudio-is/sdk";+import type { AppContext } from "@webstudio-is/trpc-interface/index.server";+import { db } from "./db";+import { validateDomain } from "./db/validate";++type LoadedProject = Awaited<ReturnType<typeof projectApi.loadById>>;+type ProjectDomain = LoadedProject["domainsVirtual"][number];++const assertMutation = (result: { success: boolean; error?: string }) => {+ if (result.success === false) {+ throw new Error(result.error ?? "Domain operation failed");+ }+};++const serializeProjectDomain = (domain: ProjectDomain) => ({+ id: domain.domainId,+ domain: domain.domain,+ status: domain.status,+ verified: domain.verified,+ txtRecord: domain.domainTxtRecord ?? undefined,+ expectedTxtRecord: domain.expectedTxtRecord,+ cname: domain.cname,+ error: domain.error ?? undefined,+ createdAt: domain.createdAt,+ updatedAt: domain.updatedAt,+});++const getProjectDomainOrThrow = (+ project: LoadedProject,+ predicate: (domain: ProjectDomain) => boolean+) => {+ const domain = project.domainsVirtual.find(predicate);+ if (domain === undefined) {+ throw new Error("Domain not found");+ }+ return domain;+};++export const getDefaultPublishDomains = (+ project: LoadedProject,+ target: "staging" | "production"+) => {+ if (target === "staging") {+ return [project.domain];+ }+ return [+ project.domain,+ ...project.domainsVirtual+ .filter((domain) => domain.status === "ACTIVE" && domain.verified)+ .map((domain) => domain.domain),+ ];+};++export const getVerifiedPublishDomains = (+ project: LoadedProject,+ domains: string[]+) => {+ const currentProjectDomains = project.domainsVirtual;+ const verifiedDomains: string[] = [];++ if (domains.includes(project.domain)) {+ verifiedDomains.push(project.domain);+ }++ verifiedDomains.push(+ ...domains.filter((domain) =>+ currentProjectDomains.some(+ (projectDomain) =>+ projectDomain.domain === domain &&+ projectDomain.status === "ACTIVE" &&+ projectDomain.verified+ )+ )+ );++ return verifiedDomains;+};++export const listProjectPublishes = async (+ projectId: string,+ context: AppContext+) => {+ const result = await context.postgrest.client+ .from("Build")+ .select("id, version, createdAt, deployment")+ .eq("projectId", projectId)+ .not("deployment", "is", null)+ .order("createdAt", { ascending: false });++ if (result.error) {+ throw result.error;+ }++ return {+ publishes: result.data.flatMap((build) => {+ const deployment = parseDeployment(build.deployment);+ if (deployment === undefined || deployment.destination === "static") {+ return [];+ }+ return [+ {+ id: build.id,+ jobId: build.id,+ version: build.version,+ target: deployment.domains.length > 1 ? "production" : "staging",+ domains: deployment.domains,+ createdAt: build.createdAt,+ },+ ];+ }),+ };+};++export const getProjectPublishJob = async (+ input: { projectId: string; jobId: string },+ context: AppContext+) => {+ const result = await context.postgrest.client+ .from("Build")+ .select("id, version, createdAt, deployment")+ .eq("projectId", input.projectId)+ .eq("id", input.jobId)+ .maybeSingle();++ if (result.error) {+ throw result.error;+ }+ const publishJob = result.data;+ if (publishJob === null) {+ return undefined;+ }++ const deployment = parseDeployment(publishJob.deployment);+ return {+ id: publishJob.id,+ version: publishJob.version,+ status: deployment === undefined ? "removed" : "success",+ domains:+ deployment !== undefined && deployment.destination !== "static"+ ? deployment.domains+ : [],+ createdAt: publishJob.createdAt,+ completedAt: publishJob.createdAt,+ };+};++const createSaasDeployment = ({+ project,+ domains,+}: {+ project: LoadedProject;+ domains: string[];+}): Deployment => ({+ destination: "saas",+ domains,+ assetsDomain: project.domain,+ excludeWstdDomainFromSearch: project.domainsVirtual.some(+ (domain) => domain.status === "ACTIVE" && domain.verified+ ),+});++export const publishProject = async (+ {+ project,+ domains,+ }: {+ project: LoadedProject;+ domains: string[];+ },+ context: AppContext+) => {+ const build = await createProductionBuild(+ {+ projectId: project.id,+ deployment: createSaasDeployment({ project, domains }),+ },+ context+ );+ const { deploymentTrpc, env } = context.deployment;++ if (env.BUILDER_ORIGIN === undefined) {+ throw new Error("Missing env.BUILDER_ORIGIN");+ }++ const result = await deploymentTrpc.publish.mutate({+ builderOrigin: env.BUILDER_ORIGIN,+ githubSha: env.GITHUB_SHA,+ buildId: build.id,+ branchName: env.GITHUB_REF_NAME,+ destination: "saas",+ logProjectName: `${project.title} - ${project.id}`,+ });++ const deploymentNotImplemented =+ result.success === false && result.error === "NOT_IMPLEMENTED";+ if (result.success === false && deploymentNotImplemented === false) {+ throw new Error(String(result.error ?? "Publish failed"));+ }++ return { build, project, deploymentNotImplemented };+};++export const publishStaticProject = async (+ {+ projectId,+ templates,+ name = `${projectId}-${nanoid()}.zip`,+ }: {+ projectId: string;+ templates: z.infer<typeof templateSchema>[];+ name?: string;+ },+ context: AppContext+) => {+ const project = await projectApi.loadById(projectId, context);+ const build = await createProductionBuild(+ {+ projectId,+ deployment: {+ destination: "static",+ name,+ assetsDomain: project.domain,+ templates,+ },+ },+ context+ );++ const { deploymentTrpc, env } = context.deployment;++ if (env.BUILDER_ORIGIN === undefined) {+ throw new Error("Missing env.BUILDER_ORIGIN");+ }++ const result = await deploymentTrpc.publish.mutate({+ builderOrigin: env.BUILDER_ORIGIN,+ githubSha: env.GITHUB_SHA,+ buildId: build.id,+ branchName: env.GITHUB_REF_NAME,+ destination: "static",+ logProjectName: `${project.title} - ${project.id}`,+ });++ return result.success+ ? { success: true as const, name, build, project }+ : result;+};++export const unpublishProjectDomains = async (+ {+ projectId,+ domains,+ }: {+ projectId: string;+ domains: string[];+ },+ context: AppContext+) => {+ const { deploymentTrpc, env } = context.deployment;++ for (const domain of domains) {+ const dbDomain = domain.replace(`.${env.PUBLISHER_HOST}`, "");+ const result = await deploymentTrpc.unpublish.mutate({ domain });+ await unpublishBuild({ projectId, domain: dbDomain }, context).catch(+ (error) => {+ if (+ error instanceof Error &&+ error.message === `Domain ${dbDomain} is not published`+ ) {+ return;+ }+ throw error;+ }+ );+ if (result.success === false && result.error !== "NOT_IMPLEMENTED") {+ throw new Error(`Failed to unpublish ${domain}: ${result.error}`);+ }+ }+};++export const listProjectDomains = async (+ projectId: string,+ context: AppContext+) => {+ const project = await projectApi.loadById(projectId, context);+ return project.domainsVirtual.map(serializeProjectDomain);+};++export const createProjectDomain = async (+ input: { projectId: string; domain: string },+ context: AppContext+) => {+ assertMutation(await createProjectDomainResult(input, context));+ const project = await projectApi.loadById(input.projectId, context);+ const validation = validateDomain(input.domain);+ const domain =+ validation.success === true+ ? validation.domain+ : input.domain.toLowerCase();+ return serializeProjectDomain(+ getProjectDomainOrThrow(project, (item) => item.domain === domain)+ );+};++export const createProjectDomainResult = async (+ input: { projectId: string; domain: string },+ context: AppContext+) => {+ return await db.create(input, context);+};++export const updateProjectDomain = async (+ input: {+ projectId: string;+ domainId: string;+ updates: { domain?: string };+ },+ context: AppContext+) => {+ const project = await projectApi.loadById(input.projectId, context);+ getProjectDomainOrThrow(+ project,+ (domain) => domain.domainId === input.domainId+ );++ if (input.updates.domain !== undefined) {+ const validation = validateDomain(input.updates.domain);+ if (validation.success === false) {+ throw new Error(validation.error);+ }+ const result = await context.postgrest.client+ .from("Domain")+ .update({+ domain: validation.domain,+ status: "INITIALIZING",+ error: null,+ txtRecord: null,+ })+ .eq("id", input.domainId);+ if (result.error) {+ throw result.error;+ }+ }++ const updatedProject = await projectApi.loadById(input.projectId, context);+ return serializeProjectDomain(+ getProjectDomainOrThrow(+ updatedProject,+ (domain) => domain.domainId === input.domainId+ )+ );+};++export const deleteProjectDomain = async (+ input: { projectId: string; domainId: string },+ context: AppContext+) => {+ assertMutation(await deleteProjectDomainResult(input, context));+ return { status: "deleted" as const };+};++export const deleteProjectDomainResult = async (+ input: { projectId: string; domainId: string },+ context: AppContext+) => {+ return await db.remove(input, context);+};++export const verifyProjectDomain = async (+ input: { projectId: string; domainId: string },+ context: AppContext+) => {+ assertMutation(await verifyProjectDomainResult(input, context));+ const project = await projectApi.loadById(input.projectId, context);+ return serializeProjectDomain(+ getProjectDomainOrThrow(+ project,+ (domain) => domain.domainId === input.domainId+ )+ );+};++export const verifyProjectDomainResult = async (+ input: { projectId: string; domainId: string },+ context: AppContext+) => {+ return await db.verify(input, context);+};++export const createUnpublishJobId = () => `unpublish-${nanoid()}`;diff --git a/packages/domain/src/trpc/domain.ts b/packages/domain/src/trpc/domain.tsindex 9c8b3efc9f..7d9b2b032c 100644--- a/packages/domain/src/trpc/domain.ts+++ b/packages/domain/src/trpc/domain.ts@@ -1,10 +1,5 @@import { z } from "zod";-import { nanoid } from "nanoid";import * as projectApi from "@webstudio-is/project/index.server";-import {- createProductionBuild,- unpublishBuild,-} from "@webstudio-is/project-build/index.server";import {router,procedure,@@ -16,6 +11,15 @@ import {import { templates } from "@webstudio-is/sdk";import { db } from "../db";import { isDomainUsingCloudflareNameservers } from "../rdap";+import {+ getVerifiedPublishDomains,+ createProjectDomainResult,+ deleteProjectDomainResult,+ publishProject,+ publishStaticProject,+ unpublishProjectDomains,+ verifyProjectDomainResult,+} from "../project-domain-api.server";export const domainRouter = router({getEntriToken: procedure.query(async ({ ctx }) => {@@ -75,79 +79,23 @@ export const domainRouter = router({).mutation(async ({ input, ctx }) => {try {- const project = await projectApi.loadById(input.projectId, ctx);-- const name = `${project.id}-${nanoid()}.zip`;-- const domains: string[] = [];-- let hasCustomDomain = false;-if (input.destination === "saas") {- const currentProjectDomains = project.domainsVirtual;-- if (input.domains.includes(project.domain)) {- domains.push(project.domain);- }-- domains.push(- ...input.domains.filter((domain) =>- currentProjectDomains.some(- (projectDomain) =>- projectDomain.domain === domain &&- projectDomain.status === "ACTIVE" &&- projectDomain.verified- )- )- );-- hasCustomDomain = currentProjectDomains.some(- (projectDomain) =>- projectDomain.status === "ACTIVE" && projectDomain.verified- );+ const project = await projectApi.loadById(input.projectId, ctx);+ const domains = getVerifiedPublishDomains(project, input.domains);+ await publishProject({ project, domains }, ctx);+ return { success: true as const };}- const build = await createProductionBuild(+ const result = await publishStaticProject({projectId: input.projectId,- deployment:- input.destination === "saas"- ? {- destination: input.destination,- domains: domains,- assetsDomain: project.domain,- excludeWstdDomainFromSearch: hasCustomDomain,- }- : {- destination: input.destination,- name,- assetsDomain: project.domain,- templates: input.templates,- },+ templates: input.templates,},ctx);- const { deploymentTrpc, env } = ctx.deployment;-- if (env.BUILDER_ORIGIN === undefined) {- throw new Error("Missing env.BUILDER_ORIGIN");- }-- const result = await deploymentTrpc.publish.mutate({- // used to load build data from the builder with build.loadProjectBundleByBuildId- builderOrigin: env.BUILDER_ORIGIN,- githubSha: env.GITHUB_SHA,- buildId: build.id,- // preview support- branchName: env.GITHUB_REF_NAME,- destination: input.destination,- // action log helper (not used for deployment, but for action logs readablity)- logProjectName: `${project.title} - ${project.id}`,- });-- if (input.destination === "static" && result.success) {- return { success: true as const, name };+ if (result.success) {+ return { success: true as const, name: result.name };}return result;@@ -167,31 +115,14 @@ export const domainRouter = router({).mutation(async ({ input, ctx }) => {try {- const { deploymentTrpc, env } = ctx.deployment;-- // Call deployment service to delete the worker for this domain- const result = await deploymentTrpc.unpublish.mutate({- domain: input.domain,- });-- // Extract subdomain for DB lookup (strip publisher host suffix)- // e.g., "myproject.wstd.work" → "myproject", "custom.com" → "custom.com"- const dbDomain = input.domain.replace(`.${env.PUBLISHER_HOST}`, "");-- // Always unpublish in DB regardless of worker deletion result- await unpublishBuild(- { projectId: input.projectId, domain: dbDomain },+ await unpublishProjectDomains(+ {+ projectId: input.projectId,+ domains: [input.domain],+ },ctx);- // If worker deletion failed (and not NOT_IMPLEMENTED), return error- if (result.success === false && result.error !== "NOT_IMPLEMENTED") {- return {- success: false,- message: `Failed to unpublish ${input.domain}: ${result.error}`,- };- }-return {success: true,message: `${input.domain} unpublished`,@@ -243,7 +174,7 @@ export const domainRouter = router({).mutation(async ({ input, ctx }) => {try {- return await db.create(+ return await createProjectDomainResult({projectId: input.projectId,domain: input.domain,@@ -264,7 +195,7 @@ export const domainRouter = router({).mutation(async ({ input, ctx }) => {try {- return await db.verify(+ return await verifyProjectDomainResult({projectId: input.projectId,domainId: input.domainId,@@ -284,7 +215,7 @@ export const domainRouter = router({).mutation(async ({ input, ctx }) => {try {- return await db.remove(+ return await deleteProjectDomainResult({projectId: input.projectId,domainId: input.domainId,diff --git a/packages/http-client/README.md b/packages/http-client/README.mdindex 7d9c4877ad..6fe67981aa 100644--- a/packages/http-client/README.md+++ b/packages/http-client/README.md@@ -1,3 +1,16 @@# Webstudio HTTP Client-Enables to optimize the http calls to Webstudio API.+Function-call client for Webstudio HTTP and TRPC APIs.++This package owns network details for Builder/project calls so callers do not+need route URLs, TRPC procedure paths, auth header names, staged upload+details, or response validation details.++- parsing Builder project URLs+- project bundle load/import helpers and sync bundle normalization+- staged uploads, asset uploads, and import-with-assets orchestration+- project API read/write helpers+- API compatibility headers and error messages++CLI command names, help text, manuals, and command-specific output formatting+belong in the CLI package, not here.diff --git a/packages/http-client/package.json b/packages/http-client/package.jsonindex 7a2e6ba964..5750ebcdb3 100644--- a/packages/http-client/package.json+++ b/packages/http-client/package.json@@ -1,7 +1,7 @@{"name": "@webstudio-is/http-client","version": "0.0.0-webstudio-version",- "description": "Webstudio HTTP Client",+ "description": "Function-call client for Webstudio HTTP and TRPC APIs","author": "Webstudio <[email protected]>","homepage": "https://webstudio.is","type": "module",@@ -14,6 +14,7 @@"dependencies": {"@trpc/client": "^10.45.2","@webstudio-is/protocol": "workspace:*",+ "@webstudio-is/trpc-interface": "workspace:*","tus-js-client": "^4.3.1"},"devDependencies": {diff --git a/packages/http-client/src/index.test.ts b/packages/http-client/src/index.test.tsindex e41c86b085..cae1f309f6 100644--- a/packages/http-client/src/index.test.ts+++ b/packages/http-client/src/index.test.ts@@ -1,108 +1,139 @@+import { readFile } from "node:fs/promises";import { createServer, type IncomingMessage } from "node:http";import { afterEach, expect, test, vi } from "vitest";-import { stagedUploadPath } from "@webstudio-is/protocol";import {+ bundleVersion,+ publicApiOperations,+ stagedUploadPath,+} from "@webstudio-is/protocol";+import {+ createImageAssetFixture,+ createPublishedProjectBundleFixture,+} from "@webstudio-is/protocol/fixtures";+import {+ applyBuildPatch,+ appendInstance,+ attachDesignToken,+ bindProps,+ cloneInstance,+ createBreakpoint,+ createPageFromTemplate,+ createDesignTokens,+ createDomain,+ createRedirect,+ defineCssVariables,+ createFolder,+ createPage,+ createApiClientHeaders,+ createResource,+ createVariable,+ deleteDesignTokenStyles,+ deleteCssVariables,+ deleteAssets,+ deleteBreakpoint,+ deleteDomain,+ deletePage,+ deleteFolder,+ detachDesignToken,+ deleteInstance,+ deleteProps,+ deleteResource,+ deleteRedirect,+ deleteVariable,+ duplicatePage,+ extractDesignToken,+ findAssetUsage,+ getPublishJob,+ getApiCompatibilityMessage,+ getApiErrorCode,+ getBuildSnapshot,+ getPage,+ getPageByPath,+ getBuildPatchSummary,+ getProjectPermissions,+ getProjectSettings,+ getStyleDeclarations,+ inspectInstance,importProjectBundle,+ importProjectBundleWithAssets,+ listAssets,+ listBreakpoints,+ listDesignTokens,+ listDomains,+ listFolders,+ listCssVariables,+ listInstances,+ listPages,+ listPageTemplates,+ listPublishes,+ listRedirects,+ listResources,+ listTexts,+ listVariables,loadProjectBundleByProjectId,+ moveInstance,+ publish,+ parseBuildPatchTransactions,parseBuilderUrl,+ toLocalProjectBundle,uploadAsset,+ uploadAssets,+ uploadProjectAsset,+ uploadProjectAssets,+ deleteStyleDeclarations,+ replaceAsset,+ replaceStyleValues,+ rewriteCssVariableRefs,+ updateDesignTokenStyles,+ updateDomain,+ updateBreakpoint,+ updatePage,+ updateFolder,+ updateProps,+ updateProjectSettings,+ updateRedirect,+ updateResource,+ updateStyleDeclarations,+ updateText,+ updateVariable,+ unpublish,+ verifyDomain,type PublishedProjectBundle,} from "./index";+import * as httpClient from "./index";afterEach(() => {vi.unstubAllGlobals();});-test("parseBuilderUrl wstd.dev", async () => {- expect(- parseBuilderUrl("https://p-090e6e14-ae50-4b2e-bd22-71733cec05bb.wstd.dev")- ).toMatchInlineSnapshot(`- {- "projectId": "090e6e14-ae50-4b2e-bd22-71733cec05bb",- "sourceOrigin": "https://wstd.dev",- }- `);-});--test("parseBuilderUrl localhost", async () => {- expect(- parseBuilderUrl("https://p-090e6e14-ae50-4b2e-bd22-71733cec05bb.localhost")- ).toMatchInlineSnapshot(`- {- "projectId": "090e6e14-ae50-4b2e-bd22-71733cec05bb",- "sourceOrigin": "https://localhost",- }- `);+const expectRequest = (+ path: string,+ body: string | ReturnType<typeof expect.stringContaining> = ""+) => ({+ path,+ search: expect.any(String),+ token: "token",+ body,});-test("parseBuilderUrl localhost", async () => {- expect(parseBuilderUrl("https://p-eee.localhost")).toMatchInlineSnapshot(`- {- "projectId": undefined,- "sourceOrigin": "https://p-eee.localhost",- }- `);-});+const expectBodyRequest = (path: string, body: string) =>+ expectRequest(path, expect.stringContaining(body));-test("parseBuilderUrl development.webstudio.is", async () => {- expect(- parseBuilderUrl(- "https://p-090e6e14-ae50-4b2e-bd22-71733cec05bb.development.webstudio.is"- )- ).toMatchInlineSnapshot(`- {- "projectId": "090e6e14-ae50-4b2e-bd22-71733cec05bb",- "sourceOrigin": "https://development.webstudio.is",- }- `);-});--test("parseBuilderUrl main.development.webstudio.is", async () => {- expect(- parseBuilderUrl(- "https://p-090e6e14-ae50-4b2e-bd22-71733cec05bb-dot-main.development.webstudio.is"- )- ).toMatchInlineSnapshot(`- {- "projectId": "090e6e14-ae50-4b2e-bd22-71733cec05bb",- "sourceOrigin": "https://main.development.webstudio.is",- }- `);-});--test("parseBuilderUrl branch.development.webstudio.is", async () => {- expect(- parseBuilderUrl(- "https://p-090e6e14-ae50-4b2e-bd22-71733cec05bb-dot-branch.development.webstudio.is"- )- ).toMatchInlineSnapshot(`-{- "projectId": "090e6e14-ae50-4b2e-bd22-71733cec05bb",- "sourceOrigin": "https://branch.development.webstudio.is",-}-`);-});+const apiParams = {+ authToken: "token",+ origin: "https://apps.webstudio.is",+ projectId: "project-id",+};-test("parseBuilderUrl apps.webstudio.is", async () => {+test("re-exports builder URL parsing from protocol", () => {expect(parseBuilderUrl("https://p-090e6e14-ae50-4b2e-bd22-71733cec05bb.apps.webstudio.is")- ).toMatchInlineSnapshot(`- {- "projectId": "090e6e14-ae50-4b2e-bd22-71733cec05bb",- "sourceOrigin": "https://apps.webstudio.is",- }- `);-});--test("parseBuilderUrl apps.webstudio.is", async () => {- expect(parseBuilderUrl("https://apps.webstudio.is")).toMatchInlineSnapshot(`- {- "projectId": undefined,- "sourceOrigin": "https://apps.webstudio.is",- }- `);+ ).toEqual({+ projectId: "090e6e14-ae50-4b2e-bd22-71733cec05bb",+ sourceOrigin: "https://apps.webstudio.is",+ });});test("reports non-json api responses", async () => {@@ -141,6 +172,801 @@ test("reports non-json api responses", async () => {expect(message).toContain("The request may be too large for the API.");});+test("creates api client compatibility headers", () => {+ expect(createApiClientHeaders({ name: "cli", version: "1.2.3" })).toEqual({+ "x-webstudio-client": "cli",+ "x-webstudio-client-version": "1.2.3",+ });+});++test("formats api compatibility update messages", () => {+ const error = {+ cause: {+ type: "webstudioApiCompatibilityError",+ reason: "apiProcedureNotFound",+ target: "cli",+ message:+ "This version of the Webstudio CLI is incompatible with the current API.",+ action: { type: "updateCli" },+ },+ };++ expect(+ getApiCompatibilityMessage(error, {+ updateCommand: "npm install -g webstudio@latest",+ runLatestCommand: "npx webstudio@latest sync",+ })+ ).toMatchInlineSnapshot(`+ "This version of the Webstudio CLI is incompatible with the current API.++ Update the CLI with:+ npm install -g webstudio@latest++ Or run the latest version once with:+ npx webstudio@latest sync"+ `);+});++test("extracts api error codes", () => {+ expect(getApiErrorCode({ data: { code: "CONFLICT" } })).toBe("CONFLICT");+ expect(+ getApiErrorCode({ data: { code: "SOME_PRIVATE_CODE" } })+ ).toBeUndefined();+ expect(getApiErrorCode(new Error("No code"))).toBeUndefined();+});++test("defines unique public api operation descriptors", () => {+ const commands = publicApiOperations.map(({ command }) => command);+ const ids = publicApiOperations.map(({ id }) => id);+ expect(new Set(commands).size).toBe(commands.length);+ expect(new Set(ids).size).toBe(ids.length);+ expect(publicApiOperations).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ command: "create-page",+ id: "pages.create",+ method: "mutation",+ permit: "build",+ path: "api.pages.create",+ client: "createPage",+ }),+ expect.objectContaining({+ command: "list-pages",+ id: "pages.list",+ method: "query",+ permit: "view",+ path: "api.pages.list",+ client: "listPages",+ }),+ expect.objectContaining({+ command: "list-instances",+ id: "instances.list",+ method: "query",+ permit: "view",+ path: "api.instances.list",+ client: "listInstances",+ }),+ expect.objectContaining({+ command: "list-texts",+ id: "instances.listTexts",+ method: "query",+ permit: "view",+ path: "api.instances.listTexts",+ client: "listTexts",+ }),+ expect.objectContaining({+ command: "create-domain",+ permit: "admin",+ }),+ ])+ );+});++test("operation descriptors reference exported http-client functions", () => {+ for (const operation of publicApiOperations) {+ expect(httpClient).toHaveProperty(operation.client);+ expect(typeof httpClient[operation.client as keyof typeof httpClient]).toBe(+ "function"+ );+ }+});++test("keeps public api paths in the operation descriptor", async () => {+ const content = await readFile(new URL("index.ts", import.meta.url), "utf-8");+ expect(content).not.toMatch(/["']api\.[A-Za-z0-9_.]+["']/);+});++test("wraps project api trpc calls in named functions", async () => {+ const requests: Array<{+ path: string;+ search: string;+ body: string;+ token?: string;+ }> = [];+ const server = createServer(async (request, response) => {+ const url = new URL(request.url ?? "/", "http://localhost");+ requests.push({+ path: url.pathname,+ search: url.search,+ body: (await readRequestBody(request)).toString("utf8"),+ token: request.headers["x-auth-token"] as string | undefined,+ });+ const data =+ url.pathname === "/trpc/api.build.get"+ ? {+ version: 2,+ homePageId: "home-id",+ rootFolderId: "root-folder",+ pages: [+ {+ id: "home-id",+ name: "Home",+ path: "",+ title: "Home",+ rootInstanceId: "home-body-id",+ meta: {},+ },+ {+ id: "page-id",+ name: "Pricing",+ path: "/pricing",+ title: "Pricing",+ rootInstanceId: "body-id",+ meta: {},+ },+ {+ id: "post-id",+ name: "Post",+ path: "/first-post",+ title: "Post",+ rootInstanceId: "post-body-id",+ meta: {},+ },+ ],+ folders: [+ {+ id: "root-folder",+ children: ["home-id", "page-id", "folder-id"],+ },+ {+ id: "folder-id",+ name: "Blog",+ slug: "blog",+ children: ["post-id"],+ },+ ],+ styleSources: [{ id: "token-id", type: "token", name: "Primary" }],+ styles: [+ {+ styleSourceId: "token-id",+ property: "color",+ value: { type: "keyword", value: "red" },+ },+ ],+ styleSourceSelections: [{ values: ["token-id"] }],+ instances: [+ {+ id: "body-id",+ component: "Body",+ children: [{ type: "text", value: "headline" }],+ },+ ],+ resources: [],+ variables: [+ {+ id: "variable-id",+ scopeInstanceId: "body-id",+ name: "Old Title",+ type: "variable",+ value: { type: "string", value: "Hello" },+ },+ ],+ }+ : { ok: true };+ response.writeHead(200, { "content-type": "application/json" });+ response.end(JSON.stringify([{ result: { data } }]));+ });++ await new Promise<void>((resolve) => {+ server.listen(0, "127.0.0.1", resolve);+ });++ try {+ const address = server.address();+ if (address === null || typeof address === "string") {+ throw new Error("Server address is unavailable");+ }+ const params = {+ authToken: "token",+ origin: `http://127.0.0.1:${address.port}`,+ projectId: "project-id",+ };++ await getBuildSnapshot({+ ...params,+ include: ["pages"],+ version: 2,+ });+ await listPages({+ ...params,+ includeFolders: true,+ });+ await getPage({+ ...params,+ pageId: "page-id",+ });+ await getPageByPath({+ ...params,+ path: "/pricing",+ });+ await getPageByPath({+ ...params,+ path: "/",+ });+ await getPageByPath({+ ...params,+ path: "/blog/first-post",+ });+ await createPage({+ ...params,+ name: "Pricing",+ path: "/pricing",+ });+ await updatePage({+ ...params,+ pageId: "page-id",+ values: { title: "Pricing" },+ });+ await getProjectSettings(params);+ await updateProjectSettings({+ ...params,+ meta: { siteName: "Acme", faviconAssetId: null },+ compiler: { atomicStyles: true },+ });+ await listRedirects(params);+ await createRedirect({+ ...params,+ old: "/old",+ new: "/new",+ status: "301",+ });+ await updateRedirect({+ ...params,+ old: "/old",+ values: { old: "/older", new: "/newer", status: null },+ });+ await deleteRedirect({+ ...params,+ old: "/older",+ });+ await listBreakpoints(params);+ await createBreakpoint({+ ...params,+ id: "tablet",+ label: "Tablet",+ maxWidth: 991,+ });+ await updateBreakpoint({+ ...params,+ breakpointId: "tablet",+ values: { maxWidth: 1023, condition: null },+ });+ await deleteBreakpoint({+ ...params,+ breakpointId: "tablet",+ });+ await duplicatePage({+ ...params,+ pageId: "page-id",+ name: "Pricing Copy",+ });+ await listPageTemplates(params);+ await createPageFromTemplate({+ ...params,+ templateId: "template-id",+ name: "Landing",+ path: "/landing",+ });+ await deletePage({+ ...params,+ pageId: "page-id",+ });+ await createFolder({+ ...params,+ name: "Blog",+ slug: "blog",+ });+ await updateFolder({+ ...params,+ folderId: "folder-id",+ values: { name: "Blog" },+ });+ await deleteFolder({+ ...params,+ folderId: "folder-id",+ });+ await listInstances({+ ...params,+ pagePath: "/pricing",+ maxDepth: 2,+ });+ await inspectInstance({+ ...params,+ instanceId: "instance-id",+ include: ["props", "styles", "children"],+ childDepth: 1,+ });+ await listTexts({+ ...params,+ pagePath: "/pricing",+ contains: "headline",+ });+ await updateText({+ ...params,+ instanceId: "instance-id",+ childIndex: 0,+ text: "Hello",+ });+ await createVariable({+ ...params,+ scopeInstanceId: "body-id",+ name: "Title",+ value: { type: "string", value: "Hello" },+ });+ await updateVariable({+ ...params,+ dataSourceId: "variable-id",+ values: { name: "Title" },+ });+ await deleteVariable({+ ...params,+ dataSourceId: "variable-id",+ });+ await createResource({+ ...params,+ resource: {+ name: "Posts",+ method: "get",+ url: '"https://api.example.com/posts"',+ headers: [],+ },+ });+ await updateResource({+ ...params,+ resourceId: "resource-id",+ values: { name: "Posts" },+ });+ await deleteResource({+ ...params,+ resourceId: "resource-id",+ force: true,+ });+ await appendInstance({+ ...params,+ parentInstanceId: "parent-id",+ children: [{ tag: "div", text: "Hello" }],+ });+ await moveInstance({+ ...params,+ moves: [{ instanceId: "instance-id", parentInstanceId: "parent-id" }],+ });+ await cloneInstance({+ ...params,+ sourceInstanceId: "instance-id",+ targetParentInstanceId: "parent-id",+ });+ await deleteInstance({+ ...params,+ instanceIds: ["instance-id"],+ });+ await updateProps({+ ...params,+ updates: [+ {+ instanceId: "instance-id",+ name: "title",+ type: "string",+ value: "Hi",+ },+ ],+ });+ await deleteProps({+ ...params,+ deletions: [{ instanceId: "instance-id", name: "title" }],+ });+ await bindProps({+ ...params,+ bindings: [+ {+ instanceId: "instance-id",+ name: "title",+ binding: { type: "expression", value: "title" },+ },+ ],+ });+ await getStyleDeclarations({+ ...params,+ instanceIds: ["instance-id"],+ includeTokens: true,+ });+ await updateStyleDeclarations({+ ...params,+ updates: [+ {+ instanceId: "instance-id",+ property: "color",+ value: { type: "keyword", value: "red" },+ },+ ],+ });+ await deleteStyleDeclarations({+ ...params,+ deletions: [{ instanceId: "instance-id", property: "color" }],+ });+ await replaceStyleValues({+ ...params,+ property: "color",+ fromValue: { type: "keyword", value: "red" },+ toValue: { type: "keyword", value: "blue" },+ });+ await listDesignTokens({+ ...params,+ withUsage: true,+ sort: "usage",+ });+ await createDesignTokens({+ ...params,+ tokens: [+ {+ name: "Primary",+ styles: { color: { type: "keyword", value: "red" } },+ },+ ],+ });+ await updateDesignTokenStyles({+ ...params,+ designTokenId: "token-id",+ updates: [+ { property: "color", value: { type: "keyword", value: "blue" } },+ ],+ });+ await deleteDesignTokenStyles({+ ...params,+ designTokenId: "token-id",+ deletions: [{ property: "color" }],+ });+ await attachDesignToken({+ ...params,+ designTokenId: "token-id",+ instanceIds: ["instance-id"],+ position: "before-local",+ });+ await detachDesignToken({+ ...params,+ designTokenId: "token-id",+ instanceIds: ["instance-id"],+ });+ await extractDesignToken({+ ...params,+ instanceIds: ["instance-id"],+ name: "Extracted",+ removeLocalProps: ["color"],+ });+ await listCssVariables({+ ...params,+ withUsage: true,+ });+ await defineCssVariables({+ ...params,+ vars: { "--brand-color": "red" },+ overwrite: true,+ });+ await deleteCssVariables({+ ...params,+ names: ["--brand-color"],+ force: true,+ });+ await rewriteCssVariableRefs({+ ...params,+ map: { "--brand-color": "--accent-color" },+ scopeRegex: "body",+ });+ await listVariables({+ ...params,+ scopeInstanceId: "body-id",+ });+ await listResources({+ ...params,+ scopeInstanceId: "body-id",+ });+ await listPublishes(params);+ await publish({+ ...params,+ target: "production",+ domains: ["example.com"],+ message: "Ship",+ idempotencyKey: "publish-key",+ });+ await getPublishJob({+ ...params,+ jobId: "job-id",+ });+ await unpublish({+ ...params,+ target: "production",+ domains: ["example.com"],+ message: "Rollback",+ idempotencyKey: "unpublish-key",+ });+ await listDomains(params);+ await createDomain({+ ...params,+ domain: "example.com",+ });+ await updateDomain({+ ...params,+ domainId: "domain-id",+ updates: { domain: "www.example.com" },+ });+ await deleteDomain({+ ...params,+ domainId: "domain-id",+ });+ await verifyDomain({+ ...params,+ domainId: "domain-id",+ });+ await listAssets({+ ...params,+ type: "image",+ withUsage: true,+ });+ await findAssetUsage({+ ...params,+ assetId: "asset-id",+ });+ await replaceAsset({+ ...params,+ fromAssetId: "old-asset-id",+ toAssetId: "new-asset-id",+ });+ await deleteAssets({+ ...params,+ assetIdsOrPrefixes: ["asset-id"],+ force: true,+ });+ await getProjectPermissions(params);+ await listFolders({+ ...params,+ includePages: true,+ });+ await applyBuildPatch({+ ...params,+ baseVersion: 2,+ transactions: {+ transactions: [+ {+ id: "tx-1",+ payload: [+ {+ namespace: "pages",+ patches: [+ {+ op: "replace",+ path: ["meta", "siteName"],+ value: "Site",+ },+ ],+ },+ ],+ },+ ],+ },+ });+ } finally {+ await new Promise<void>((resolve, reject) => {+ server.close((error) => (error ? reject(error) : resolve()));+ });+ }++ expect(requests).toEqual([+ expectRequest("/trpc/api.build.get"),+ expectRequest("/trpc/api.pages.list"),+ expectRequest("/trpc/api.pages.get"),+ expectRequest("/trpc/api.pages.getByPath"),+ expectRequest("/trpc/api.pages.getByPath"),+ expectRequest("/trpc/api.pages.getByPath"),+ expectBodyRequest("/trpc/api.pages.create", '"name":"Pricing"'),+ expectBodyRequest("/trpc/api.pages.update", '"title":"Pricing"'),+ expectRequest("/trpc/api.projectSettings.get"),+ expectBodyRequest("/trpc/api.projectSettings.update", '"siteName":"Acme"'),+ expectRequest("/trpc/api.redirects.list"),+ expectBodyRequest("/trpc/api.redirects.create", '"old":"/old"'),+ expectBodyRequest("/trpc/api.redirects.update", '"old":"/older"'),+ expectBodyRequest("/trpc/api.redirects.delete", '"old":"/older"'),+ expectRequest("/trpc/api.breakpoints.list"),+ expectBodyRequest("/trpc/api.breakpoints.create", '"maxWidth":991'),+ expectBodyRequest("/trpc/api.breakpoints.update", '"condition":null'),+ expectBodyRequest(+ "/trpc/api.breakpoints.delete",+ '"breakpointId":"tablet"'+ ),+ expectBodyRequest("/trpc/api.pages.duplicate", '"name":"Pricing Copy"'),+ expectRequest("/trpc/api.pageTemplates.list"),+ expectBodyRequest(+ "/trpc/api.pageTemplates.createPage",+ '"templateId":"template-id"'+ ),+ expectBodyRequest("/trpc/api.pages.delete", '"pageId":"page-id"'),+ expectBodyRequest("/trpc/api.folders.create", '"slug":"blog"'),+ expectBodyRequest("/trpc/api.folders.update", '"folderId":"folder-id"'),+ expectBodyRequest("/trpc/api.folders.delete", '"folderId":"folder-id"'),+ expectRequest("/trpc/api.instances.list"),+ expectRequest("/trpc/api.instances.inspect"),+ expectRequest("/trpc/api.instances.listTexts"),+ expectBodyRequest("/trpc/api.instances.updateText", '"text":"Hello"'),+ expectBodyRequest(+ "/trpc/api.variables.create",+ '"scopeInstanceId":"body-id"'+ ),+ expectBodyRequest("/trpc/api.variables.update", '"variable-id"'),+ expectBodyRequest("/trpc/api.variables.delete", '"variable-id"'),+ expectBodyRequest("/trpc/api.resources.create", '"name":"Posts"'),+ expectBodyRequest(+ "/trpc/api.resources.update",+ '"resourceId":"resource-id"'+ ),+ expectBodyRequest("/trpc/api.resources.delete", '"force":true'),+ expectBodyRequest(+ "/trpc/api.instances.append",+ '"parentInstanceId":"parent-id"'+ ),+ expectBodyRequest("/trpc/api.instances.move", '"instanceId":"instance-id"'),+ expectBodyRequest(+ "/trpc/api.instances.clone",+ '"sourceInstanceId":"instance-id"'+ ),+ expectBodyRequest(+ "/trpc/api.instances.delete",+ '"instanceIds":["instance-id"]'+ ),+ expectBodyRequest("/trpc/api.instances.updateProps", '"name":"title"'),+ expectBodyRequest("/trpc/api.instances.deleteProps", '"deletions"'),+ expectBodyRequest("/trpc/api.instances.bindProps", '"binding"'),+ expectRequest("/trpc/api.styles.getDeclarations"),+ expectBodyRequest(+ "/trpc/api.styles.updateDeclarations",+ '"property":"color"'+ ),+ expectBodyRequest("/trpc/api.styles.deleteDeclarations", '"deletions"'),+ expectBodyRequest("/trpc/api.styles.replaceValues", '"fromValue"'),+ expectRequest("/trpc/api.designTokens.list"),+ expectBodyRequest("/trpc/api.designTokens.create", '"name":"Primary"'),+ expectBodyRequest(+ "/trpc/api.designTokens.updateStyles",+ '"designTokenId":"token-id"'+ ),+ expectBodyRequest("/trpc/api.designTokens.deleteStyles", '"deletions"'),+ expectBodyRequest(+ "/trpc/api.designTokens.attach",+ '"position":"before-local"'+ ),+ expectBodyRequest(+ "/trpc/api.designTokens.detach",+ '"instanceIds":["instance-id"]'+ ),+ expectBodyRequest("/trpc/api.designTokens.extract", '"name":"Extracted"'),+ expectRequest("/trpc/api.cssVariables.list"),+ expectBodyRequest("/trpc/api.cssVariables.define", '"--brand-color":"red"'),+ expectBodyRequest("/trpc/api.cssVariables.delete", '"confirm":true'),+ expectBodyRequest(+ "/trpc/api.cssVariables.rewriteRefs",+ '"scopeRegex":"body"'+ ),+ expectRequest("/trpc/api.variables.list"),+ expectRequest("/trpc/api.resources.list"),+ expectRequest("/trpc/api.publish.list"),+ expectBodyRequest(+ "/trpc/api.publish.create",+ '"idempotencyKey":"publish-key"'+ ),+ expectRequest("/trpc/api.publish.getJob"),+ expectBodyRequest("/trpc/api.publish.unpublish", '"confirm":true'),+ expectRequest("/trpc/api.domains.list"),+ expectBodyRequest("/trpc/api.domains.create", '"domain":"example.com"'),+ expectBodyRequest("/trpc/api.domains.update", '"domain":"www.example.com"'),+ expectBodyRequest("/trpc/api.domains.delete", '"confirm":true'),+ expectBodyRequest("/trpc/api.domains.verify", '"domainId":"domain-id"'),+ expectRequest("/trpc/api.assets.list"),+ expectRequest("/trpc/api.assets.findUsage"),+ expectBodyRequest("/trpc/api.assets.replace", '"confirm":true'),+ expectBodyRequest(+ "/trpc/api.assets.delete",+ '"assetIdsOrPrefixes":["asset-id"]'+ ),+ expectRequest("/trpc/api.projects.permissions"),+ expectRequest("/trpc/api.folders.list"),+ expectBodyRequest("/trpc/api.build.patch", '"baseVersion":2'),+ ]);+ expect(decodeURIComponent(requests[0]?.search ?? "")).toContain(+ '"include":["pages"]'+ );+ expect(decodeURIComponent(requests[0]?.search ?? "")).toContain(+ '"version":2'+ );+});++test("reports invalid build patch transactions", async () => {+ await expect(+ applyBuildPatch({+ ...apiParams,+ baseVersion: 2,+ transactions: [{ id: "tx-1" }],+ })+ ).rejects.toThrow("Invalid patch JSON:");+});++test("parses build patch transaction input", () => {+ expect(+ parseBuildPatchTransactions({+ transactions: [+ {+ id: "tx-1",+ payload: [+ {+ namespace: "pages",+ patches: [+ { op: "replace", path: ["meta", "siteName"], value: "Site" },+ ],+ },+ ],+ },+ ],+ })+ ).toEqual([+ {+ id: "tx-1",+ payload: [+ {+ namespace: "pages",+ patches: [+ { op: "replace", path: ["meta", "siteName"], value: "Site" },+ ],+ },+ ],+ },+ ]);+});++test("summarizes build patch transactions", () => {+ expect(+ getBuildPatchSummary([+ {+ id: "tx-1",+ payload: [+ {+ namespace: "pages",+ patches: [+ { op: "replace", path: ["meta", "siteName"], value: "Site" },+ ],+ },+ {+ namespace: "styles",+ patches: [+ { op: "remove", path: ["style-1"] },+ { op: "remove", path: ["style-2"] },+ ],+ },+ ],+ },+ ])+ ).toEqual({+ transactionCount: 1,+ patchCount: 3,+ namespaces: ["pages", "styles"],+ });+});+test("uploads assets as binary requests", async () => {const fetch = vi.fn().mockResolvedValue(new Response(JSON.stringify({ ok: true }), {@@ -175,7 +1001,7 @@ test("uploads assets as binary requests", async () => {expect(fetch).toHaveBeenCalledOnce();const [url, init] = fetch.mock.calls[0] as [URL, RequestInit];expect(url.href).toBe(- "https://apps.webstudio.is/rest/assets/image.png?projectId=090e6e14-ae50-4b2e-bd22-71733cec05bb&type=image&width=10&height=20&format=png"+ "https://apps.webstudio.is/rest/assets/image.png?projectId=090e6e14-ae50-4b2e-bd22-71733cec05bb&type=image&assetId=asset-id&width=10&height=20&format=png");expect(init.method).toBe("POST");expect(init.body).toBe(file);@@ -221,6 +1047,132 @@ test("reports asset upload errors", async () => {).rejects.toThrow("Upload failed");});+test("uploads assets with one retry and aggregated failures", async () => {+ const asset = createImageAssetFixture({ name: "image.png" });+ const otherAsset = createImageAssetFixture({+ id: "asset-2",+ name: "other.png",+ });+ const attempts = new Map<string, number>();+ const fetch = vi.fn(async (request: URL | RequestInfo) => {+ const url = new URL(request.toString());+ const assetName = url.pathname.split("/").at(-1) ?? "";+ const attempt = (attempts.get(assetName) ?? 0) + 1;+ attempts.set(assetName, attempt);+ if (assetName === "image.png" && attempt === 2) {+ return new Response(JSON.stringify({ ok: true }), {+ headers: { "content-type": "application/json" },+ });+ }+ return new Response(+ JSON.stringify({+ errors:+ assetName === "image.png" ? "Temporary failure" : "Upload failed",+ }),+ {+ headers: { "content-type": "application/json" },+ }+ );+ });+ vi.stubGlobal("fetch", fetch);++ await expect(+ uploadAssets({+ assets: [asset, otherAsset],+ ...apiParams,+ readAssetData: async (asset) => new Blob([asset.name]),+ })+ ).rejects.toThrow("Failed to upload assets: other.png: Upload failed");++ expect(fetch).toHaveBeenCalledTimes(4);+});++test("keeps uploaded assets in input order", async () => {+ const first = createImageAssetFixture({ id: "first", name: "first.png" });+ const second = createImageAssetFixture({ id: "second", name: "second.png" });+ const fetch = vi.fn(async (request: URL | RequestInfo) => {+ const url = new URL(request.toString());+ const name = decodeURIComponent(url.pathname.split("/").at(-1) ?? "");+ if (name === "first.png") {+ await new Promise((resolve) => setTimeout(resolve, 10));+ }+ return new Response(+ JSON.stringify({+ uploadedAssets: [name === "first.png" ? first : second],+ }),+ {+ headers: { "content-type": "application/json" },+ }+ );+ });+ vi.stubGlobal("fetch", fetch);++ await expect(+ uploadAssets({+ assets: [first, second],+ ...apiParams,+ readAssetData: async (asset) => new Blob([asset.name]),+ })+ ).resolves.toEqual([first, second]);+});++test("uploads project asset descriptors with local data readers", async () => {+ const uploadedAsset = createImageAssetFixture({ name: "image.png" });+ const fetch = vi.fn(+ async () =>+ new Response(JSON.stringify({ uploadedAssets: [uploadedAsset] }), {+ headers: { "content-type": "application/json" },+ })+ );+ vi.stubGlobal("fetch", fetch);++ await expect(+ uploadProjectAsset({+ ...apiParams,+ asset: {+ name: "image.png",+ type: "image",+ format: "png",+ meta: { width: 10, height: 20 },+ },+ readAssetData: async () => new Uint8Array([1, 2, 3]),+ })+ ).resolves.toEqual({ uploaded: [uploadedAsset] });++ await expect(+ uploadProjectAssets({+ ...apiParams,+ assets: [+ {+ name: "image.png",+ type: "image",+ format: "png",+ meta: { width: 10, height: 20 },+ },+ ],+ readAssetData: async () => new Uint8Array([1, 2, 3]),+ })+ ).resolves.toEqual({ uploaded: [uploadedAsset] });+});++test("normalizes synced project bundles for local storage", () => {+ const bundle = createPublishedProjectBundleFixture({+ bundleVersion: undefined,+ });++ expect(toLocalProjectBundle(bundle)).toMatchObject({+ bundleVersion,+ build: bundle.build,+ page: bundle.page,+ pages: bundle.pages,+ assets: bundle.assets,+ user: bundle.user,+ projectDomain: bundle.projectDomain,+ projectTitle: bundle.projectTitle,+ origin: bundle.origin,+ });+});+const readRequestBody = async (request: IncomingMessage) => {const chunks = [];for await (const chunk of request) {@@ -305,6 +1257,134 @@ test("imports project bundle through staged upload", async () => {expect(JSON.stringify(trpcBody)).not.toContain("largeContent");});+test("imports project bundle with assets and retries missing asset uploads", async () => {+ const asset = createImageAssetFixture({ name: "image.png" });+ const bundle = createPublishedProjectBundleFixture({ assets: [asset] });+ const calls: string[] = [];+ const uploadOffsets = new Map<string, number>();+ let importAttempts = 0;+ let uploadAttempts = 0;++ const server = createServer(async (request, response) => {+ const url = new URL(request.url ?? "/", "http://localhost");+ calls.push(`${request.method} ${url.pathname}`);++ if (+ request.method === "GET" &&+ url.pathname === "/trpc/build.checkProjectBuildPermission"+ ) {+ response.writeHead(200, { "content-type": "application/json" });+ response.end(JSON.stringify([{ result: { data: undefined } }]));+ return;+ }++ if (+ request.method === "POST" &&+ url.pathname === "/rest/assets/image.png"+ ) {+ uploadAttempts += 1;+ await readRequestBody(request);+ response.writeHead(200, { "content-type": "application/json" });+ response.end(JSON.stringify({ ok: true }));+ return;+ }++ if (request.method === "POST" && url.pathname === stagedUploadPath) {+ response.writeHead(201, {+ Location: `http://${request.headers.host}${stagedUploadPath}/upload-id-${importAttempts}`,+ "Tus-Resumable": "1.0.0",+ });+ response.end();+ return;+ }++ if (+ request.method === "PATCH" &&+ url.pathname.startsWith(`${stagedUploadPath}/upload-id-`)+ ) {+ const chunk = await readRequestBody(request);+ const offset = (uploadOffsets.get(url.pathname) ?? 0) + chunk.byteLength;+ uploadOffsets.set(url.pathname, offset);+ response.writeHead(204, {+ "Tus-Resumable": "1.0.0",+ "Upload-Offset": String(offset),+ });+ response.end();+ return;+ }++ if (+ request.method === "POST" &&+ url.pathname === "/trpc/build.importProjectBundle"+ ) {+ importAttempts += 1;+ await readRequestBody(request);+ response.writeHead(200, { "content-type": "application/json" });+ response.end(+ JSON.stringify([+ importAttempts === 1+ ? {+ error: {+ message: "Imported asset files are missing: image.png",+ code: -32603,+ data: { code: "INTERNAL_SERVER_ERROR" },+ },+ }+ : { result: { data: { version: 2 } } },+ ])+ );+ return;+ }++ response.writeHead(404);+ response.end();+ });++ await new Promise<void>((resolve) => {+ server.listen(0, "127.0.0.1", resolve);+ });++ const importAttemptMessages: string[] = [];+ const missingAssetMessages: string[] = [];+ const uploadAssetMessages: string[] = [];++ try {+ const address = server.address();+ if (address === null || typeof address === "string") {+ throw new Error("Server address is unavailable");+ }++ await expect(+ importProjectBundleWithAssets({+ authToken: "token",+ origin: `http://127.0.0.1:${address.port}`,+ projectId: "project-id",+ data: bundle,+ readAssetData: async () => new Blob(["asset"]),+ onImportAttempt: () => importAttemptMessages.push("attempt"),+ onMissingAssets: (assets) =>+ missingAssetMessages.push(+ assets.map((asset) => asset.name).join(",")+ ),+ onUploadAssets: (assets) =>+ uploadAssetMessages.push(assets.map((asset) => asset.name).join(",")),+ })+ ).resolves.toEqual({ version: 2 });+ } finally {+ await new Promise<void>((resolve, reject) => {+ server.close((error) => (error ? reject(error) : resolve()));+ });+ }++ expect(calls).toContain("GET /trpc/build.checkProjectBuildPermission");+ expect(importAttempts).toBe(2);+ expect(uploadAttempts).toBe(2);+ expect(uploadOffsets.size).toBe(2);+ expect(importAttemptMessages).toEqual(["attempt", "attempt"]);+ expect(missingAssetMessages).toEqual(["image.png"]);+ expect(uploadAssetMessages).toEqual(["image.png"]);+});+test("rejects project bundles over the import size limit", async () => {let requestCount = 0;const server = createServer((_request, response) => {diff --git a/packages/http-client/src/index.ts b/packages/http-client/src/index.tsindex 6ba09b9fbd..ae76878ca7 100644--- a/packages/http-client/src/index.ts+++ b/packages/http-client/src/index.ts@@ -1,18 +1,36 @@import { createTRPCUntypedClient, httpBatchLink } from "@trpc/client";import { Upload } from "tus-js-client";import {+ apiClientHeader,+ apiClientVersionHeader,+ getApiCompatibilityPayload,+} from "@webstudio-is/trpc-interface/api-compatibility";+import {+ buildPatchTransaction,+ buildPatchNamespaces,+ bundleVersion as currentBundleVersion,importProjectBundleResult,+ parseMissingImportedAssetFilesMessage,publishedProjectBundle,maxProjectBundleSize,stagedUploadPath,stagedUploadProjectIdHeader,+ parseBuilderUrl,+ type BuildPatchTransaction,+ getPublicApiOperation,+ getPublicApiOperationPath,type ImportProjectBundleResult,+ isPublicApiRemoteErrorCode,type PublishedProjectBundle,+ type PublicApiCommand,} from "@webstudio-is/protocol";export { getBundleVersion, bundleVersion } from "@webstudio-is/protocol";+export { parseBuilderUrl } from "@webstudio-is/protocol";export type {+ BuildPatchTransaction,PublishedProjectBundle,ProjectBundle,+ PublicApiRemoteErrorCode,} from "@webstudio-is/protocol";const maxResponsePreviewLength = 500;@@ -78,6 +96,56 @@ const createHeadersObject = (headers: Record<string, string | undefined>) => {};type RequestHeaders = Record<string, string | undefined>;+type ApiClientName = "browser" | "cli" | "service";++export const createApiClientHeaders = ({+ name,+ version,+}: {+ name: ApiClientName;+ version: string;+}): RequestHeaders => ({+ [apiClientHeader]: name,+ [apiClientVersionHeader]: version,+});++export const getApiCompatibilityMessage = (+ error: unknown,+ {+ runLatestCommand,+ updateCommand,+ }: {+ runLatestCommand: string;+ updateCommand: string;+ }+) => {+ const payload = getApiCompatibilityPayload(error);+ if (payload?.action.type !== "updateCli") {+ return;+ }++ return `${payload.message}++Update the CLI with:+ ${updateCommand}++Or run the latest version once with:+ ${runLatestCommand}`;+};++export const getApiErrorCode = (error: unknown) => {+ const data =+ typeof error === "object" && error !== null+ ? (error as { data?: unknown }).data+ : undefined;+ if (typeof data !== "object" || data === null) {+ return;+ }+ const code = (data as { code?: unknown }).code;+ return typeof code === "string" && isPublicApiRemoteErrorCode(code)+ ? code+ : undefined;+};const createTrpcClient = (origin: string, headers: RequestHeaders) => {const { sourceOrigin } = parseBuilderUrl(origin);@@ -98,11 +166,18 @@ const createAuthTrpcClient = (params: {origin: string;authToken: string;headers?: RequestHeaders;-}) =>- createTrpcClient(params.origin, {+}) => {+ const client = createTrpcClient(params.origin, {...params.headers,"x-auth-token": params.authToken,});+ return {+ query: <Result = unknown>(path: string, input?: unknown) =>+ client.query(path, input) as Promise<Result>,+ mutation: <Result = unknown>(path: string, input?: unknown) =>+ client.mutation(path, input) as Promise<Result>,+ };+};type AuthProjectParams = {projectId: string;@@ -111,6 +186,102 @@ type AuthProjectParams = {headers?: RequestHeaders;};+type AuthTokenParams = {+ origin: string;+ authToken: string;+ headers?: RequestHeaders;+};++const queryProjectApi = async <Result = unknown>(+ params: AuthProjectParams,+ path: string,+ input: Record<string, unknown> = {}+) => {+ return await createAuthTrpcClient(params).query<Result>(path, {+ projectId: params.projectId,+ ...input,+ });+};++const mutateProjectApi = async <Result = unknown>(+ params: AuthProjectParams,+ path: string,+ input: Record<string, unknown> = {}+) => {+ return await createAuthTrpcClient(params).mutation<Result>(path, {+ projectId: params.projectId,+ ...input,+ });+};++const pickInput = <Params extends object, Key extends keyof Params>(+ params: Params,+ keys: readonly Key[]+) => {+ const input: Record<string, unknown> = {};+ for (const key of keys) {+ input[String(key)] = params[key];+ }+ return input;+};++const projectQuery =+ <Params extends AuthProjectParams, Result = unknown>(+ path: string,+ getInput: (params: Params) => Record<string, unknown> = () => ({})+ ) =>+ async (params: Params) =>+ await queryProjectApi<Result>(params, path, getInput(params));++const projectMutation =+ <Params extends AuthProjectParams, Result = unknown>(+ path: string,+ getInput: (params: Params) => Record<string, unknown> = () => ({})+ ) =>+ async (params: Params) =>+ await mutateProjectApi<Result>(params, path, getInput(params));++const projectQueryInput = <Params extends AuthProjectParams, Result = unknown>(+ command: PublicApiCommand+) => {+ const operation = getPublicApiOperation(command);+ return projectQuery<Params, Result>(+ getPublicApiOperationPath(command),+ (params) =>+ pickInput(params, operation.inputFields as readonly (keyof Params)[])+ );+};++const projectMutationInput = <+ Params extends AuthProjectParams,+ Result = unknown,+>(+ command: PublicApiCommand+) => {+ const operation = getPublicApiOperation(command);+ return projectMutation<Params, Result>(+ getPublicApiOperationPath(command),+ (params) =>+ pickInput(params, operation.inputFields as readonly (keyof Params)[])+ );+};++const projectConfirmedMutationInput = <+ Params extends AuthProjectParams,+ Result = unknown,+>(+ command: PublicApiCommand+) => {+ const operation = getPublicApiOperation(command);+ return projectMutation<Params, Result>(+ getPublicApiOperationPath(command),+ (params) => ({+ ...pickInput(params, operation.inputFields as readonly (keyof Params)[]),+ confirm: true,+ })+ );+};+const stagedUploadChunkSize = 3 * 1024 * 1024;const formatMebibytes = (bytes: number) =>@@ -124,6 +295,54 @@ type AssetUpload = {data: BinaryAssetData;};+type AssetUploadDescriptor = {+ id?: string;+ name: string;+ type: Asset["type"];+ format?: string;+ meta?: Record<string, unknown>;+ description?: string | null;+};++type AssetUploadResult = { uploadedAssets?: Asset[] };+type AssetUploadBatchResult =+ | { status: "fulfilled"; uploadedAssets: Asset[] }+ | { status: "rejected"; asset: Asset; error: unknown };++const toArrayBuffer = async (data: BinaryAssetData) => {+ if (data instanceof Blob) {+ return data.arrayBuffer();+ }+ if (ArrayBuffer.isView(data)) {+ return data.buffer.slice(+ data.byteOffset,+ data.byteOffset + data.byteLength+ );+ }+ return data;+};++const getSha256Hash = async (data: BinaryAssetData) => {+ const hashBuffer = await crypto.subtle.digest(+ "SHA-256",+ await toArrayBuffer(data)+ );+ return Array.from(new Uint8Array(hashBuffer))+ .map((byte) => byte.toString(16).padStart(2, "0"))+ .join("");+};++const formatError = (error: unknown) =>+ error instanceof Error ? error.message : String(error);++const retryOnce = async <Result>(task: () => Promise<Result>) => {+ try {+ return await task();+ } catch {+ return await task();+ }+};+const getAssetUploadUrl = ({asset,origin,@@ -140,6 +359,7 @@ const getAssetUploadUrl = ({);url.searchParams.set("projectId", projectId);url.searchParams.set("type", asset.type);+ url.searchParams.set("assetId", asset.id);if (asset.type === "image") {url.searchParams.set("width", String(asset.meta.width));url.searchParams.set("height", String(asset.meta.height));@@ -152,7 +372,7 @@ export const uploadAsset = async (params: AuthProjectParams & {upload: AssetUpload;}-): Promise<void> => {+): Promise<Asset[]> => {const { authToken, headers, origin, projectId, upload } = params;const response = await fetchJsonResponse(getAssetUploadUrl({@@ -170,7 +390,11 @@ export const uploadAsset = async (}),});- const result = await response.json();+ const result = (await response.json()) as+ | AssetUploadResult+ | {+ errors?: string;+ };if (typeof result === "object" &&result !== null &&@@ -179,6 +403,162 @@ export const uploadAsset = async () {throw new Error(result.errors);}+ return "uploadedAssets" in result && Array.isArray(result.uploadedAssets)+ ? result.uploadedAssets.map((asset) => ({+ ...asset,+ id: asset.id || upload.asset.id,+ }))+ : [];+};++export const uploadAssets = async (+ params: AuthProjectParams & {+ assets: Asset[];+ readAssetData: (asset: Asset) => Promise<BinaryAssetData>;+ }+): Promise<Asset[]> => {+ const results: AssetUploadBatchResult[] = await Promise.all(+ params.assets.map(async (asset) => {+ try {+ const uploadedAssets = await retryOnce(async () => {+ const data = await params.readAssetData(asset);+ const assetWithId = {+ ...asset,+ id: asset.id || (await getSha256Hash(data)),+ };+ return await uploadAsset({+ authToken: params.authToken,+ headers: params.headers,+ origin: params.origin,+ projectId: params.projectId,+ upload: {+ asset: assetWithId,+ data,+ },+ });+ });+ return { status: "fulfilled", uploadedAssets };+ } catch (error) {+ return { status: "rejected", asset, error };+ }+ })+ );++ const failedUploads = results.flatMap((result) =>+ result.status === "rejected"+ ? [{ asset: result.asset, error: result.error }]+ : []+ );+ if (failedUploads.length > 0) {+ throw new Error(+ `Failed to upload assets: ${failedUploads+ .map(({ asset, error }) => `${asset.name}: ${formatError(error)}`)+ .join("; ")}`+ );+ }+ return results.flatMap((result) =>+ result.status === "fulfilled" ? result.uploadedAssets : []+ );+};++const toUploadAsset = ({+ descriptor,+ projectId,+}: {+ descriptor: AssetUploadDescriptor;+ projectId: string;+}): Asset => {+ const base = {+ id: descriptor.id ?? "",+ projectId,+ name: descriptor.name,+ filename: descriptor.name,+ description: descriptor.description ?? null,+ size: 0,+ createdAt: new Date().toISOString(),+ };+ if (descriptor.type === "image") {+ const width = descriptor.meta?.width;+ const height = descriptor.meta?.height;+ if (+ typeof width !== "number" ||+ typeof height !== "number" ||+ descriptor.format === undefined+ ) {+ throw new Error(+ `Image asset "${descriptor.name}" requires format, meta.width, and meta.height.`+ );+ }+ return {+ ...base,+ type: "image",+ format: descriptor.format,+ meta: { width, height },+ };+ }+ if (descriptor.type === "font") {+ return {+ ...base,+ type: "font",+ format: descriptor.format ?? "woff2",+ meta: descriptor.meta ?? {},+ } as Asset;+ }+ return {+ ...base,+ type: "file",+ format: descriptor.format ?? descriptor.name.split(".").at(-1) ?? "",+ meta: {},+ };+};++export const uploadProjectAsset = async (+ params: AuthProjectParams & {+ asset: AssetUploadDescriptor;+ readAssetData: (asset: AssetUploadDescriptor) => Promise<BinaryAssetData>;+ }+) => {+ const asset = toUploadAsset({+ descriptor: params.asset,+ projectId: params.projectId,+ });+ const uploaded = await uploadAssets({+ authToken: params.authToken,+ headers: params.headers,+ origin: params.origin,+ projectId: params.projectId,+ assets: [asset],+ readAssetData: () => params.readAssetData(params.asset),+ });+ return { uploaded };+};++export const uploadProjectAssets = async (+ params: AuthProjectParams & {+ assets: AssetUploadDescriptor[];+ readAssetData: (asset: AssetUploadDescriptor) => Promise<BinaryAssetData>;+ }+) => {+ const descriptorByName = new Map(+ params.assets.map((descriptor) => [descriptor.name, descriptor])+ );+ const uploaded = await uploadAssets({+ authToken: params.authToken,+ headers: params.headers,+ origin: params.origin,+ projectId: params.projectId,+ assets: params.assets.map((descriptor) =>+ toUploadAsset({ descriptor, projectId: params.projectId })+ ),+ readAssetData: (asset) => {+ const descriptor = descriptorByName.get(asset.name);+ if (descriptor === undefined) {+ throw new Error(`Asset descriptor not found for ${asset.name}.`);+ }+ return params.readAssetData(descriptor);+ },+ });+ return { uploaded };};export const loadProjectBundleByBuildId = async (@@ -219,6 +599,32 @@ export const loadProjectBundleByProjectId = async (return publishedProjectBundle.parse(data);};+export const toLocalProjectBundle = (project: PublishedProjectBundle) => {+ const normalizedProject = publishedProjectBundle.parse(project);+ const {+ assets,+ build,+ bundleVersion: synchronizedBundleVersion,+ origin,+ page,+ pages,+ projectDomain,+ projectTitle,+ user,+ } = normalizedProject;+ return {+ bundleVersion: synchronizedBundleVersion ?? currentBundleVersion,+ build,+ page,+ pages,+ assets,+ user,+ projectDomain,+ projectTitle,+ origin,+ };+};+export const checkProjectBuildPermission = async (params: AuthProjectParams): Promise<void> => {@@ -230,6 +636,723 @@ export const checkProjectBuildPermission = async ();};+const formatSchemaIssues = (+ issues: Array<{ path: Array<string | number>; message: string }>+) =>+ issues+ .map((issue) => {+ const path = issue.path.join(".");+ return path === "" ? issue.message : `${path}: ${issue.message}`;+ })+ .join(", ");++export const parseBuildPatchTransactions = (transactions: unknown) => {+ const input =+ typeof transactions === "object" &&+ transactions !== null &&+ "transactions" in transactions+ ? (transactions as { transactions: unknown }).transactions+ : transactions;++ const result = buildPatchTransaction.array().safeParse(input);+ if (result.success === false) {+ throw new Error(+ `Invalid patch JSON: ${formatSchemaIssues(result.error.issues)}`+ );+ }+ return result.data;+};++export const getBuildPatchSummary = (transactions: BuildPatchTransaction[]) => {+ const namespaces = new Set<(typeof buildPatchNamespaces)[number]>();+ let patchCount = 0;+ for (const transaction of transactions) {+ for (const item of transaction.payload) {+ namespaces.add(item.namespace);+ patchCount += item.patches.length;+ }+ }+ return {+ transactionCount: transactions.length,+ patchCount,+ namespaces: [...namespaces],+ };+};++export const getApiTokenInfo = async (params: AuthTokenParams) => {+ return await createAuthTrpcClient(params).query(+ getPublicApiOperationPath("whoami")+ );+};++export const getProjectInfo = projectQuery(+ getPublicApiOperationPath("inspect")+);++export const getProjectPermissions = projectQuery(+ getPublicApiOperationPath("permissions")+);++export const getBuildSnapshot = projectQueryInput<+ AuthProjectParams & {+ include?: string[];+ version?: number;+ }+>("snapshot");++export const applyBuildPatch = async (+ params: AuthProjectParams & {+ baseVersion: number;+ transactions: unknown;+ }+) => {+ return await mutateProjectApi(+ params,+ getPublicApiOperationPath("apply-patch"),+ {+ baseVersion: params.baseVersion,+ transactions: parseBuildPatchTransactions(params.transactions),+ }+ );+};++type PageMetaInput = {+ description?: string;+ language?: string;+ redirect?: string;+ status?: string;+ socialImageUrl?: string;+ socialImageAssetId?: string;+ excludePageFromSearch?: boolean;+ documentType?: "html" | "xml" | "text";+ content?: string;+ auth?: { method: "basic"; login: string; password: string };+ custom?: Array<{ property: string; content: string }>;+};++type PageFieldsInput = {+ name?: string;+ path?: string;+ title?: string;+ parentFolderId?: string;+ meta?: PageMetaInput;+};++export const listPages = projectQueryInput<+ AuthProjectParams & {+ includeFolders?: boolean;+ }+>("list-pages");++export const getPage = projectQueryInput<+ AuthProjectParams & {+ pageId: string;+ }+>("get-page");++export const getPageByPath = projectQueryInput<+ AuthProjectParams & {+ path: string;+ }+>("get-page-by-path");++export const createPage = projectMutationInput<+ AuthProjectParams & {+ pageId?: string;+ name: string;+ path: string;+ title?: string;+ parentFolderId?: string;+ meta?: PageMetaInput;+ }+>("create-page");++export const updatePage = projectMutationInput<+ AuthProjectParams & {+ pageId: string;+ values: PageFieldsInput;+ }+>("update-page");++type ProjectSettingsInput = {+ meta?: {+ siteName?: string | null;+ contactEmail?: string | null;+ faviconAssetId?: string | null;+ code?: string | null;+ auth?: string | null;+ };+ compiler?: {+ atomicStyles?: boolean | null;+ };+};++export const getProjectSettings = projectQuery(+ getPublicApiOperationPath("get-project-settings")+);++export const updateProjectSettings = projectMutationInput<+ AuthProjectParams & ProjectSettingsInput+>("update-project-settings");++export const listRedirects = projectQuery(+ getPublicApiOperationPath("list-redirects")+);++export const createRedirect = projectMutationInput<+ AuthProjectParams & {+ old: string;+ new: string;+ status?: "301" | "302";+ }+>("create-redirect");++export const updateRedirect = projectMutationInput<+ AuthProjectParams & {+ old: string;+ values: {+ old?: string;+ new?: string;+ status?: "301" | "302" | null;+ };+ }+>("update-redirect");++export const deleteRedirect = projectMutationInput<+ AuthProjectParams & {+ old: string;+ }+>("delete-redirect");++export const listBreakpoints = projectQuery(+ getPublicApiOperationPath("list-breakpoints")+);++type BreakpointInput = {+ id: string;+ label: string;+ minWidth?: number;+ maxWidth?: number;+ condition?: string;+};++type BreakpointUpdateInput = Partial<Omit<BreakpointInput, "id">>;+type NullableBreakpointUpdateInput = {+ [Key in keyof BreakpointUpdateInput]?: BreakpointUpdateInput[Key] | null;+};++export const createBreakpoint = projectMutationInput<+ AuthProjectParams & BreakpointInput+>("create-breakpoint");++export const updateBreakpoint = projectMutationInput<+ AuthProjectParams & {+ breakpointId: string;+ values: NullableBreakpointUpdateInput;+ }+>("update-breakpoint");++export const deleteBreakpoint = projectMutationInput<+ AuthProjectParams & {+ breakpointId: string;+ }+>("delete-breakpoint");++export const deletePage = projectMutationInput<+ AuthProjectParams & {+ pageId: string;+ }+>("delete-page");++export const duplicatePage = projectMutationInput<+ AuthProjectParams & {+ pageId: string;+ parentFolderId?: string;+ name?: string;+ path?: string;+ }+>("duplicate-page");++export const listPageTemplates = projectQuery(+ getPublicApiOperationPath("list-page-templates")+);++export const createPageFromTemplate = projectMutationInput<+ AuthProjectParams & {+ templateId: string;+ parentFolderId?: string;+ name: string;+ path: string;+ }+>("create-page-from-template");++export const listFolders = projectQueryInput<+ AuthProjectParams & {+ includePages?: boolean;+ }+>("list-folders");++export const createFolder = projectMutationInput<+ AuthProjectParams & {+ folderId?: string;+ name: string;+ slug: string;+ parentFolderId?: string;+ }+>("create-folder");++export const updateFolder = projectMutationInput<+ AuthProjectParams & {+ folderId: string;+ values: {+ name?: string;+ slug?: string;+ parentFolderId?: string;+ };+ }+>("update-folder");++export const deleteFolder = projectMutationInput<+ AuthProjectParams & {+ folderId: string;+ }+>("delete-folder");++export const listInstances = projectQueryInput<+ AuthProjectParams & {+ pageId?: string;+ pagePath?: string;+ rootInstanceId?: string;+ maxDepth?: number;+ topLevelOnly?: boolean;+ component?: string;+ tag?: string;+ labelContains?: string;+ }+>("list-instances");++export const inspectInstance = projectQueryInput<+ AuthProjectParams & {+ instanceId: string;+ include?: string[];+ childDepth?: number;+ }+>("inspect-instance");++export const appendInstance = projectMutationInput<+ AuthProjectParams & {+ parentInstanceId: string;+ mode?: "append" | "prepend" | "replace";+ insertIndex?: number;+ children: Array<{+ instanceId?: string;+ component?: string;+ tag: string;+ label?: string;+ text?: string;+ }>;+ }+>("append-instance");++export const moveInstance = projectMutationInput<+ AuthProjectParams & {+ moves: Array<{+ instanceId: string;+ parentInstanceId: string;+ insertIndex?: number;+ }>;+ }+>("move-instance");++export const cloneInstance = projectMutationInput<+ AuthProjectParams & {+ sourceInstanceId: string;+ targetParentInstanceId?: string;+ insertIndex?: number;+ }+>("clone-instance");++export const deleteInstance = projectMutationInput<+ AuthProjectParams & {+ instanceIds: string[];+ }+>("delete-instance");++type PropValueInput = {+ propId?: string;+ instanceId: string;+ name: string;+ type:+ | "number"+ | "string"+ | "boolean"+ | "json"+ | "asset"+ | "page"+ | "string[]"+ | "parameter"+ | "resource"+ | "expression"+ | "action"+ | "animationAction";+ value: unknown;+ required?: boolean;+};++type PropBindingInput = {+ propId?: string;+ instanceId: string;+ name: string;+ binding:+ | { type: "expression"; value: string }+ | { type: "parameter"; value: string }+ | { type: "resource"; value: string }+ | {+ type: "action";+ value: Array<{ type: "execute"; args: string[]; code: string }>;+ };+};++export const updateProps = projectMutationInput<+ AuthProjectParams & {+ updates: PropValueInput[];+ }+>("update-props");++export const deleteProps = projectMutationInput<+ AuthProjectParams & {+ deletions: Array<{ instanceId: string; name: string }>;+ }+>("delete-props");++export const bindProps = projectMutationInput<+ AuthProjectParams & {+ bindings: PropBindingInput[];+ }+>("bind-props");++export const listTexts = projectQueryInput<+ AuthProjectParams & {+ pageId?: string;+ pagePath?: string;+ instanceId?: string;+ mode?: "text" | "expression" | "all";+ contains?: string;+ maxValueLength?: number;+ }+>("list-texts");++export const updateText = projectMutationInput<+ AuthProjectParams & {+ instanceId: string;+ childIndex: number;+ text: string;+ mode?: "text" | "expression";+ }+>("update-text");++export const getStyleDeclarations = projectQueryInput<+ AuthProjectParams & {+ instanceIds?: string[];+ pageId?: string;+ pagePath?: string;+ breakpoint?: string;+ state?: string;+ property?: string;+ propertyFilter?: string;+ includeTokens?: boolean;+ }+>("get-styles");++type StyleDeclarationUpdateInput = {+ instanceId: string;+ property: string;+ value: unknown;+ breakpoint?: string;+ state?: string;+ createLocalIfMissing?: boolean;+};++type StyleDeclarationDeleteInput = {+ instanceId: string;+ property: string;+ breakpoint?: string;+ state?: string;+};++export const updateStyleDeclarations = projectMutationInput<+ AuthProjectParams & {+ updates: StyleDeclarationUpdateInput[];+ }+>("update-styles");++export const deleteStyleDeclarations = projectMutationInput<+ AuthProjectParams & {+ deletions: StyleDeclarationDeleteInput[];+ }+>("delete-styles");++export const replaceStyleValues = projectMutationInput<+ AuthProjectParams & {+ property: string;+ fromValue: unknown;+ toValue: unknown;+ pageId?: string;+ pagePath?: string;+ }+>("replace-styles");++export const listDesignTokens = projectQueryInput<+ AuthProjectParams & {+ filter?: string;+ withUsage?: boolean;+ sort?: "name" | "usage";+ }+>("list-design-tokens");++type DesignTokenStyleInput = {+ property: string;+ value: unknown;+ breakpoint?: string;+ state?: string;+};++export const createDesignTokens = projectMutationInput<+ AuthProjectParams & {+ tokens: Array<{+ tokenId?: string;+ name: string;+ styles?: Record<string, unknown>;+ declarations?: DesignTokenStyleInput[];+ }>;+ }+>("create-design-token");++export const updateDesignTokenStyles = projectMutationInput<+ AuthProjectParams & {+ designTokenId: string;+ updates: DesignTokenStyleInput[];+ }+>("update-design-token-styles");++export const deleteDesignTokenStyles = projectMutationInput<+ AuthProjectParams & {+ designTokenId: string;+ deletions: Array<Omit<StyleDeclarationDeleteInput, "instanceId">>;+ }+>("delete-design-token-styles");++export const attachDesignToken = projectMutationInput<+ AuthProjectParams & {+ designTokenId: string;+ instanceIds: string[];+ position?: "before-local" | "after-local";+ }+>("attach-design-token");++export const detachDesignToken = projectMutationInput<+ AuthProjectParams & {+ designTokenId: string;+ instanceIds: string[];+ }+>("detach-design-token");++export const extractDesignToken = projectMutationInput<+ AuthProjectParams & {+ instanceIds: string[];+ name: string;+ removeLocalProps?: string[];+ }+>("extract-design-token");++export const listCssVariables = projectQueryInput<+ AuthProjectParams & {+ filter?: string;+ withUsage?: boolean;+ }+>("list-css-variables");++export const defineCssVariables = projectMutationInput<+ AuthProjectParams & {+ vars: Record<string, string | Record<string, unknown>>;+ overwrite?: boolean;+ }+>("define-css-variable");++export const deleteCssVariables = projectConfirmedMutationInput<+ AuthProjectParams & {+ names: string[];+ force?: boolean;+ }+>("delete-css-variable");++export const rewriteCssVariableRefs = projectMutationInput<+ AuthProjectParams & {+ map: Record<string, string>;+ scopeRegex?: string;+ }+>("rewrite-css-variable-refs");++type VariableValueInput =+ | { type: "number"; value: number }+ | { type: "string"; value: string }+ | { type: "boolean"; value: boolean }+ | { type: "string[]"; value: string[] }+ | { type: "json"; value: unknown };++export const listVariables = projectQueryInput<+ AuthProjectParams & {+ scopeInstanceId?: string;+ }+>("list-variables");++export const createVariable = projectMutationInput<+ AuthProjectParams & {+ dataSourceId?: string;+ scopeInstanceId: string;+ name: string;+ value: VariableValueInput;+ }+>("create-variable");++export const updateVariable = projectMutationInput<+ AuthProjectParams & {+ dataSourceId: string;+ values: {+ scopeInstanceId?: string;+ name?: string;+ value?: VariableValueInput;+ };+ }+>("update-variable");++export const deleteVariable = projectMutationInput<+ AuthProjectParams & {+ dataSourceId: string;+ }+>("delete-variable");++type ResourceFieldsInput = {+ name: string;+ control?: "system" | "graphql";+ method: "get" | "post" | "put" | "delete";+ url: string;+ searchParams?: Array<{ name: string; value: string }>;+ headers: Array<{ name: string; value: string }>;+ body?: string;+};++export const listResources = projectQueryInput<+ AuthProjectParams & {+ scopeInstanceId?: string;+ }+>("list-resources");++export const createResource = projectMutationInput<+ AuthProjectParams & {+ resourceId?: string;+ resource: ResourceFieldsInput;+ dataSourceId?: string;+ scopeInstanceId?: string;+ dataSourceName?: string;+ }+>("create-resource");++export const updateResource = projectMutationInput<+ AuthProjectParams & {+ resourceId: string;+ values: Partial<ResourceFieldsInput>;+ dataSourceName?: string;+ scopeInstanceId?: string;+ }+>("update-resource");++export const deleteResource = projectMutationInput<+ AuthProjectParams & {+ resourceId: string;+ force?: boolean;+ }+>("delete-resource");++export const listPublishes = projectQuery(+ getPublicApiOperationPath("list-publishes")+);++export const publish = projectMutationInput<+ AuthProjectParams & {+ target: "staging" | "production";+ domains?: string[];+ message?: string;+ idempotencyKey?: string;+ }+>("publish");++export const getPublishJob = projectQueryInput<+ AuthProjectParams & { jobId: string }+>("get-publish-job");++export const unpublish = projectConfirmedMutationInput<+ AuthProjectParams & {+ target: "staging" | "production";+ domains?: string[];+ message?: string;+ idempotencyKey?: string;+ }+>("unpublish");++export const listDomains = projectQuery(+ getPublicApiOperationPath("list-domains")+);++export const createDomain = projectMutationInput<+ AuthProjectParams & { domain: string }+>("create-domain");++export const updateDomain = projectMutationInput<+ AuthProjectParams & {+ domainId: string;+ updates: { domain?: string };+ }+>("update-domain");++export const deleteDomain = projectConfirmedMutationInput<+ AuthProjectParams & { domainId: string }+>("delete-domain");++export const verifyDomain = projectMutationInput<+ AuthProjectParams & { domainId: string }+>("verify-domain");++export const listAssets = projectQueryInput<+ AuthProjectParams & {+ type?: "image" | "font";+ sort?: "name" | "size" | "createdAt" | "usage";+ withUsage?: boolean;+ cursor?: string;+ limit?: number;+ }+>("list-assets");++export const findAssetUsage = projectQueryInput<+ AuthProjectParams & {+ assetId: string;+ }+>("find-asset-usage");++export const replaceAsset = projectConfirmedMutationInput<+ AuthProjectParams & {+ fromAssetId: string;+ toAssetId: string;+ }+>("replace-asset");++export const deleteAssets = projectConfirmedMutationInput<+ AuthProjectParams & {+ assetIdsOrPrefixes: string[];+ force?: boolean;+ }+>("delete-asset");+const getUploadIdFromUrl = (uploadUrl: string | null) => {if (uploadUrl === null) {throw new Error("Project bundle upload did not return an upload URL.");@@ -302,45 +1425,79 @@ export const importProjectBundle = async (return importProjectBundleResult.parse(result);};-// For easier detecting the builder URL-const buildProjectDomainPrefix = "p-";--export const parseBuilderUrl = (urlStr: string) => {- const url = new URL(urlStr);-- const fragments = url.host.split(".");- // Regular expression to match the prefix, UUID, and any optional string after '-dot-'- const re =- /^(?<prefix>[a-z-]+)(?<uuid>[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-5][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})(-dot-(?<branch>.*))?/;- const match = fragments[0].match(re);+export const importProjectBundleWithAssets = async (+ params: AuthProjectParams & {+ data: PublishedProjectBundle;+ ignoreVersionCheck?: boolean;+ maxMissingAssetImportRetries?: number;+ onImportAttempt?: () => void;+ onMissingAssets?: (assets: Asset[]) => void;+ onUploadAssets?: (assets: Asset[]) => void;+ } & (+ | {+ skipAssets: true;+ readAssetData?: undefined;+ }+ | {+ skipAssets?: false;+ readAssetData: (asset: Asset) => Promise<BinaryAssetData>;+ }+ )+): Promise<ImportProjectBundleResult> => {+ await checkProjectBuildPermission(params);- // Extract prefix, projectId (UUID), and branch (if exists)- const prefix = match?.groups?.prefix;- const projectId = match?.groups?.uuid;- const branch = match?.groups?.branch;+ const dataToImport =+ params.skipAssets === true ? { ...params.data, assets: [] } : params.data;- if (prefix !== buildProjectDomainPrefix) {- return {- projectId: undefined,- sourceOrigin: url.origin,- };+ if (params.skipAssets !== true) {+ params.onUploadAssets?.(params.data.assets);+ await uploadAssets({+ ...params,+ assets: params.data.assets,+ readAssetData: params.readAssetData,+ });}- if (projectId === undefined) {- return {- projectId: undefined,- sourceOrigin: url.origin,- };- }+ const maxRetries = params.maxMissingAssetImportRetries ?? 5;+ for (let attempt = 0; attempt <= maxRetries; attempt += 1) {+ params.onImportAttempt?.();+ try {+ return await importProjectBundle({+ ...params,+ data: dataToImport,+ ignoreVersionCheck: params.ignoreVersionCheck,+ });+ } catch (error) {+ const missingAssetNames =+ params.skipAssets === true+ ? undefined+ : parseMissingImportedAssetFilesMessage(error);+ const assetNames = missingAssetNames ?? [];+ if (assetNames.length === 0 || attempt === maxRetries) {+ throw error;+ }- fragments[0] = fragments[0].replace(re, branch ?? "");+ const missingAssets = params.data.assets.filter((asset) =>+ assetNames.includes(asset.name)+ );+ if (missingAssets.length !== assetNames.length) {+ throw error;+ }- const sourceUrl = new URL(url.origin);- sourceUrl.protocol = "https";- sourceUrl.host = fragments.filter(Boolean).join(".");+ const readAssetData =+ params.skipAssets === true ? undefined : params.readAssetData;+ if (readAssetData === undefined) {+ throw error;+ }- return {- projectId,- sourceOrigin: sourceUrl.origin,- };+ params.onMissingAssets?.(missingAssets);+ await uploadAssets({+ ...params,+ assets: missingAssets,+ readAssetData,+ });+ }+ }++ throw new Error("Project import failed.");};diff --git a/packages/image/src/image-loader.test.ts b/packages/image/src/image-loaders.test.tssimilarity index 100%rename from packages/image/src/image-loader.test.tsrename to packages/image/src/image-loaders.test.tsdiff --git a/packages/postgrest/src/__generated__/db-types.ts b/packages/postgrest/src/__generated__/db-types.tsindex 4f3443c3e1..0b312bf3a2 100644--- a/packages/postgrest/src/__generated__/db-types.ts+++ b/packages/postgrest/src/__generated__/db-types.ts@@ -104,6 +104,7 @@ export type Database = {canClone: boolean;canCopy: boolean;canPublish: boolean;+ canUseApi: boolean;createdAt: string;name: string;projectId: string;@@ -114,6 +115,7 @@ export type Database = {canClone?: boolean;canCopy?: boolean;canPublish?: boolean;+ canUseApi?: boolean;createdAt?: string;name?: string;projectId: string;@@ -124,6 +126,7 @@ export type Database = {canClone?: boolean;canCopy?: boolean;canPublish?: boolean;+ canUseApi?: boolean;createdAt?: string;name?: string;projectId?: string;diff --git a/packages/prisma-client/prisma/migrations/20260624120000_add-token-api-permission/migration.sql b/packages/prisma-client/prisma/migrations/20260624120000_add-token-api-permission/migration.sqlnew file mode 100644index 0000000000..aea38ce9df--- /dev/null+++ b/packages/prisma-client/prisma/migrations/20260624120000_add-token-api-permission/migration.sql@@ -0,0 +1 @@+ALTER TABLE "AuthorizationToken" ADD COLUMN "canUseApi" boolean NOT NULL DEFAULT false;diff --git a/packages/prisma-client/prisma/schema.prisma b/packages/prisma-client/prisma/schema.prismaindex be8c6d80bb..de56a12022 100644--- a/packages/prisma-client/prisma/schema.prisma+++ b/packages/prisma-client/prisma/schema.prisma@@ -225,6 +225,7 @@ model AuthorizationToken {canClone Boolean @default(true)canCopy Boolean @default(true)+ canUseApi Boolean @default(false)@@id([token, projectId])@@unique([token])diff --git a/packages/project-build/package.json b/packages/project-build/package.jsonindex 64c4f3b104..44880676f1 100644--- a/packages/project-build/package.json+++ b/packages/project-build/package.json@@ -17,6 +17,136 @@"import": "./src/schema.ts","default": "./src/schema.ts"},+ "./contracts/builder-runtime": {+ "webstudio": "./src/contracts/builder-runtime.ts",+ "import": "./src/contracts/builder-runtime.ts",+ "default": "./src/contracts/builder-runtime.ts"+ },+ "./contracts/namespaces": {+ "webstudio": "./src/contracts/namespaces.ts",+ "import": "./src/contracts/namespaces.ts",+ "default": "./src/contracts/namespaces.ts"+ },+ "./contracts/patch": {+ "webstudio": "./src/contracts/patch.ts",+ "import": "./src/contracts/patch.ts",+ "default": "./src/contracts/patch.ts"+ },+ "./project-session": {+ "webstudio": "./src/project-session.ts",+ "import": "./src/project-session.ts",+ "default": "./src/project-session.ts"+ },+ "./mcp": {+ "webstudio": "./src/mcp.ts",+ "import": "./src/mcp.ts",+ "default": "./src/mcp.ts"+ },+ "./state/adapters": {+ "webstudio": "./src/state/adapters.ts",+ "import": "./src/state/adapters.ts",+ "default": "./src/state/adapters.ts"+ },+ "./state/builder-state": {+ "webstudio": "./src/state/builder-state.ts",+ "import": "./src/state/builder-state.ts",+ "default": "./src/state/builder-state.ts"+ },+ "./state/freshness": {+ "webstudio": "./src/state/freshness.ts",+ "import": "./src/state/freshness.ts",+ "default": "./src/state/freshness.ts"+ },+ "./state/patch": {+ "webstudio": "./src/state/patch.ts",+ "import": "./src/state/patch.ts",+ "default": "./src/state/patch.ts"+ },+ "./visual/screenshot-diff": {+ "webstudio": "./src/visual/screenshot-diff.ts",+ "import": "./src/visual/screenshot-diff.ts",+ "default": "./src/visual/screenshot-diff.ts"+ },+ "./visual/screenshot-browser": {+ "webstudio": "./src/visual/screenshot-browser.ts",+ "import": "./src/visual/screenshot-browser.ts",+ "default": "./src/visual/screenshot-browser.ts"+ },+ "./runtime/assets": {+ "webstudio": "./src/runtime/assets.ts",+ "import": "./src/runtime/assets.ts",+ "default": "./src/runtime/assets.ts"+ },+ "./runtime/breakpoints": {+ "webstudio": "./src/runtime/breakpoints.ts",+ "import": "./src/runtime/breakpoints.ts",+ "default": "./src/runtime/breakpoints.ts"+ },+ "./runtime/data": {+ "webstudio": "./src/runtime/data.ts",+ "import": "./src/runtime/data.ts",+ "default": "./src/runtime/data.ts"+ },+ "./runtime/errors": {+ "webstudio": "./src/runtime/errors.ts",+ "import": "./src/runtime/errors.ts",+ "default": "./src/runtime/errors.ts"+ },+ "./runtime/fragment": {+ "webstudio": "./src/runtime/fragment.ts",+ "import": "./src/runtime/fragment.ts",+ "default": "./src/runtime/fragment.ts"+ },+ "./runtime/instances": {+ "webstudio": "./src/runtime/instances.ts",+ "import": "./src/runtime/instances.ts",+ "default": "./src/runtime/instances.ts"+ },+ "./runtime/mutation": {+ "webstudio": "./src/runtime/mutation.ts",+ "import": "./src/runtime/mutation.ts",+ "default": "./src/runtime/mutation.ts"+ },+ "./runtime/page-copy": {+ "webstudio": "./src/runtime/page-copy.ts",+ "import": "./src/runtime/page-copy.ts",+ "default": "./src/runtime/page-copy.ts"+ },+ "./runtime/pages": {+ "webstudio": "./src/runtime/pages.ts",+ "import": "./src/runtime/pages.ts",+ "default": "./src/runtime/pages.ts"+ },+ "./runtime/project-settings": {+ "webstudio": "./src/runtime/project-settings.ts",+ "import": "./src/runtime/project-settings.ts",+ "default": "./src/runtime/project-settings.ts"+ },+ "./runtime/props": {+ "webstudio": "./src/runtime/props.ts",+ "import": "./src/runtime/props.ts",+ "default": "./src/runtime/props.ts"+ },+ "./runtime/registry": {+ "webstudio": "./src/runtime/registry.ts",+ "import": "./src/runtime/registry.ts",+ "default": "./src/runtime/registry.ts"+ },+ "./runtime/style-copy": {+ "webstudio": "./src/runtime/style-copy.ts",+ "import": "./src/runtime/style-copy.ts",+ "default": "./src/runtime/style-copy.ts"+ },+ "./runtime/style-utils": {+ "webstudio": "./src/runtime/style-utils.ts",+ "import": "./src/runtime/style-utils.ts",+ "default": "./src/runtime/style-utils.ts"+ },+ "./runtime/styles": {+ "webstudio": "./src/runtime/styles.ts",+ "import": "./src/runtime/styles.ts",+ "default": "./src/runtime/styles.ts"+ },"./index.server": {"webstudio": "./src/index.server.ts"},@@ -36,12 +166,18 @@"test": "vitest run"},"dependencies": {+ "@modelcontextprotocol/sdk": "^1.10.0","@webstudio-is/authorization-token": "workspace:*",+ "@webstudio-is/css-data": "workspace:*",+ "@webstudio-is/css-engine": "workspace:*","@webstudio-is/postgrest": "workspace:*","@webstudio-is/project-migrations": "workspace:*","@webstudio-is/sdk": "workspace:*","@webstudio-is/template": "workspace:*","@webstudio-is/trpc-interface": "workspace:*",+ "fast-deep-equal": "^3.1.3",+ "fast-png": "8.0.0",+ "immer": "^10.1.1","nanoid": "^5.1.5","zod": "^3.24.2"},diff --git a/packages/project-build/src/contracts/builder-runtime.test.ts b/packages/project-build/src/contracts/builder-runtime.test.tsnew file mode 100644index 0000000000..1cf103b7ea--- /dev/null+++ b/packages/project-build/src/contracts/builder-runtime.test.ts@@ -0,0 +1,105 @@+import { describe, expect, test } from "vitest";+import {+ runtimeOperationContracts,+ type RuntimeOperationId,+} from "./builder-runtime";++const knownOperationId: RuntimeOperationId = "pages.list";+void knownOperationId;+// @ts-expect-error RuntimeOperationId must stay narrowed to the catalog union.+const unknownOperationId: RuntimeOperationId = "unknown.operation";+void unknownOperationId;++describe("builder runtime operation contracts", () => {+ const getContract = (id: RuntimeOperationId) => {+ const contract = runtimeOperationContracts.find(+ (contract) => contract.id === id+ );+ if (contract === undefined) {+ throw Error(`Expected ${id} contract`);+ }+ return contract;+ };++ test("has unique operation ids", () => {+ const ids = runtimeOperationContracts.map((contract) => contract.id);+ expect(new Set(ids).size).toBe(ids.length);+ });++ test("describes reads and mutations with namespace metadata", () => {+ for (const contract of runtimeOperationContracts) {+ expect(contract.readNamespaces).toBeDefined();+ expect(contract.writeNamespaces).toBeDefined();+ expect(contract.invalidatesNamespaces).toBeDefined();++ if (contract.kind === "read") {+ expect(contract.writeNamespaces).toEqual([]);+ expect(contract.invalidatesNamespaces).toEqual([]);+ }++ if (contract.kind === "mutation") {+ expect(+ contract.writeNamespaces.length ++ contract.invalidatesNamespaces.length+ ).toBeGreaterThan(0);+ }+ }+ });++ test("includes page list contract", () => {+ expect(+ runtimeOperationContracts.find((contract) => contract.id === "pages.list")+ ?.readNamespaces+ ).toEqual(["pages"]);+ });++ test("loads full tree namespaces for mutations that can remove referenced records", () => {+ const namespaces = [+ "pages",+ "instances",+ "props",+ "dataSources",+ "resources",+ "styles",+ "styleSources",+ "styleSourceSelections",+ ];++ for (const id of [+ "pages.delete",+ "folders.delete",+ "instances.append",+ "instances.clone",+ "instances.delete",+ ] as const) {+ const contract = getContract(id);+ expect(contract.readNamespaces).toEqual(+ expect.arrayContaining(namespaces)+ );+ expect(contract.writeNamespaces).toEqual(+ expect.arrayContaining(namespaces)+ );+ }+ });++ test("loads full page-copy namespaces for page duplication", () => {+ const namespaces = [+ "pages",+ "assets",+ "dataSources",+ "resources",+ "instances",+ "props",+ "breakpoints",+ "styles",+ "styleSources",+ "styleSourceSelections",+ ];+ const contract = getContract("pages.duplicate");++ expect(contract.readNamespaces).toEqual(expect.arrayContaining(namespaces));+ expect(contract.writeNamespaces).toEqual(+ expect.arrayContaining(namespaces)+ );+ });+});diff --git a/packages/project-build/src/contracts/builder-runtime.ts b/packages/project-build/src/contracts/builder-runtime.tsnew file mode 100644index 0000000000..cda7c0066c--- /dev/null+++ b/packages/project-build/src/contracts/builder-runtime.ts@@ -0,0 +1,327 @@+import type { BuilderNamespace } from "./namespaces";++export type RuntimeOperationKind = "read" | "mutation";++export type RuntimeOperationContract = {+ id: string;+ kind: RuntimeOperationKind;+ readNamespaces: readonly BuilderNamespace[];+ writeNamespaces: readonly BuilderNamespace[];+ invalidatesNamespaces: readonly BuilderNamespace[];+ retryOnConflict: boolean;+};++const pageNamespaces = ["pages", "instances"] as const;+const instanceReadNamespaces = ["pages", "instances", "props"] as const;+const styleNamespaces = [+ "styles",+ "styleSources",+ "styleSourceSelections",+] as const;+const dataNamespaces = ["dataSources", "resources"] as const;+const treeMutationNamespaces = [+ "pages",+ "instances",+ "props",+ ...dataNamespaces,+ ...styleNamespaces,+] as const;+const assetUsageNamespaces = [+ "assets",+ "pages",+ "props",+ "styles",+ "resources",+ "dataSources",+] as const;+const pageCopyNamespaces = [+ "pages",+ "assets",+ "dataSources",+ "resources",+ "instances",+ "props",+ "breakpoints",+ "styles",+ "styleSources",+ "styleSourceSelections",+] as const;++const read = <Id extends string>(+ id: Id,+ readNamespaces: readonly BuilderNamespace[]+): RuntimeOperationContract & { id: Id } => ({+ id,+ kind: "read",+ readNamespaces,+ writeNamespaces: [],+ invalidatesNamespaces: [],+ retryOnConflict: false,+});++const mutation = <Id extends string>(+ id: Id,+ {+ readNamespaces,+ writeNamespaces,+ invalidatesNamespaces = writeNamespaces,+ retryOnConflict = false,+ }: {+ readNamespaces: readonly BuilderNamespace[];+ writeNamespaces: readonly BuilderNamespace[];+ invalidatesNamespaces?: readonly BuilderNamespace[];+ retryOnConflict?: boolean;+ }+): RuntimeOperationContract & { id: Id } => ({+ id,+ kind: "mutation",+ readNamespaces,+ writeNamespaces,+ invalidatesNamespaces,+ retryOnConflict,+});++export const runtimeOperationContracts = [+ read("pages.list", ["pages"]),+ read("pages.get", pageNamespaces),+ read("pages.getByPath", pageNamespaces),+ mutation("pages.create", {+ readNamespaces: ["pages"],+ writeNamespaces: pageNamespaces,+ }),+ mutation("pages.update", {+ readNamespaces: ["pages"],+ writeNamespaces: ["pages"],+ retryOnConflict: true,+ }),+ read("projectSettings.get", ["pages"]),+ mutation("projectSettings.update", {+ readNamespaces: ["pages"],+ writeNamespaces: ["pages"],+ retryOnConflict: true,+ }),+ read("redirects.list", ["pages"]),+ mutation("redirects.create", {+ readNamespaces: ["pages"],+ writeNamespaces: ["pages"],+ retryOnConflict: true,+ }),+ mutation("redirects.update", {+ readNamespaces: ["pages"],+ writeNamespaces: ["pages"],+ retryOnConflict: true,+ }),+ mutation("redirects.delete", {+ readNamespaces: ["pages"],+ writeNamespaces: ["pages"],+ retryOnConflict: true,+ }),+ read("breakpoints.list", ["breakpoints"]),+ mutation("breakpoints.create", {+ readNamespaces: ["breakpoints"],+ writeNamespaces: ["breakpoints"],+ retryOnConflict: true,+ }),+ mutation("breakpoints.update", {+ readNamespaces: ["breakpoints"],+ writeNamespaces: ["breakpoints"],+ retryOnConflict: true,+ }),+ mutation("breakpoints.delete", {+ readNamespaces: ["breakpoints", "styles"],+ writeNamespaces: ["breakpoints", "styles"],+ retryOnConflict: true,+ }),+ mutation("pages.delete", {+ readNamespaces: treeMutationNamespaces,+ writeNamespaces: treeMutationNamespaces,+ }),+ mutation("pages.duplicate", {+ readNamespaces: pageCopyNamespaces,+ writeNamespaces: pageCopyNamespaces,+ }),+ read("pageTemplates.list", ["pages"]),+ mutation("pageTemplates.createPage", {+ readNamespaces: pageCopyNamespaces,+ writeNamespaces: pageCopyNamespaces,+ }),+ read("folders.list", ["pages"]),+ mutation("folders.create", {+ readNamespaces: ["pages"],+ writeNamespaces: ["pages"],+ }),+ mutation("folders.update", {+ readNamespaces: ["pages"],+ writeNamespaces: ["pages"],+ retryOnConflict: true,+ }),+ mutation("folders.delete", {+ readNamespaces: treeMutationNamespaces,+ writeNamespaces: treeMutationNamespaces,+ }),+ read("instances.list", instanceReadNamespaces),+ read("instances.inspect", [+ "instances",+ "props",+ "styles",+ "styleSources",+ "styleSourceSelections",+ ]),+ mutation("instances.append", {+ readNamespaces: treeMutationNamespaces,+ writeNamespaces: treeMutationNamespaces,+ }),+ mutation("instances.move", {+ readNamespaces: ["instances"],+ writeNamespaces: ["instances"],+ }),+ mutation("instances.clone", {+ readNamespaces: treeMutationNamespaces,+ writeNamespaces: treeMutationNamespaces,+ }),+ mutation("instances.delete", {+ readNamespaces: treeMutationNamespaces,+ writeNamespaces: treeMutationNamespaces,+ }),+ mutation("instances.updateProps", {+ readNamespaces: ["instances", "props"],+ writeNamespaces: ["props"],+ }),+ mutation("instances.deleteProps", {+ readNamespaces: ["instances", "props"],+ writeNamespaces: ["props", "resources"],+ }),+ mutation("instances.bindProps", {+ readNamespaces: ["instances", "props", ...dataNamespaces],+ writeNamespaces: ["props"],+ }),+ read("instances.listTexts", ["pages", "instances"]),+ mutation("instances.updateText", {+ readNamespaces: ["instances"],+ writeNamespaces: ["instances"],+ retryOnConflict: true,+ }),+ read("styles.getDeclarations", [+ "instances",+ ...styleNamespaces,+ "breakpoints",+ ]),+ mutation("styles.updateDeclarations", {+ readNamespaces: ["instances", ...styleNamespaces, "breakpoints"],+ writeNamespaces: ["styles", "styleSources", "styleSourceSelections"],+ }),+ mutation("styles.deleteDeclarations", {+ readNamespaces: ["instances", ...styleNamespaces, "breakpoints"],+ writeNamespaces: ["styles"],+ }),+ mutation("styles.replaceValues", {+ readNamespaces: ["pages", "instances", ...styleNamespaces],+ writeNamespaces: ["styles"],+ }),+ read("designTokens.list", styleNamespaces),+ mutation("designTokens.create", {+ readNamespaces: [...styleNamespaces, "breakpoints"],+ writeNamespaces: ["styleSources", "styles"],+ }),+ mutation("designTokens.updateStyles", {+ readNamespaces: [...styleNamespaces, "breakpoints"],+ writeNamespaces: ["styles", "styleSources"],+ }),+ mutation("designTokens.deleteStyles", {+ readNamespaces: [...styleNamespaces, "breakpoints"],+ writeNamespaces: ["styles"],+ }),+ mutation("designTokens.attach", {+ readNamespaces: ["instances", ...styleNamespaces],+ writeNamespaces: ["styleSourceSelections"],+ }),+ mutation("designTokens.detach", {+ readNamespaces: ["instances", ...styleNamespaces],+ writeNamespaces: ["styleSourceSelections"],+ }),+ mutation("designTokens.extract", {+ readNamespaces: ["instances", ...styleNamespaces],+ writeNamespaces: ["styles", "styleSources", "styleSourceSelections"],+ }),+ read("cssVariables.list", [...styleNamespaces, "props"]),+ mutation("cssVariables.define", {+ readNamespaces: ["pages", ...styleNamespaces, "breakpoints"],+ writeNamespaces: ["styles", "styleSources", "styleSourceSelections"],+ }),+ mutation("cssVariables.delete", {+ readNamespaces: [...styleNamespaces, "props"],+ writeNamespaces: ["styles"],+ }),+ mutation("cssVariables.rewriteRefs", {+ readNamespaces: [...styleNamespaces, "props"],+ writeNamespaces: ["styles", "props"],+ }),+ read("variables.list", ["dataSources"]),+ mutation("variables.create", {+ readNamespaces: ["dataSources", "instances"],+ writeNamespaces: ["dataSources"],+ }),+ mutation("variables.update", {+ readNamespaces: ["dataSources"],+ writeNamespaces: ["dataSources"],+ retryOnConflict: true,+ }),+ mutation("variables.delete", {+ readNamespaces: ["pages", "instances", "props", ...dataNamespaces],+ writeNamespaces: ["pages", "instances", "props", ...dataNamespaces],+ }),+ read("resources.list", dataNamespaces),+ mutation("resources.create", {+ readNamespaces: [+ "pages",+ "instances",+ "props",+ ...dataNamespaces,+ ...styleNamespaces,+ "breakpoints",+ ],+ writeNamespaces: [+ "pages",+ "instances",+ "props",+ ...dataNamespaces,+ ...styleNamespaces,+ "breakpoints",+ ],+ }),+ mutation("resources.update", {+ readNamespaces: [+ "pages",+ "instances",+ "props",+ ...dataNamespaces,+ ...styleNamespaces,+ "breakpoints",+ ],+ writeNamespaces: [+ "pages",+ "instances",+ "props",+ ...dataNamespaces,+ ...styleNamespaces,+ "breakpoints",+ ],+ }),+ mutation("resources.delete", {+ readNamespaces: [...dataNamespaces, "props"],+ writeNamespaces: [...dataNamespaces, "props"],+ }),+ read("assets.list", assetUsageNamespaces),+ read("assets.findUsage", assetUsageNamespaces),+ mutation("assets.replace", {+ readNamespaces: assetUsageNamespaces,+ writeNamespaces: ["pages", "props", "styles", "assets"],+ }),+ mutation("assets.delete", {+ readNamespaces: assetUsageNamespaces,+ writeNamespaces: ["assets"],+ }),+] as const satisfies readonly RuntimeOperationContract[];++export type RuntimeOperationId =+ (typeof runtimeOperationContracts)[number]["id"];diff --git a/packages/project-build/src/contracts/namespaces.test.ts b/packages/project-build/src/contracts/namespaces.test.tsnew file mode 100644index 0000000000..0e850369db--- /dev/null+++ b/packages/project-build/src/contracts/namespaces.test.ts@@ -0,0 +1,18 @@+import { expect, test } from "vitest";+import { builderNamespaces } from "./namespaces";++test("defines the shared builder namespace catalog", () => {+ expect(builderNamespaces).toEqual([+ "pages",+ "instances",+ "props",+ "styles",+ "styleSources",+ "styleSourceSelections",+ "dataSources",+ "resources",+ "assets",+ "breakpoints",+ "marketplaceProduct",+ ]);+});diff --git a/packages/project-build/src/contracts/namespaces.ts b/packages/project-build/src/contracts/namespaces.tsnew file mode 100644index 0000000000..54f36fc719--- /dev/null+++ b/packages/project-build/src/contracts/namespaces.ts@@ -0,0 +1,15 @@+export const builderNamespaces = [+ "pages",+ "instances",+ "props",+ "styles",+ "styleSources",+ "styleSourceSelections",+ "dataSources",+ "resources",+ "assets",+ "breakpoints",+ "marketplaceProduct",+] as const;++export type BuilderNamespace = (typeof builderNamespaces)[number];diff --git a/packages/project-build/src/contracts/patch.test.ts b/packages/project-build/src/contracts/patch.test.tsnew file mode 100644index 0000000000..584b9c1f5d--- /dev/null+++ b/packages/project-build/src/contracts/patch.test.ts@@ -0,0 +1,83 @@+import { describe, expect, test } from "vitest";+import {+ builderPatchChangeSchema,+ builderPatchSchema,+ builderPatchTransactionSchema,+ compactBuilderPatchPayload,+} from "./patch";++describe("builder patch contracts", () => {+ test("requires values for add and replace patches", () => {+ expect(+ builderPatchSchema.safeParse({ op: "add", path: ["prop-subtitle"] })+ .success+ ).toBe(false);+ expect(+ builderPatchSchema.safeParse({ op: "replace", path: ["prop-subtitle"] })+ .success+ ).toBe(false);+ expect(+ builderPatchSchema.safeParse({+ op: "remove",+ path: ["prop-subtitle"],+ }).success+ ).toBe(true);+ });++ test("parses transactions", () => {+ const transaction = builderPatchTransactionSchema.parse({+ id: "tx-1",+ payload: [+ {+ namespace: "props",+ patches: [+ {+ op: "add",+ path: ["prop-subtitle"],+ value: {+ id: "prop-subtitle",+ instanceId: "instance-root",+ name: "Subtitle",+ type: "string",+ value: "Subtitle",+ },+ },+ ],+ },+ ],+ });++ expect(transaction.payload.map((change) => change.namespace)).toEqual([+ "props",+ ]);+ });++ test("parses patch changes", () => {+ expect(+ builderPatchChangeSchema.parse({+ namespace: "props",+ patches: [{ op: "remove", path: ["prop-title"] }],+ })+ ).toEqual({+ namespace: "props",+ patches: [{ op: "remove", path: ["prop-title"] }],+ });+ });++ test("removes empty patch changes from payload", () => {+ expect(+ compactBuilderPatchPayload([+ { namespace: "pages", patches: [] },+ {+ namespace: "props",+ patches: [{ op: "remove", path: ["prop-title"] }],+ },+ ])+ ).toEqual([+ {+ namespace: "props",+ patches: [{ op: "remove", path: ["prop-title"] }],+ },+ ]);+ });+});diff --git a/packages/project-build/src/contracts/patch.ts b/packages/project-build/src/contracts/patch.tsnew file mode 100644index 0000000000..800b0b2eca--- /dev/null+++ b/packages/project-build/src/contracts/patch.ts@@ -0,0 +1,84 @@+import { z } from "zod";+import { builderNamespaces } from "./namespaces";++const builderPatchPath = z.array(z.union([z.string(), z.number()]));++export type BuilderPatchPath = Array<string | number>;++export type BuilderPatch =+ | { op: "add"; path: BuilderPatchPath; value: unknown }+ | { op: "replace"; path: BuilderPatchPath; value: unknown }+ | { op: "remove"; path: BuilderPatchPath };++const requireBuilderPatchValue = (+ patch: { value?: unknown },+ context: z.RefinementCtx+) => {+ if (Object.hasOwn(patch, "value") === false) {+ context.addIssue({+ code: z.ZodIssueCode.custom,+ path: ["value"],+ message: "Required",+ });+ }+};++export const builderPatchSchema: z.ZodType<+ BuilderPatch,+ z.ZodTypeDef,+ unknown+> = z+ .union([+ z+ .object({+ op: z.literal("add"),+ path: builderPatchPath,+ value: z.unknown(),+ })+ .superRefine(requireBuilderPatchValue),+ z+ .object({+ op: z.literal("replace"),+ path: builderPatchPath,+ value: z.unknown(),+ })+ .superRefine(requireBuilderPatchValue),+ z.object({+ op: z.literal("remove"),+ path: builderPatchPath,+ }),+ ])+ .transform((patch): BuilderPatch => patch as BuilderPatch);++export const builderPatchChangeSchema: z.ZodType<+ BuilderPatchChange,+ z.ZodTypeDef,+ unknown+> = z.object({+ namespace: z.enum(builderNamespaces),+ patches: z.array(builderPatchSchema),+});++export const builderPatchTransactionSchema: z.ZodType<+ BuilderPatchTransaction,+ z.ZodTypeDef,+ unknown+> = z.object({+ id: z.string().min(1),+ payload: z.array(builderPatchChangeSchema),+});++export type BuilderPatchChange = {+ namespace: (typeof builderNamespaces)[number];+ patches: BuilderPatch[];+};++export type BuilderPatchTransaction = {+ id: string;+ payload: BuilderPatchChange[];+};++export const compactBuilderPatchPayload = (+ payload: BuilderPatchChange[]+): BuilderPatchChange[] =>+ payload.flatMap((change) => (change.patches.length === 0 ? [] : [change]));diff --git a/packages/project-build/src/db/build.test.ts b/packages/project-build/src/db/build.test.tsindex 1214f682cb..21ef06daab 100644--- a/packages/project-build/src/db/build.test.ts+++ b/packages/project-build/src/db/build.test.ts@@ -176,6 +176,7 @@ describe("canTokenPublishDeployment", () => {canClone: true,canCopy: true,canPublish: false,+ canUseApi: false,};test("allows builder tokens to publish to the staging domain", () => {diff --git a/packages/project-build/src/index.server.ts b/packages/project-build/src/index.server.tsindex ce1e7e0568..ee4c7647fe 100644--- a/packages/project-build/src/index.server.ts+++ b/packages/project-build/src/index.server.ts@@ -1,4 +1,5 @@export * from "./db/build";+export * from "./db/deployment";export * from "./db/pages";export * from "./db/styles";export * from "./db/style-source-selections";diff --git a/packages/project-build/src/mcp.test.ts b/packages/project-build/src/mcp.test.tsnew file mode 100644index 0000000000..ea7704c824--- /dev/null+++ b/packages/project-build/src/mcp.test.ts@@ -0,0 +1,1419 @@+import { mkdtemp, rm } from "node:fs/promises";+import { tmpdir } from "node:os";+import path from "node:path";+import { Client } from "@modelcontextprotocol/sdk/client/index.js";+import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";+import { describe, expect, test, vi } from "vitest";+import {+ createProjectSessionMcpCore,+ createProjectSessionMcpServer,+ listProjectSessionMcpResources,+ listProjectSessionMcpTools,+ type PublicMcpOperation,+ type ProjectSessionMcpGuidance,+} from "./mcp";+import type { ProjectSessionEnvelope } from "./project-session";+import { diffPngFiles } from "./visual/screenshot-diff";+import { createPng, paintRect, writePng } from "./visual/screenshot.test-utils";++type CreateProjectSession = NonNullable<+ Parameters<typeof createProjectSessionMcpCore>[0]["createProjectSession"]+>;++type ExecuteOperation = NonNullable<+ Parameters<typeof createProjectSessionMcpCore>[0]["executeOperation"]+>;++type TestSession = ReturnType<CreateProjectSession>;++const publicMcpOperations: readonly PublicMcpOperation[] = [+ {+ command: "list-pages",+ id: "pages.list",+ method: "query",+ permit: "view",+ description: "List pages",+ inputFields: ["includeFolders"],+ localCapable: true,+ serverOnly: false,+ readNamespaces: ["pages"],+ writeNamespaces: [],+ invalidatesNamespaces: [],+ retryOnConflict: false,+ },+ {+ command: "whoami",+ id: "auth.me",+ method: "query",+ permit: "view",+ description: "Identify token",+ inputFields: [],+ localCapable: false,+ serverOnly: true,+ readNamespaces: [],+ writeNamespaces: [],+ invalidatesNamespaces: [],+ retryOnConflict: false,+ },+ {+ command: "publish",+ id: "build.publish",+ method: "mutation",+ permit: "build",+ description: "Publish project",+ inputFields: ["target", "domains"],+ localCapable: false,+ serverOnly: true,+ readNamespaces: [],+ writeNamespaces: [],+ invalidatesNamespaces: [],+ retryOnConflict: false,+ },+];++const testMcpGuidance: ProjectSessionMcpGuidance = {+ visualVerificationRule:+ "Verify rendered visual/design work before finishing.",+ getVisionVerificationLoop: ({ includeDiff }) =>+ [+ "Make focused changes.",+ "Start preview.",+ "Install dependencies if missing.",+ 'Call screenshot with { path: "/" } or the changed page path.',+ includeDiff ? "Use screenshot.diff when a baseline exists." : undefined,+ "Inspect the PNG with vision.",+ ].filter((step): step is string => step !== undefined),+ getVisionWorkflowSummary: ({ includeDiff }) =>+ includeDiff+ ? "Visual workflow with screenshot diff."+ : "Visual workflow without screenshot diff.",+};++const tesseractInstallUrl =+ "https://tesseract-ocr.github.io/tessdoc/Installation.html";++const createEnvelope = (+ overrides: Partial<ProjectSessionEnvelope> & {+ operationId: string;+ result: unknown;+ }+): ProjectSessionEnvelope => ({+ projectId: "project-1",+ buildId: "build-1",+ version: 1,+ source: "local",+ state: { committed: false, freshness: {} },+ namespaces: {+ read: [],+ write: [],+ invalidated: [],+ missing: [],+ },+ diagnostics: [],+ ...overrides,+});++const createSession = (overrides: Partial<TestSession> = {}): TestSession => ({+ initialize: vi.fn(async () =>+ createEnvelope({+ operationId: "project-session.status",+ result: { loaded: true },+ })+ ),+ refresh: vi.fn(async () =>+ createEnvelope({+ operationId: "project-session.refresh",+ result: { refreshedNamespaces: [] },+ })+ ),+ reset: vi.fn(async () =>+ createEnvelope({+ operationId: "project-session.reset",+ result: { loaded: false },+ })+ ),+ ...overrides,+});++const createSessionFactory = (session = createSession()) =>+ vi.fn(() => session) as CreateProjectSession;++const createExecuteOperation = (+ implementation: ExecuteOperation = async () =>+ createEnvelope({+ operationId: "test.operation",+ result: undefined,+ })+): ExecuteOperation => vi.fn(implementation);++const createConnectedClient = async (+ server: Awaited<ReturnType<typeof createProjectSessionMcpServer>>+) => {+ const [clientTransport, serverTransport] =+ InMemoryTransport.createLinkedPair();+ const client = new Client({ name: "test-client", version: "1.0.0" });+ await Promise.all([+ server.connect(serverTransport),+ client.connect(clientTransport),+ ]);+ return {+ client,+ close: async () => {+ await client.close();+ await server.close();+ },+ };+};++describe("project session mcp adapter", () => {+ test("lists tools from the public operation catalog", () => {+ const tools = listProjectSessionMcpTools(publicMcpOperations);++ expect(tools.map((tool) => tool.name)).toEqual([+ ...publicMcpOperations.map((operation) => operation.command),+ "meta.index",+ "meta.guide",+ "meta.get_more_tools",+ "status",+ "refresh",+ "reset-session",+ ]);+ expect(tools).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ name: "list-pages",+ inputSchema: expect.objectContaining({+ properties: {+ includeFolders: {+ description: "Public API input field `includeFolders`.",+ },+ },+ }),+ annotations: expect.objectContaining({+ operationId: "pages.list",+ inputFields: ["includeFolders"],+ localCapable: true,+ serverOnly: false,+ readNamespaces: ["pages"],+ }),+ }),+ expect.objectContaining({+ name: "whoami",+ annotations: expect.objectContaining({+ operationId: "auth.me",+ localCapable: false,+ serverOnly: true,+ }),+ }),+ expect.objectContaining({+ name: "meta.index",+ annotations: expect.objectContaining({+ operationId: "meta.index",+ localCapable: true,+ }),+ }),+ expect.objectContaining({+ name: "refresh",+ inputSchema: expect.objectContaining({+ properties: expect.objectContaining({+ namespaces: expect.objectContaining({+ type: "array",+ }),+ }),+ }),+ annotations: expect.objectContaining({+ operationId: "project-session.refresh",+ localCapable: true,+ }),+ }),+ expect.objectContaining({+ name: "reset-session",+ annotations: expect.objectContaining({+ operationId: "project-session.reset",+ }),+ }),+ ])+ );+ });++ test("lists OCR installer only when host provides installer", () => {+ expect(+ listProjectSessionMcpTools(publicMcpOperations).map((tool) => tool.name)+ ).not.toContain("vision.install-ocr");+ expect(+ listProjectSessionMcpTools(publicMcpOperations, {+ includeInstallOcr: true,+ }).map((tool) => tool.name)+ ).toContain("vision.install-ocr");+ });++ test("does not expose CLI-only required options as MCP tool schemas", () => {+ const operationWithCliOptions = {+ ...publicMcpOperations[0]!,+ requiredOptions: ["page", "base-version", "json"],+ };++ expect(listProjectSessionMcpTools([operationWithCliOptions])).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ name: "list-pages",+ inputSchema: {+ type: "object",+ description:+ "Pass the public API input object for this tool. Use meta.get_more_tools for examples and required fields.",+ additionalProperties: true,+ properties: {+ includeFolders: {+ description: "Public API input field `includeFolders`.",+ },+ },+ },+ }),+ ])+ );+ });++ test("lists MCP resources for project status and tool catalog", () => {+ expect(listProjectSessionMcpResources()).toEqual([+ expect.objectContaining({ uri: "webstudio://project/status" }),+ expect.objectContaining({ uri: "webstudio://project/tools" }),+ expect.objectContaining({ uri: "webstudio://project/guide" }),+ ]);+ });++ test("calls tools through project session operation executor", async () => {+ const executeOperation: ExecuteOperation = vi.fn(async () =>+ createEnvelope({+ operationId: "pages.list",+ result: [{ id: "home" }],+ namespaces: {+ read: ["pages"],+ write: [],+ invalidated: [],+ missing: [],+ },+ })+ );+ const adapter = createProjectSessionMcpCore({+ operations: publicMcpOperations,+ createProjectSession: createSessionFactory(),+ executeOperation,+ });++ const result = await adapter.callTool({+ name: "list-pages",+ input: { includeFolders: true },+ });++ expect(executeOperation).toHaveBeenCalledWith({+ command: "list-pages",+ input: { includeFolders: true },+ dryRun: false,+ });+ expect(result.structuredContent).toEqual({+ ok: true,+ data: [{ id: "home" }],+ meta: {+ session: expect.objectContaining({+ operationId: "pages.list",+ source: "local",+ }),+ },+ });+ });++ test("delegates catalog operation tools without creating core session", async () => {+ const createProjectSession = createSessionFactory();+ const executeOperation: ExecuteOperation = vi.fn(async () =>+ createEnvelope({+ operationId: "pages.list",+ result: [],+ namespaces: {+ read: ["pages"],+ write: [],+ invalidated: [],+ missing: [],+ },+ })+ );+ const adapter = createProjectSessionMcpCore({+ operations: publicMcpOperations,+ createProjectSession,+ executeOperation,+ });++ await adapter.callTool({ name: "list-pages" });+ await adapter.callTool({ name: "list-pages" });++ expect(createProjectSession).not.toHaveBeenCalled();+ expect(executeOperation).toHaveBeenCalledTimes(2);+ });++ test("calls project session management tools directly", async () => {+ const session = createSession({+ initialize: vi.fn(async () =>+ createEnvelope({+ operationId: "project-session.status",+ result: { loaded: true },+ })+ ),+ refresh: vi.fn(async () =>+ createEnvelope({+ operationId: "project-session.refresh",+ version: 2,+ source: "remote",+ result: { refreshedNamespaces: ["pages"] },+ namespaces: {+ read: ["pages"],+ write: [],+ invalidated: [],+ missing: [],+ },+ })+ ),+ reset: vi.fn(async () =>+ createEnvelope({+ operationId: "project-session.reset",+ buildId: undefined,+ version: undefined,+ result: { loaded: false },+ })+ ),+ });+ const adapter = createProjectSessionMcpCore({+ operations: publicMcpOperations,+ createProjectSession: createSessionFactory(session),+ executeOperation: createExecuteOperation(),+ });++ const status = await adapter.callTool({ name: "status" });+ const refresh = await adapter.callTool({+ name: "refresh",+ input: { namespaces: ["pages"] },+ });+ expect(session.initialize).toHaveBeenCalledTimes(2);+ const reset = await adapter.callTool({ name: "reset-session" });++ expect(status.structuredContent.data).toEqual({ loaded: true });+ expect(session.initialize).toHaveBeenCalledTimes(2);+ expect(session.refresh).toHaveBeenCalledWith(["pages"]);+ expect(refresh.structuredContent.meta.session).toEqual(+ expect.objectContaining({ operationId: "project-session.refresh" })+ );+ expect(reset.structuredContent.meta.session).toEqual(+ expect.objectContaining({ operationId: "project-session.reset" })+ );+ });++ test("calls meta tools without initializing project session", async () => {+ const session = createSession({+ initialize: vi.fn(),+ refresh: vi.fn(),+ reset: vi.fn(),+ });+ const adapter = createProjectSessionMcpCore({+ operations: publicMcpOperations,+ createProjectSession: createSessionFactory(session),+ executeOperation: createExecuteOperation(),+ });++ const index = await adapter.callTool({ name: "meta.index" });+ const guide = await adapter.callTool({+ name: "meta.guide",+ input: { brief: "publish a site" },+ });+ const details = await adapter.callTool({+ name: "meta.get_more_tools",+ input: { brief: "build.publish" },+ });++ expect(session.initialize).not.toHaveBeenCalled();+ expect(index.structuredContent.data).toEqual(+ expect.objectContaining({+ startHere: expect.arrayContaining(["meta.guide"]),+ capabilities: expect.arrayContaining([+ expect.objectContaining({+ area: "publish",+ tools: ["publish"],+ }),+ ]),+ })+ );+ expect(index.structuredContent.data).not.toEqual(+ expect.objectContaining({+ capabilities: expect.arrayContaining([+ expect.objectContaining({+ tools: expect.arrayContaining(["create-page"]),+ }),+ ]),+ })+ );+ expect(guide.structuredContent.data).toEqual(+ expect.objectContaining({+ tools: expect.arrayContaining([+ expect.objectContaining({ name: "publish" }),+ ]),+ })+ );+ expect(guide.structuredContent.data).toEqual(+ expect.objectContaining({+ tools: expect.arrayContaining([+ expect.objectContaining({+ name: "publish",+ mcpExamples: [{ target: "production" }],+ }),+ ]),+ })+ );+ expect(details.structuredContent.data).toEqual(+ expect.objectContaining({+ tools: expect.arrayContaining([+ expect.objectContaining({+ name: "publish",+ inputSchema: expect.any(Object),+ inputFields: ["target", "domains"],+ mcpExamples: [{ target: "production" }],+ cliExamples: [],+ inputNote:+ "MCP tool arguments are public API input objects. Examples show intent, but do not imply MCP flag names.",+ }),+ ]),+ })+ );+ });++ test("exposes screenshot tools only when screenshot runners are injected", async () => {+ const session = createSession({+ initialize: vi.fn(),+ refresh: vi.fn(),+ reset: vi.fn(),+ });+ const captureScreenshot = vi.fn(async () => ({+ output: "/tmp/current.png",+ browserPath: "/usr/bin/chromium",+ browser: "chromium" as const,+ viewport: { width: 1440, height: 900 },+ elapsedMs: 12,+ warnings: [],+ }));+ const adapterWithoutScreenshot = createProjectSessionMcpCore({+ operations: publicMcpOperations,+ createProjectSession: createSessionFactory(session),+ executeOperation: createExecuteOperation(),+ });+ const adapterWithScreenshot = createProjectSessionMcpCore({+ operations: publicMcpOperations,+ createProjectSession: createSessionFactory(session),+ executeOperation: createExecuteOperation(),+ captureScreenshot,+ });+ const adapterWithScreenshotDiff = createProjectSessionMcpCore({+ operations: publicMcpOperations,+ createProjectSession: createSessionFactory(session),+ executeOperation: createExecuteOperation(),+ diffScreenshots: diffPngFiles,+ });++ expect(+ adapterWithoutScreenshot.listTools().map((tool) => tool.name)+ ).not.toContain("screenshot");+ expect(+ adapterWithoutScreenshot.listTools().map((tool) => tool.name)+ ).not.toContain("screenshot.diff");+ expect(+ adapterWithScreenshot.listTools().map((tool) => tool.name)+ ).toContain("screenshot");+ expect(+ adapterWithScreenshot.listTools().map((tool) => tool.name)+ ).not.toContain("screenshot.diff");+ expect(+ adapterWithScreenshotDiff.listTools().map((tool) => tool.name)+ ).toContain("screenshot.diff");++ const result = await adapterWithScreenshot.callTool({+ name: "screenshot",+ input: {+ url: "https://example.com",+ output: "current.png",+ viewport: { width: 1440, height: 900 },+ browser: "auto",+ waitUntil: "networkidle",+ waitForSelector: "#ready",+ waitForTimeout: 500,+ timeout: 10_000,+ },+ });++ expect(session.initialize).not.toHaveBeenCalled();+ expect(captureScreenshot).toHaveBeenCalledWith({+ url: "https://example.com",+ path: undefined,+ output: "current.png",+ viewport: { width: 1440, height: 900 },+ browser: "auto",+ browserPath: undefined,+ waitUntil: "networkidle",+ waitForSelector: "#ready",+ waitForTimeout: 500,+ timeout: 10_000,+ });+ expect(result.structuredContent).toEqual({+ ok: true,+ data: {+ output: "/tmp/current.png",+ browserPath: "/usr/bin/chromium",+ browser: "chromium",+ viewport: { width: 1440, height: 900 },+ elapsedMs: 12,+ warnings: [],+ },+ meta: {},+ });+ });++ test("omits screenshot diff guidance when diff runner is not injected", async () => {+ const adapter = createProjectSessionMcpCore({+ operations: publicMcpOperations,+ createProjectSession: createSessionFactory(),+ executeOperation: createExecuteOperation(),+ captureScreenshot: vi.fn(async () => ({+ output: "/tmp/current.png",+ browserPath: "/usr/bin/chromium",+ browser: "chromium" as const,+ viewport: { width: 1440, height: 900 },+ elapsedMs: 12,+ warnings: [],+ })),+ startPreview: vi.fn(async () => ({+ url: "http://127.0.0.1:5173/",+ running: true,+ })),+ getPreviewStatus: vi.fn(async () => ({+ url: "http://127.0.0.1:5173/",+ running: true,+ })),+ guidance: testMcpGuidance,+ });++ const index = await adapter.callTool({ name: "meta.index" });+ const guide = await adapter.callTool({+ name: "meta.guide",+ input: { brief: "visual verification" },+ });++ expect(index.structuredContent.data).toEqual(+ expect.objectContaining({+ visionLoop: expect.not.arrayContaining([+ expect.stringContaining("screenshot.diff"),+ ]),+ })+ );+ expect(guide.structuredContent.data).toEqual(+ expect.objectContaining({+ workflow: expect.arrayContaining([+ testMcpGuidance.getVisionWorkflowSummary({ includeDiff: false }),+ ]),+ })+ );+ expect(guide.content[0].text).not.toContain("screenshot.diff");+ });++ test("rejects unsupported screenshot browser input", async () => {+ const adapter = createProjectSessionMcpCore({+ operations: publicMcpOperations,+ createProjectSession: createSessionFactory(),+ executeOperation: createExecuteOperation(),+ captureScreenshot: vi.fn(),+ });++ await expect(+ adapter.callTool({+ name: "screenshot",+ input: {+ url: "https://example.com",+ browser: "firefox",+ },+ })+ ).rejects.toThrow(+ "screenshot browser must be auto, chromium, chrome, edge, or brave."+ );+ });++ test("rejects invalid screenshot readiness input", async () => {+ const adapter = createProjectSessionMcpCore({+ operations: publicMcpOperations,+ createProjectSession: createSessionFactory(),+ executeOperation: createExecuteOperation(),+ captureScreenshot: vi.fn(),+ });++ await expect(+ adapter.callTool({+ name: "screenshot",+ input: {+ url: "https://example.com",+ waitUntil: "interactive",+ },+ })+ ).rejects.toThrow(+ "screenshot waitUntil must be commit, domcontentloaded, load, or networkidle."+ );++ await expect(+ adapter.callTool({+ name: "screenshot",+ input: {+ url: "https://example.com",+ waitForTimeout: -1,+ },+ })+ ).rejects.toThrow(+ "screenshot waitForTimeout must be a non-negative integer."+ );++ await expect(+ adapter.callTool({+ name: "screenshot",+ input: {+ url: "https://example.com",+ waitForTimeout: "500",+ },+ })+ ).rejects.toThrow(+ "screenshot waitForTimeout must be a non-negative integer."+ );++ await expect(+ adapter.callTool({+ name: "screenshot",+ input: {+ url: "https://example.com",+ waitForSelector: "",+ },+ })+ ).rejects.toThrow("screenshot waitForSelector must be a non-empty string.");++ await expect(+ adapter.callTool({+ name: "screenshot",+ input: {+ url: "https://example.com",+ waitForSelector: 1,+ },+ })+ ).rejects.toThrow("screenshot waitForSelector must be a non-empty string.");++ await expect(+ adapter.callTool({+ name: "screenshot",+ input: {+ url: "https://example.com",+ timeout: 0,+ },+ })+ ).rejects.toThrow("screenshot timeout must be a positive integer.");++ await expect(+ adapter.callTool({+ name: "screenshot",+ input: {+ url: "https://example.com",+ timeout: "10000",+ },+ })+ ).rejects.toThrow("screenshot timeout must be a positive integer.");+ });++ test("rejects empty screenshot url and path input", async () => {+ const adapter = createProjectSessionMcpCore({+ operations: publicMcpOperations,+ createProjectSession: createSessionFactory(),+ executeOperation: createExecuteOperation(),+ captureScreenshot: vi.fn(),+ });++ await expect(+ adapter.callTool({+ name: "screenshot",+ input: {+ url: "",+ },+ })+ ).rejects.toThrow("screenshot requires url or path.");++ await expect(+ adapter.callTool({+ name: "screenshot",+ input: {+ path: "",+ },+ })+ ).rejects.toThrow("screenshot requires url or path.");+ });++ test("compares screenshot diffs with generated PNG files", async () => {+ const tempDir = await mkdtemp(path.join(tmpdir(), "webstudio-mcp-diff-"));+ try {+ const baselinePath = path.join(tempDir, "baseline.png");+ const currentPath = path.join(tempDir, "current.png");+ const outputDir = path.join(tempDir, "diff");+ await writePng(baselinePath, createPng(4, 4, { r: 255, g: 255, b: 255 }));+ const current = createPng(4, 4, { r: 255, g: 255, b: 255 });+ paintRect(+ current,+ { x: 1, y: 1, width: 2, height: 1 },+ { r: 0, g: 0, b: 0 }+ );+ await writePng(currentPath, current);+ const adapter = createProjectSessionMcpCore({+ operations: publicMcpOperations,+ createProjectSession: createSessionFactory(),+ executeOperation: createExecuteOperation(),+ diffScreenshots: diffPngFiles,+ });++ const result = await adapter.callTool({+ name: "screenshot.diff",+ input: {+ baselinePath,+ currentPath,+ outputDir,+ },+ });++ expect(result.structuredContent.data).toEqual(+ expect.objectContaining({+ totalPixels: 16,+ differentPixels: 2,+ mismatchPercentage: 12.5,+ regions: [+ expect.objectContaining({+ bounds: { x: 1, y: 1, width: 2, height: 1 },+ pixelCount: 2,+ }),+ ],+ summary: expect.stringContaining("status: changed"),+ diffPath: path.join(outputDir, "current-diff.png"),+ contextDiffPath: path.join(outputDir, "current-context-diff.png"),+ })+ );+ } finally {+ await rm(tempDir, { recursive: true, force: true });+ }+ });++ test("rejects invalid screenshot diff input", async () => {+ const adapter = createProjectSessionMcpCore({+ operations: publicMcpOperations,+ createProjectSession: createSessionFactory(),+ executeOperation: createExecuteOperation(),+ diffScreenshots: diffPngFiles,+ });++ await expect(+ adapter.callTool({+ name: "screenshot.diff",+ input: { baselinePath: "baseline.png" },+ })+ ).rejects.toThrow("screenshot.diff requires baselinePath and currentPath.");+ await expect(+ adapter.callTool({+ name: "screenshot.diff",+ input: {+ baselinePath: "baseline.png",+ currentPath: "current.png",+ threshold: 2,+ },+ })+ ).rejects.toThrow("screenshot.diff threshold must be between 0 and 1.");+ });++ test("installs OCR only after explicit confirmation", async () => {+ const installOcr = vi.fn(async () => ({+ installed: true,+ alreadyAvailable: false,+ command: "sudo apt install -y tesseract-ocr",+ tesseractPath: "/usr/bin/tesseract",+ installUrl: tesseractInstallUrl,+ warnings: [],+ }));+ const adapter = createProjectSessionMcpCore({+ operations: publicMcpOperations,+ createProjectSession: createSessionFactory(),+ executeOperation: createExecuteOperation(),+ installOcr,+ });++ await expect(+ adapter.callTool({ name: "vision.install-ocr", input: {} })+ ).rejects.toThrow(+ "vision.install-ocr requires confirm: true after explicit user consent."+ );+ await expect(+ adapter.callTool({+ name: "vision.install-ocr",+ input: { confirm: true },+ })+ ).resolves.toEqual(+ expect.objectContaining({+ structuredContent: expect.objectContaining({+ data: expect.objectContaining({+ installed: true,+ tesseractPath: "/usr/bin/tesseract",+ }),+ }),+ })+ );+ expect(installOcr).toHaveBeenCalledOnce();+ });++ test("exposes preview tools when preview runner is injected", async () => {+ const captureScreenshot = vi.fn(async () => ({+ output: "/tmp/current.png",+ browserPath: "/usr/bin/chromium",+ browser: "chromium" as const,+ viewport: { width: 1440, height: 900 },+ elapsedMs: 12,+ warnings: [],+ }));+ const startPreview = vi.fn(async () => ({+ url: "http://127.0.0.1:5173/",+ pid: 123,+ running: true,+ }));+ const getPreviewStatus = vi.fn(async () => ({+ url: "http://127.0.0.1:5173/",+ pid: 123,+ running: true,+ }));+ const adapter = createProjectSessionMcpCore({+ operations: publicMcpOperations,+ createProjectSession: createSessionFactory(),+ executeOperation: createExecuteOperation(),+ captureScreenshot,+ diffScreenshots: diffPngFiles,+ startPreview,+ getPreviewStatus,+ guidance: testMcpGuidance,+ });++ expect(adapter.listTools().map((tool) => tool.name)).toEqual(+ expect.arrayContaining(["preview.start", "preview.status"])+ );++ const started = await adapter.callTool({+ name: "preview.start",+ input: { host: "127.0.0.1", port: 5173 },+ });+ const status = await adapter.callTool({ name: "preview.status" });+ const index = await adapter.callTool({ name: "meta.index" });+ const guide = await adapter.callTool({+ name: "meta.guide",+ input: { brief: "visual verification" },+ });++ expect(startPreview).toHaveBeenCalledWith({+ host: "127.0.0.1",+ port: 5173,+ });+ expect(getPreviewStatus).toHaveBeenCalledOnce();+ expect(started.structuredContent.data).toEqual({+ url: "http://127.0.0.1:5173/",+ pid: 123,+ running: true,+ });+ expect(status.structuredContent.data).toEqual({+ url: "http://127.0.0.1:5173/",+ pid: 123,+ running: true,+ });+ expect(index.structuredContent.data).toEqual(+ expect.objectContaining({+ visionLoop: expect.arrayContaining([+ ...testMcpGuidance+ .getVisionVerificationLoop({ includeDiff: true })+ .slice(1, 3),+ 'Call screenshot with { path: "/" } or the changed page path.',+ ]),+ capabilities: expect.arrayContaining([+ expect.objectContaining({+ area: "visual-verification",+ tools: [+ "preview.start",+ "preview.status",+ "screenshot",+ "screenshot.diff",+ ],+ }),+ ]),+ })+ );+ expect(guide.structuredContent.data).toEqual(+ expect.objectContaining({+ workflow: expect.arrayContaining([+ testMcpGuidance.getVisionWorkflowSummary({ includeDiff: true }),+ ]),+ tools: expect.arrayContaining([+ expect.objectContaining({ name: "preview.start" }),+ expect.objectContaining({ name: "screenshot" }),+ ]),+ })+ );+ });++ test("does not include visual guidance without host-provided docs", async () => {+ const adapter = createProjectSessionMcpCore({+ operations: publicMcpOperations,+ createProjectSession: createSessionFactory(),+ executeOperation: createExecuteOperation(),+ captureScreenshot: vi.fn(),+ startPreview: vi.fn(),+ getPreviewStatus: vi.fn(),+ });++ const index = await adapter.callTool({ name: "meta.index" });+ const guide = await adapter.callTool({+ name: "meta.guide",+ input: { brief: "visual verification" },+ });++ expect(index.structuredContent.data).toEqual(+ expect.objectContaining({ visionLoop: [] })+ );+ expect(+ (guide.structuredContent.data as { workflow: string[] }).workflow+ ).not.toContain(+ testMcpGuidance.getVisionWorkflowSummary({ includeDiff: false })+ );+ });++ test("rejects invalid preview ports", async () => {+ const adapter = createProjectSessionMcpCore({+ operations: publicMcpOperations,+ createProjectSession: createSessionFactory(),+ executeOperation: createExecuteOperation(),+ startPreview: vi.fn(),+ getPreviewStatus: vi.fn(),+ });++ await expect(+ adapter.callTool({+ name: "preview.start",+ input: { port: 70000 },+ })+ ).rejects.toThrow("preview port must be an integer between 1 and 65535.");+ });++ test("rejects empty preview host", async () => {+ const adapter = createProjectSessionMcpCore({+ operations: publicMcpOperations,+ createProjectSession: createSessionFactory(),+ executeOperation: createExecuteOperation(),+ startPreview: vi.fn(),+ getPreviewStatus: vi.fn(),+ });++ await expect(+ adapter.callTool({+ name: "preview.start",+ input: { host: "" },+ })+ ).rejects.toThrow("preview host must not be empty.");+ });++ test("uses discovery tools when meta guide has no brief", async () => {+ const session = createSession({+ initialize: vi.fn(),+ refresh: vi.fn(),+ reset: vi.fn(),+ });+ const adapter = createProjectSessionMcpCore({+ operations: publicMcpOperations,+ createProjectSession: createSessionFactory(session),+ executeOperation: createExecuteOperation(),+ });++ const guide = await adapter.callTool({ name: "meta.guide" });++ expect(session.initialize).not.toHaveBeenCalled();+ expect(guide.structuredContent.data).toEqual(+ expect.objectContaining({+ tools: expect.arrayContaining([+ expect.objectContaining({ name: "status" }),+ expect.objectContaining({ name: "whoami" }),+ ]),+ })+ );+ });++ test("rejects unknown tools before calling the operation executor", async () => {+ const createProjectSession = createSessionFactory();+ const executeOperation = createExecuteOperation();+ const adapter = createProjectSessionMcpCore({+ operations: publicMcpOperations,+ createProjectSession,+ executeOperation,+ });++ await expect(adapter.callTool({ name: "unknown-tool" })).rejects.toThrow(+ 'Unknown MCP tool "unknown-tool".'+ );+ expect(createProjectSession).not.toHaveBeenCalled();+ expect(executeOperation).not.toHaveBeenCalled();+ });++ test("reads MCP resources from the long-lived project session", async () => {+ const session = createSession({+ initialize: vi.fn(async () =>+ createEnvelope({+ operationId: "project-session.status",+ result: { loaded: true },+ })+ ),+ refresh: vi.fn(),+ reset: vi.fn(),+ });+ const adapter = createProjectSessionMcpCore({+ operations: publicMcpOperations,+ createProjectSession: createSessionFactory(session),+ executeOperation: createExecuteOperation(),+ });++ const status = await adapter.readResource({+ uri: "webstudio://project/status",+ });+ const tools = await adapter.readResource({+ uri: "webstudio://project/tools",+ });+ const guide = await adapter.readResource({+ uri: "webstudio://project/guide",+ });++ expect(JSON.parse(status.contents[0]?.text ?? "{}")).toEqual(+ expect.objectContaining({+ data: { loaded: true },+ meta: expect.objectContaining({+ session: expect.objectContaining({+ operationId: "project-session.status",+ }),+ }),+ })+ );+ expect(JSON.parse(tools.contents[0]?.text ?? "{}")).toEqual(+ expect.objectContaining({ tools: expect.any(Array) })+ );+ expect(JSON.parse(guide.contents[0]?.text ?? "{}")).toEqual(+ expect.objectContaining({+ startHere: expect.arrayContaining(["meta.index"]),+ })+ );+ });++ test("connects through the official MCP SDK and exposes discovery", async () => {+ const server = await createProjectSessionMcpServer({+ operations: publicMcpOperations,+ createProjectSession: createSessionFactory(),+ executeOperation: createExecuteOperation(),+ });+ const { client, close } = await createConnectedClient(server);++ try {+ expect(client.getServerCapabilities()).toEqual({+ tools: {},+ resources: {},+ });+ expect(client.getServerVersion()).toEqual({+ name: "webstudio",+ version: "0.0.0",+ });+ await expect(client.listTools()).resolves.toEqual({+ tools: expect.arrayContaining([+ expect.objectContaining({+ name: "list-pages",+ annotations: expect.objectContaining({+ readOnlyHint: true,+ destructiveHint: false,+ }),+ _meta: {+ webstudio: expect.objectContaining({+ operationId: "pages.list",+ }),+ },+ }),+ expect.objectContaining({+ name: "publish",+ annotations: expect.objectContaining({+ readOnlyHint: false,+ destructiveHint: true,+ openWorldHint: true,+ }),+ }),+ expect.objectContaining({+ name: "meta.index",+ annotations: expect.objectContaining({+ readOnlyHint: true,+ destructiveHint: false,+ }),+ }),+ expect.objectContaining({+ name: "refresh",+ annotations: expect.objectContaining({+ readOnlyHint: false,+ destructiveHint: false,+ }),+ }),+ expect.objectContaining({+ name: "reset-session",+ annotations: expect.objectContaining({+ readOnlyHint: false,+ destructiveHint: true,+ }),+ }),+ ]),+ });+ await expect(client.listResources()).resolves.toEqual({+ resources: expect.arrayContaining([+ expect.objectContaining({ uri: "webstudio://project/status" }),+ expect.objectContaining({ uri: "webstudio://project/tools" }),+ ]),+ });+ } finally {+ await close();+ }+ });++ test("marks visual verification tools with side-effect-aware SDK annotations", async () => {+ const server = await createProjectSessionMcpServer({+ operations: publicMcpOperations,+ createProjectSession: createSessionFactory(),+ executeOperation: createExecuteOperation(),+ startPreview: vi.fn(async () => ({+ url: "http://127.0.0.1:5173/",+ running: true,+ })),+ getPreviewStatus: vi.fn(async () => ({+ url: "http://127.0.0.1:5173/",+ running: true,+ })),+ captureScreenshot: vi.fn(async () => ({+ output: "current.png",+ browserPath: "/usr/bin/chromium",+ browser: "chromium" as const,+ viewport: { width: 1440, height: 900 },+ elapsedMs: 1,+ warnings: [],+ })),+ diffScreenshots: vi.fn(async () => ({+ totalPixels: 0,+ differentPixels: 0,+ mismatchPercentage: 0,+ summary: "Screenshot diff summary",+ regions: [],+ textAnalysis: {+ status: "skipped" as const,+ provider: "tesseract" as const,+ changes: [],+ },+ warnings: [],+ })),+ installOcr: vi.fn(async () => ({+ installed: false,+ alreadyAvailable: true,+ tesseractPath: "/usr/bin/tesseract",+ installUrl: tesseractInstallUrl,+ warnings: [],+ })),+ });+ const { client, close } = await createConnectedClient(server);++ try {+ await expect(client.listTools()).resolves.toEqual({+ tools: expect.arrayContaining([+ expect.objectContaining({+ name: "preview.start",+ annotations: expect.objectContaining({+ readOnlyHint: false,+ destructiveHint: false,+ openWorldHint: true,+ }),+ }),+ expect.objectContaining({+ name: "preview.status",+ annotations: expect.objectContaining({+ readOnlyHint: true,+ destructiveHint: false,+ openWorldHint: true,+ }),+ }),+ expect.objectContaining({+ name: "screenshot",+ annotations: expect.objectContaining({+ readOnlyHint: false,+ destructiveHint: false,+ openWorldHint: true,+ }),+ }),+ expect.objectContaining({+ name: "screenshot.diff",+ annotations: expect.objectContaining({+ readOnlyHint: false,+ destructiveHint: false,+ openWorldHint: true,+ }),+ }),+ expect.objectContaining({+ name: "vision.install-ocr",+ annotations: expect.objectContaining({+ readOnlyHint: false,+ destructiveHint: false,+ openWorldHint: true,+ }),+ }),+ ]),+ });+ } finally {+ await close();+ }+ });++ test("handles SDK tool calls and resource reads", async () => {+ const session = createSession({+ initialize: vi.fn(async () =>+ createEnvelope({+ operationId: "project-session.status",+ result: { loaded: true },+ })+ ),+ refresh: vi.fn(),+ reset: vi.fn(),+ });+ const executeOperation: ExecuteOperation = vi.fn(async () =>+ createEnvelope({+ operationId: "pages.list",+ result: [{ id: "home" }],+ })+ );+ const server = await createProjectSessionMcpServer({+ operations: publicMcpOperations,+ createProjectSession: createSessionFactory(session),+ executeOperation,+ });+ const { client, close } = await createConnectedClient(server);++ try {+ await expect(+ client.callTool({+ name: "list-pages",+ arguments: { includeFolders: true, dryRun: true },+ })+ ).resolves.toEqual(+ expect.objectContaining({+ structuredContent: expect.objectContaining({+ ok: true,+ data: [{ id: "home" }],+ }),+ })+ );+ expect(executeOperation).toHaveBeenCalledWith({+ command: "list-pages",+ input: { includeFolders: true },+ dryRun: true,+ });+ await client.callTool({+ name: "list-pages",+ arguments: { includeFolders: true, dryRun: false },+ });+ expect(executeOperation).toHaveBeenLastCalledWith({+ command: "list-pages",+ input: { includeFolders: true },+ dryRun: false,+ });++ await expect(+ client.readResource({ uri: "webstudio://project/status" })+ ).resolves.toEqual({+ contents: [+ expect.objectContaining({+ uri: "webstudio://project/status",+ mimeType: "application/json",+ }),+ ],+ });+ } finally {+ await close();+ }+ });++ test("returns stable SDK tool errors from resolver", async () => {+ const error = new Error(+ "Project session snapshot changed on disk."+ ) as Error & { code: string };+ error.code = "PROJECT_SESSION_BUSY";+ const server = await createProjectSessionMcpServer({+ operations: publicMcpOperations,+ createProjectSession: createSessionFactory(),+ executeOperation: createExecuteOperation(async () => {+ throw error;+ }),+ getErrorCode: (error) =>+ typeof error === "object" && error !== null && "code" in error+ ? (error as { code?: string }).code+ : undefined,+ });+ const { client, close } = await createConnectedClient(server);++ try {+ await expect(+ client.callTool({+ name: "list-pages",+ arguments: {},+ })+ ).resolves.toEqual(+ expect.objectContaining({+ isError: true,+ structuredContent: {+ ok: false,+ error: {+ message: "Project session snapshot changed on disk.",+ code: "PROJECT_SESSION_BUSY",+ },+ meta: {},+ },+ })+ );+ } finally {+ await close();+ }+ });++ test("creates a complete project session MCP server", async () => {+ const server = await createProjectSessionMcpServer({+ operations: publicMcpOperations,+ createProjectSession: createSessionFactory(),+ executeOperation: createExecuteOperation(async () =>+ createEnvelope({+ operationId: "pages.list",+ result: [{ id: "home" }],+ })+ ),+ });+ const { client, close } = await createConnectedClient(server);++ try {+ await expect(+ client.callTool({+ name: "list-pages",+ arguments: {},+ })+ ).resolves.toEqual(+ expect.objectContaining({+ structuredContent: expect.objectContaining({+ data: [{ id: "home" }],+ }),+ })+ );+ } finally {+ await close();+ }+ });+});diff --git a/packages/project-build/src/mcp.ts b/packages/project-build/src/mcp.tsnew file mode 100644index 0000000000..00c06ad3f6--- /dev/null+++ b/packages/project-build/src/mcp.ts@@ -0,0 +1,1673 @@+import {+ builderNamespaces,+ type BuilderNamespace,+} from "./contracts/namespaces";+import path from "node:path";+import type { ProjectSessionEnvelope } from "./project-session";+import {+ defaultScreenshotTimeout,+ defaultScreenshotWaitForTimeout,+ defaultScreenshotWaitUntil,+ isScreenshotWaitUntil,+ screenshotBrowserChoices,+ type ScreenshotBrowser,+ screenshotWaitUntilValues,+ type ScreenshotWaitUntil,+} from "./visual/screenshot-browser";+import type { ScreenshotDiffResult } from "./visual/screenshot-diff";+import { Server } from "@modelcontextprotocol/sdk/server/index.js";+import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";+import type { Transport } from "@modelcontextprotocol/sdk/shared/transport.js";+import {+ CallToolRequestSchema,+ ListResourcesRequestSchema,+ ListToolsRequestSchema,+ ReadResourceRequestSchema,+} from "@modelcontextprotocol/sdk/types.js";++type PublicMcpOperationMethod = "query" | "mutation";+type PublicMcpOperationPermit = "api" | "view" | "build" | "edit" | "admin";++export type PublicMcpOperation<Command extends string = string> = {+ command: Command;+ id: string;+ method: PublicMcpOperationMethod;+ permit: PublicMcpOperationPermit;+ description: string;+ inputFields: readonly string[];+ requiredOptions?: readonly string[];+ examples?: readonly string[];+ localCapable: boolean;+ serverOnly: boolean;+ readNamespaces: readonly string[];+ writeNamespaces: readonly string[];+ invalidatesNamespaces: readonly string[];+ retryOnConflict: boolean;+};++type ProjectSessionLike = {+ initialize: () => Promise<ProjectSessionEnvelope>;+ refresh: (+ namespaces: readonly BuilderNamespace[]+ ) => Promise<ProjectSessionEnvelope>;+ reset: () => Promise<ProjectSessionEnvelope>;+};++type CreateProjectSession = () => ProjectSessionLike;++type ExecuteMcpOperation<Command extends string = string> = (options: {+ command: Command;+ input: unknown;+ dryRun: boolean;+}) => Promise<ProjectSessionEnvelope>;++export type McpErrorCodeResolver = (error: unknown) => string | undefined;++export type McpTransport = Transport;++export type ProjectSessionScreenshotInput = {+ url?: string;+ path?: string;+ output?: string;+ viewport: {+ width: number;+ height: number;+ };+ browser: ScreenshotBrowser;+ browserPath?: string;+ waitUntil?: ScreenshotWaitUntil;+ waitForSelector?: string;+ waitForTimeout?: number;+ timeout?: number;+};++export type ProjectSessionScreenshotResult = {+ output: string;+ browserPath: string;+ browser: "chromium" | "chrome" | "edge" | "brave";+ viewport: {+ width: number;+ height: number;+ };+ elapsedMs: number;+ warnings: readonly string[];+};++type CaptureScreenshot = (+ input: ProjectSessionScreenshotInput+) => Promise<ProjectSessionScreenshotResult>;++export type ProjectSessionScreenshotDiffInput = {+ baselinePath: string;+ currentPath: string;+ outputDir: string;+ threshold?: number;+ ignoreTopNormalizedY?: number;+};++type DiffScreenshots = (+ input: ProjectSessionScreenshotDiffInput+) => Promise<ScreenshotDiffResult>;++export type ProjectSessionInstallOcrResult = {+ installed: boolean;+ alreadyAvailable: boolean;+ command?: string;+ tesseractPath?: string;+ installUrl: string;+ warnings: readonly string[];+};++type InstallOcr = () => Promise<ProjectSessionInstallOcrResult>;++export type ProjectSessionPreviewInput = {+ host?: string;+ port?: number;+};++export type ProjectSessionPreviewResult = {+ url: string;+ pid?: number;+ running: boolean;+};++type StartPreview = (+ input: ProjectSessionPreviewInput+) => Promise<ProjectSessionPreviewResult>;+type GetPreviewStatus = () => Promise<ProjectSessionPreviewResult>;++export type ProjectSessionMcpGuidance = {+ visualVerificationRule: string;+ getVisionVerificationLoop: (options: {+ includeDiff: boolean;+ }) => readonly string[];+ getVisionWorkflowSummary: (options: { includeDiff: boolean }) => string;+};++const isRecord = (value: unknown): value is Record<string, unknown> =>+ typeof value === "object" && value !== null;++const isScreenshotBrowser = (value: unknown): value is ScreenshotBrowser =>+ typeof value === "string" &&+ screenshotBrowserChoices.includes(value as ScreenshotBrowser);++const getRequestParams = (request: unknown) =>+ isRecord(request) && isRecord(request.params) ? request.params : {};++const getProjectSessionMeta = (envelope: ProjectSessionEnvelope) => ({+ operationId: envelope.operationId,+ projectId: envelope.projectId,+ buildId: envelope.buildId,+ version: envelope.version,+ source: envelope.source,+ committed: envelope.state.committed,+ compatibility: envelope.state.compatibility,+ namespaces: envelope.namespaces,+ diagnostics: envelope.diagnostics,+});++type ProjectSessionMcpInputSchema = {+ type: "object";+ description?: string;+ additionalProperties: true;+ properties?: Record<string, unknown>;+ required?: readonly string[];+};++const emptyInputSchema = {+ type: "object",+ description:+ "Pass the public API input object for this tool. Use meta.get_more_tools for examples and required fields.",+ additionalProperties: true,+} as const satisfies ProjectSessionMcpInputSchema;++const textInputSchema = (description: string) =>+ ({+ ...emptyInputSchema,+ properties: {+ brief: {+ type: "string",+ description,+ },+ },+ }) as const satisfies ProjectSessionMcpInputSchema;++const getOperationInputSchema = (+ operation: Pick<PublicMcpOperation, "inputFields">+): ProjectSessionMcpInputSchema => {+ if (operation.inputFields.length === 0) {+ return emptyInputSchema;+ }+ return {+ ...emptyInputSchema,+ properties: Object.fromEntries(+ operation.inputFields.map((field) => [+ field,+ {+ description: `Public API input field \`${field}\`.`,+ },+ ])+ ),+ };+};++const screenshotInputSchema = {+ ...emptyInputSchema,+ description:+ "Capture a visual screenshot for AI vision review. Pass { url } for any URL or { path } after preview.start.",+ properties: {+ url: {+ type: "string",+ description: "Absolute URL to capture.",+ },+ path: {+ type: "string",+ description:+ "Generated-site path to capture through the active MCP preview server.",+ },+ output: {+ type: "string",+ description: "PNG output path.",+ },+ viewport: {+ type: "object",+ description: "Viewport dimensions in CSS pixels.",+ properties: {+ width: { type: "number", default: 1440 },+ height: { type: "number", default: 900 },+ },+ },+ browser: {+ type: "string",+ enum: screenshotBrowserChoices,+ default: "auto",+ },+ browserPath: {+ type: "string",+ description: "Explicit Chromium-family browser executable path.",+ },+ waitUntil: {+ type: "string",+ enum: screenshotWaitUntilValues,+ default: defaultScreenshotWaitUntil,+ description:+ "Page readiness event to wait for before capture: commit, domcontentloaded, load, or networkidle.",+ },+ waitForSelector: {+ type: "string",+ description: "CSS selector that must exist before capture.",+ },+ waitForTimeout: {+ type: "number",+ default: defaultScreenshotWaitForTimeout,+ description:+ "Extra milliseconds to wait after readiness, selector, fonts, and layout frames.",+ },+ timeout: {+ type: "number",+ default: defaultScreenshotTimeout,+ description: "Maximum milliseconds to wait for page readiness.",+ },+ },+} as const satisfies ProjectSessionMcpInputSchema;++const screenshotDiffInputSchema = {+ ...emptyInputSchema,+ description:+ "Compare baseline/current PNG screenshots and return pixel-region plus OCR text-change evidence for AI vision review. OCR uses the system tesseract binary when available.",+ properties: {+ baselinePath: {+ type: "string",+ description: "Baseline PNG path.",+ },+ currentPath: {+ type: "string",+ description: "Current PNG path.",+ },+ outputDir: {+ type: "string",+ description:+ "Directory for diff artifacts. Defaults to the current screenshot directory.",+ },+ threshold: {+ type: "number",+ default: 0.1,+ description: "RGB distance threshold from 0 to 1.",+ },+ ignoreTopNormalizedY: {+ type: "number",+ default: 0,+ description:+ "Ignore the top fraction of the image, useful for browser chrome or status bars.",+ },+ },+ required: ["baselinePath", "currentPath"],+} as const satisfies ProjectSessionMcpInputSchema;++const installOcrInputSchema = {+ ...emptyInputSchema,+ description:+ "Install the Tesseract OCR binary needed for screenshot.diff textAnalysis. MCP cannot prompt; ask the user first, then pass { confirm: true }.",+ properties: {+ confirm: {+ type: "boolean",+ description:+ "Must be true after explicit user consent. The tool refuses to install without it.",+ },+ },+ required: ["confirm"],+} as const satisfies ProjectSessionMcpInputSchema;++const previewInputSchema = {+ ...emptyInputSchema,+ description:+ "Start or inspect a long-lived generated-site preview server for visual verification. This serves already generated local project files; generate project files first when they are missing or stale.",+ properties: {+ host: {+ type: "string",+ default: "127.0.0.1",+ },+ port: {+ type: "number",+ default: 5173,+ },+ },+} as const satisfies ProjectSessionMcpInputSchema;++export type ProjectSessionMcpTool = {+ name: string;+ description: string;+ inputSchema: ProjectSessionMcpInputSchema;+ cliRequiredOptions?: readonly string[];+ cliExamples?: readonly string[];+ mcpExamples?: readonly unknown[];+ annotations: {+ command: string;+ operationId: string;+ method: PublicMcpOperation["method"] | "session";+ permit: PublicMcpOperation["permit"];+ inputFields: readonly string[];+ localCapable: boolean;+ serverOnly: boolean;+ readNamespaces: readonly string[];+ writeNamespaces: readonly string[];+ invalidatesNamespaces: readonly string[];+ retryOnConflict: boolean;+ };+};++export const mcpArgumentExamples: Record<string, readonly unknown[]> = {+ "meta.guide": [{ brief: "Create a pricing page and style the hero" }],+ "meta.get_more_tools": [{ brief: "update-styles" }],+ refresh: [{ namespaces: ["pages", "instances", "styles"] }],+ "preview.start": [{ host: "127.0.0.1", port: 5173 }],+ "preview.status": [{}],+ "list-pages": [{ includeFolders: true }],+ "get-page-by-path": [{ path: "/pricing" }],+ "list-instances": [{ pagePath: "/", maxDepth: 3 }],+ "inspect-instance": [+ {+ instanceId: "instance-id",+ include: ["props", "styles", "children"],+ },+ ],+ "append-instance": [+ {+ parentInstanceId: "parent-id",+ children: [{ tag: "section", label: "Hero", text: "Launch faster" }],+ },+ ],+ "update-text": [+ {+ instanceId: "instance-id",+ childIndex: 0,+ text: "Launch faster",+ },+ ],+ "update-styles": [+ {+ updates: [+ {+ instanceId: "instance-id",+ property: "color",+ value: { type: "keyword", value: "red" },+ },+ ],+ },+ ],+ "apply-patch": [+ {+ baseVersion: 12,+ transactions: [+ {+ id: "transaction-id",+ payload: [+ {+ namespace: "pages",+ patches: [+ {+ op: "replace",+ path: ["meta", "siteName"],+ value: "Site name",+ },+ ],+ },+ ],+ },+ ],+ },+ ],+ publish: [{ target: "production" }],+ "create-domain": [{ domain: "www.example.com" }],+ screenshot: [+ {+ url: "https://example.com",+ output: "current.png",+ viewport: { width: 1440, height: 900 },+ browser: "auto",+ },+ ],+ "screenshot.diff": [+ {+ baselinePath: "baseline.png",+ currentPath: "current.png",+ outputDir: "visual-diff",+ threshold: 0.1,+ ignoreTopNormalizedY: 0,+ },+ ],+ "vision.install-ocr": [{ confirm: true }],+} as const;++const getMcpExamples = (command: string): readonly unknown[] =>+ mcpArgumentExamples[command] ?? [];++const sessionTools = [+ {+ name: "meta.index",+ description:+ "Return a concise Webstudio MCP capability catalog and discovery guide.",+ inputSchema: emptyInputSchema,+ annotations: {+ command: "meta.index",+ operationId: "meta.index",+ method: "session",+ permit: "api",+ inputFields: [],+ localCapable: true,+ serverOnly: false,+ readNamespaces: [],+ writeNamespaces: [],+ invalidatesNamespaces: [],+ retryOnConflict: false,+ },+ },+ {+ name: "meta.guide",+ description:+ "Return a recommended workflow and relevant tools for a user goal. Pass { brief }.",+ inputSchema: textInputSchema(+ "Short user goal, for example: publish a site."+ ),+ annotations: {+ command: "meta.guide",+ operationId: "meta.guide",+ method: "session",+ permit: "api",+ inputFields: ["brief"],+ localCapable: true,+ serverOnly: false,+ readNamespaces: [],+ writeNamespaces: [],+ invalidatesNamespaces: [],+ retryOnConflict: false,+ },+ },+ {+ name: "meta.get_more_tools",+ description:+ "Return detailed tool metadata and examples matching a brief. Pass { brief }.",+ inputSchema: textInputSchema(+ "Tool name, operation id, area, or goal, for example: build.publish."+ ),+ annotations: {+ command: "meta.get_more_tools",+ operationId: "meta.get_more_tools",+ method: "session",+ permit: "api",+ inputFields: ["brief"],+ localCapable: true,+ serverOnly: false,+ readNamespaces: [],+ writeNamespaces: [],+ invalidatesNamespaces: [],+ retryOnConflict: false,+ },+ },+ {+ name: "status",+ description: "Read the current local ProjectSession status and freshness.",+ inputSchema: emptyInputSchema,+ annotations: {+ command: "status",+ operationId: "project-session.status",+ method: "session",+ permit: "api",+ inputFields: [],+ localCapable: true,+ serverOnly: false,+ readNamespaces: [],+ writeNamespaces: [],+ invalidatesNamespaces: [],+ retryOnConflict: false,+ },+ },+ {+ name: "refresh",+ description:+ "Refresh local ProjectSession namespaces from the configured project. Pass { namespaces } or omit it to refresh all namespaces.",+ inputSchema: {+ ...emptyInputSchema,+ properties: {+ namespaces: {+ type: "array",+ items: { type: "string", enum: builderNamespaces },+ description:+ "Synced namespaces to refresh. Omit to refresh every namespace.",+ },+ },+ },+ annotations: {+ command: "refresh",+ operationId: "project-session.refresh",+ method: "session",+ permit: "api",+ inputFields: ["namespaces"],+ localCapable: true,+ serverOnly: false,+ readNamespaces: builderNamespaces,+ writeNamespaces: [],+ invalidatesNamespaces: [],+ retryOnConflict: false,+ },+ },+ {+ name: "reset-session",+ description: "Delete the persisted local ProjectSession snapshot.",+ inputSchema: emptyInputSchema,+ annotations: {+ command: "reset-session",+ operationId: "project-session.reset",+ method: "session",+ permit: "api",+ inputFields: [],+ localCapable: true,+ serverOnly: false,+ readNamespaces: [],+ writeNamespaces: [],+ invalidatesNamespaces: builderNamespaces,+ retryOnConflict: false,+ },+ },+] as const satisfies readonly ProjectSessionMcpTool[];++const screenshotTool = {+ name: "screenshot",+ description:+ "Capture a PNG screenshot so a vision-capable AI can inspect what was actually built, compare it with the intent, and iterate.",+ inputSchema: screenshotInputSchema,+ mcpExamples: getMcpExamples("screenshot"),+ annotations: {+ command: "screenshot",+ operationId: "screenshot.capture",+ method: "session",+ permit: "api",+ inputFields: [+ "url",+ "path",+ "output",+ "viewport",+ "browser",+ "browserPath",+ ],+ localCapable: false,+ serverOnly: true,+ readNamespaces: [],+ writeNamespaces: [],+ invalidatesNamespaces: [],+ retryOnConflict: false,+ },+} as const satisfies ProjectSessionMcpTool;++const screenshotDiffTool = {+ name: "screenshot.diff",+ description:+ "Compare two PNG screenshots, write diff artifacts, and return pixel regions plus optional OCR textAnalysis for visual verification.",+ inputSchema: screenshotDiffInputSchema,+ mcpExamples: getMcpExamples("screenshot.diff"),+ annotations: {+ command: "screenshot.diff",+ operationId: "screenshot.diff",+ method: "session",+ permit: "api",+ inputFields: [+ "baselinePath",+ "currentPath",+ "outputDir",+ "threshold",+ "ignoreTopNormalizedY",+ ],+ localCapable: false,+ serverOnly: true,+ readNamespaces: [],+ writeNamespaces: [],+ invalidatesNamespaces: [],+ retryOnConflict: false,+ },+} as const satisfies ProjectSessionMcpTool;++const installOcrTool = {+ name: "vision.install-ocr",+ description:+ "Install Tesseract OCR for screenshot.diff textAnalysis after explicit user consent. Use only when OCR is unavailable and the user agrees.",+ inputSchema: installOcrInputSchema,+ mcpExamples: getMcpExamples("vision.install-ocr"),+ annotations: {+ command: "vision.install-ocr",+ operationId: "vision.install-ocr",+ method: "session",+ permit: "api",+ inputFields: ["confirm"],+ localCapable: false,+ serverOnly: true,+ readNamespaces: [],+ writeNamespaces: [],+ invalidatesNamespaces: [],+ retryOnConflict: false,+ },+} as const satisfies ProjectSessionMcpTool;++const previewTools = [+ {+ name: "preview.start",+ description:+ "Start or reuse a generated-site preview server for fast visual verification while MCP is running. The server serves existing generated project files and does not regenerate them.",+ inputSchema: previewInputSchema,+ mcpExamples: getMcpExamples("preview.start"),+ annotations: {+ command: "preview.start",+ operationId: "preview.start",+ method: "session",+ permit: "api",+ inputFields: ["host", "port"],+ localCapable: false,+ serverOnly: true,+ readNamespaces: [],+ writeNamespaces: [],+ invalidatesNamespaces: [],+ retryOnConflict: false,+ },+ },+ {+ name: "preview.status",+ description:+ "Return the active generated-site preview server URL and process state for screenshot-based verification.",+ inputSchema: emptyInputSchema,+ mcpExamples: getMcpExamples("preview.status"),+ annotations: {+ command: "preview.status",+ operationId: "preview.status",+ method: "session",+ permit: "api",+ inputFields: [],+ localCapable: false,+ serverOnly: true,+ readNamespaces: [],+ writeNamespaces: [],+ invalidatesNamespaces: [],+ retryOnConflict: false,+ },+ },+] as const satisfies readonly ProjectSessionMcpTool[];++type ProjectSessionMcpStructuredContent = {+ ok: true;+ data: unknown;+ meta: {+ session?: ReturnType<typeof getProjectSessionMeta>;+ };+};++export type ProjectSessionMcpCallResult = {+ content: [{ type: "text"; text: string }];+ structuredContent: ProjectSessionMcpStructuredContent;+ isError?: boolean;+};++export type ProjectSessionMcpResource = {+ uri: string;+ name: string;+ description: string;+ mimeType: "application/json";+};++type SdkTool = {+ name: string;+ description: string;+ inputSchema: ProjectSessionMcpInputSchema;+ annotations: {+ readOnlyHint: boolean;+ destructiveHint: boolean;+ openWorldHint: boolean;+ };+ _meta: {+ webstudio: ProjectSessionMcpTool["annotations"];+ };+};++export const listProjectSessionMcpTools = (+ operations: readonly PublicMcpOperation[],+ options: {+ includeScreenshot?: boolean;+ includeScreenshotDiff?: boolean;+ includeInstallOcr?: boolean;+ includePreview?: boolean;+ } = {}+): ProjectSessionMcpTool[] => [+ ...operations.map((operation) => ({+ name: operation.command,+ description: operation.description,+ inputSchema: getOperationInputSchema(operation),+ cliRequiredOptions: operation.requiredOptions,+ cliExamples: operation.examples,+ mcpExamples: getMcpExamples(operation.command),+ annotations: {+ command: operation.command,+ operationId: operation.id,+ method: operation.method,+ permit: operation.permit,+ inputFields: operation.inputFields,+ localCapable: operation.localCapable,+ serverOnly: operation.serverOnly,+ readNamespaces: operation.readNamespaces,+ writeNamespaces: operation.writeNamespaces,+ invalidatesNamespaces: operation.invalidatesNamespaces,+ retryOnConflict: operation.retryOnConflict,+ },+ })),+ ...sessionTools.map((tool) => ({+ ...tool,+ mcpExamples: getMcpExamples(tool.name),+ })),+ ...(options.includeScreenshot ? [screenshotTool] : []),+ ...(options.includeScreenshotDiff ? [screenshotDiffTool] : []),+ ...(options.includeInstallOcr ? [installOcrTool] : []),+ ...(options.includePreview ? previewTools : []),+];++const toMetaResult = (data: unknown): ProjectSessionMcpCallResult => {+ const structuredContent = {+ ok: true as const,+ data,+ meta: {},+ } satisfies ProjectSessionMcpStructuredContent;+ return {+ content: [{ type: "text", text: JSON.stringify(structuredContent) }],+ structuredContent,+ };+};++const capabilityAreas = [+ {+ area: "visual-verification",+ goal: "Let a vision-capable AI see the rendered result, compare it with the user's intent, and iterate.",+ tools: [+ "preview.start",+ "preview.status",+ "screenshot",+ "screenshot.diff",+ "vision.install-ocr",+ ],+ },+ {+ area: "discover",+ goal: "Understand connection, permissions, project status, and available tools.",+ tools: [+ "meta.index",+ "meta.guide",+ "meta.get_more_tools",+ "status",+ "permissions",+ "whoami",+ "inspect",+ ],+ },+ {+ area: "pages",+ goal: "Create, inspect, update, duplicate, delete, and organize pages and folders.",+ tools: [+ "list-pages",+ "get-page",+ "get-page-by-path",+ "create-page",+ "update-page",+ "get-project-settings",+ "update-project-settings",+ "list-redirects",+ "create-redirect",+ "update-redirect",+ "delete-redirect",+ "duplicate-page",+ "delete-page",+ "list-page-templates",+ "create-page-from-template",+ "list-folders",+ "create-folder",+ "update-folder",+ "delete-folder",+ ],+ },+ {+ area: "content",+ goal: "Inspect and edit element instances, text, props, bindings, and page content.",+ tools: [+ "list-instances",+ "inspect-instance",+ "append-instance",+ "move-instance",+ "clone-instance",+ "delete-instance",+ "list-texts",+ "update-text",+ "update-props",+ "delete-props",+ "bind-props",+ ],+ },+ {+ area: "styles",+ goal: "Read and change styles, design tokens, CSS variables, and breakpoints.",+ tools: [+ "get-styles",+ "update-styles",+ "delete-styles",+ "replace-styles",+ "list-design-tokens",+ "create-design-token",+ "update-design-token-styles",+ "delete-design-token-styles",+ "attach-design-token",+ "detach-design-token",+ "extract-design-token",+ "list-css-variables",+ "define-css-variable",+ "delete-css-variable",+ "rewrite-css-variable-refs",+ "list-breakpoints",+ "create-breakpoint",+ "update-breakpoint",+ "delete-breakpoint",+ ],+ },+ {+ area: "data",+ goal: "Manage data variables and resources.",+ tools: [+ "list-variables",+ "create-variable",+ "update-variable",+ "delete-variable",+ "list-resources",+ "create-resource",+ "update-resource",+ "delete-resource",+ ],+ },+ {+ area: "assets",+ goal: "Upload, replace, delete, list, and find usage of assets.",+ tools: [+ "list-assets",+ "upload-asset",+ "upload-assets",+ "find-asset-usage",+ "replace-asset",+ "delete-asset",+ ],+ },+ {+ area: "publish",+ goal: "Publish, unpublish, inspect publish jobs, and manage domains.",+ tools: [+ "publish",+ "list-publishes",+ "get-publish-job",+ "unpublish",+ "list-domains",+ "create-domain",+ "update-domain",+ "delete-domain",+ "verify-domain",+ ],+ },+ {+ area: "raw-patch",+ goal: "Use raw Builder patches only when no semantic tool fits.",+ tools: ["snapshot", "apply-patch"],+ },+] as const;++const getBrief = (input: unknown) =>+ typeof input === "object" &&+ input !== null &&+ "brief" in input &&+ typeof (input as { brief?: unknown }).brief === "string"+ ? (input as { brief: string }).brief+ : "";++const normalize = (value: string) =>+ value.toLowerCase().replace(/[^a-z0-9]+/g, " ");++const scoreTool = (tool: ProjectSessionMcpTool, brief: string) => {+ const normalizedBrief = normalize(brief);+ if (normalizedBrief.trim().length === 0) {+ return 0;+ }+ const haystack = normalize(+ [+ tool.name,+ tool.description,+ tool.annotations.operationId,+ tool.annotations.readNamespaces.join(" "),+ tool.annotations.writeNamespaces.join(" "),+ ].join(" ")+ );+ let score = 0;+ for (const token of normalizedBrief.split(/\s+/)) {+ if (token.length < 3) {+ continue;+ }+ if (haystack.includes(token)) {+ score += token.length;+ }+ }+ return score;+};++const getMatchingTools = (+ brief: string,+ tools: readonly ProjectSessionMcpTool[]+) => {+ const normalizedBrief = normalize(brief);+ if (normalizedBrief.trim().length === 0) {+ const names = new Set<string>(+ capabilityAreas.find((area) => area.area === "discover")?.tools ?? []+ );+ return tools.filter((tool) => names.has(tool.name));+ }+ const area = capabilityAreas.find((area) =>+ [area.area, area.goal, area.tools.join(" ")]+ .map(normalize)+ .some((value) => value.includes(normalizedBrief))+ );+ if (area !== undefined) {+ const names = new Set<string>(area.tools);+ return tools.filter((tool) => names.has(tool.name));+ }+ return tools+ .map((tool) => ({ tool, score: scoreTool(tool, brief) }))+ .filter(({ score }) => score > 0)+ .sort((left, right) => right.score - left.score)+ .map(({ tool }) => tool);+};++const filterCapabilities = (tools: readonly ProjectSessionMcpTool[]) => {+ const names = new Set(tools.map((tool) => tool.name));+ return capabilityAreas+ .map((capability) => ({+ ...capability,+ tools: capability.tools.filter((tool) => names.has(tool)),+ }))+ .filter((capability) => capability.tools.length > 0);+};++const getMetaIndex = (+ tools: readonly ProjectSessionMcpTool[],+ guidance: ProjectSessionMcpGuidance | undefined+) => {+ const names = new Set(tools.map((tool) => tool.name));+ const canVerifyVisually = ["preview.start", "screenshot"].every((tool) =>+ names.has(tool)+ );+ return {+ startHere: ["meta.index", "meta.guide", "status", "permissions"].filter(+ (tool) => names.has(tool)+ ),+ discovery: {+ tools: "Use MCP tools/list for machine-readable tool schemas.",+ resources: "Use MCP resources/list for longer JSON resources.",+ guide: "Use meta.guide({ brief }) for a goal-specific workflow.",+ details:+ "Use meta.get_more_tools({ brief }) for matching params and examples.",+ },+ rules: [+ "Operate on the configured project only.",+ "Read ids before writing.",+ "Prefer semantic tools over apply-patch.",+ "Use status/refresh when cached data may be stale.",+ guidance?.visualVerificationRule,+ ].filter((rule): rule is string => rule !== undefined),+ visionLoop:+ canVerifyVisually && guidance !== undefined+ ? guidance.getVisionVerificationLoop({+ includeDiff: names.has("screenshot.diff"),+ })+ : [],+ capabilities: filterCapabilities(tools),+ };+};++const getMetaGuide = (+ brief: string,+ tools: readonly ProjectSessionMcpTool[],+ guidance: ProjectSessionMcpGuidance | undefined+) => {+ const matches = getMatchingTools(brief, tools).slice(0, 12);+ const canVerifyVisually =+ tools.some((tool) => tool.name === "preview.start") &&+ tools.some((tool) => tool.name === "screenshot");+ const canDiffScreenshots = tools.some(+ (tool) => tool.name === "screenshot.diff"+ );+ return {+ brief,+ workflow: [+ "Call permissions to verify token capabilities.",+ "Call status to inspect local ProjectSession state.",+ matches.some((tool) => tool.annotations.localCapable)+ ? "Call refresh if cached namespaces may be stale."+ : undefined,+ "Use focused read tools to collect ids and current values.",+ "Use the smallest semantic mutation tool that matches the requested change.",+ "Use apply-patch only when no semantic mutation tool fits.",+ canVerifyVisually && guidance !== undefined+ ? guidance.getVisionWorkflowSummary({ includeDiff: canDiffScreenshots })+ : undefined,+ ].filter(Boolean),+ tools: matches.map((tool) => ({+ name: tool.name,+ use: tool.description,+ method: tool.annotations.method,+ permit: tool.annotations.permit,+ inputFields: tool.annotations.inputFields,+ mcpExamples: tool.mcpExamples ?? [],+ cliRequiredOptions: tool.cliRequiredOptions ?? [],+ cliExamples: tool.cliExamples ?? [],+ })),+ more: "Call meta.get_more_tools with the same brief for params, examples, namespaces, and server/local behavior.",+ };+};++const getMoreTools = (+ brief: string,+ tools: readonly ProjectSessionMcpTool[]+) => ({+ brief,+ tools: getMatchingTools(brief, tools).map((tool) => ({+ name: tool.name,+ description: tool.description,+ inputSchema: tool.inputSchema,+ inputFields: tool.annotations.inputFields,+ mcpExamples: tool.mcpExamples ?? [],+ cliRequiredOptions: tool.cliRequiredOptions ?? [],+ cliExamples: tool.cliExamples ?? [],+ inputNote:+ "MCP tool arguments are public API input objects. Examples show intent, but do not imply MCP flag names.",+ annotations: tool.annotations,+ })),+});++const readOnlySessionTools = new Set([+ "meta.index",+ "meta.guide",+ "meta.get_more_tools",+ "status",+ "preview.status",+]);++const isReadOnlyTool = (tool: ProjectSessionMcpTool) =>+ tool.annotations.method === "query" ||+ (tool.annotations.method === "session" &&+ readOnlySessionTools.has(tool.name));++const isDestructiveTool = (tool: ProjectSessionMcpTool) =>+ tool.annotations.method === "mutation" ||+ tool.annotations.invalidatesNamespaces.length > 0;++const toSdkTool = (tool: ProjectSessionMcpTool): SdkTool => ({+ name: tool.name,+ description: tool.description,+ inputSchema: tool.inputSchema,+ annotations: {+ readOnlyHint: isReadOnlyTool(tool),+ destructiveHint: isDestructiveTool(tool),+ openWorldHint: tool.annotations.serverOnly,+ },+ _meta: {+ webstudio: tool.annotations,+ },+});++export const listProjectSessionMcpResources =+ (): ProjectSessionMcpResource[] => [+ {+ uri: "webstudio://project/status",+ name: "ProjectSession status",+ description:+ "Current local ProjectSession status and namespace metadata.",+ mimeType: "application/json",+ },+ {+ uri: "webstudio://project/tools",+ name: "Webstudio operation tools",+ description: "Catalog-derived MCP tools available for the project.",+ mimeType: "application/json",+ },+ {+ uri: "webstudio://project/guide",+ name: "Webstudio MCP guide",+ description:+ "Concise model-facing guide for discovering and choosing Webstudio MCP tools.",+ mimeType: "application/json",+ },+ ];++const toCallResult = (+ envelope: Parameters<typeof getProjectSessionMeta>[0]+): ProjectSessionMcpCallResult => {+ const structuredContent = {+ ok: true as const,+ data: envelope.result,+ meta: {+ session: getProjectSessionMeta(envelope),+ },+ };+ return {+ content: [+ {+ type: "text",+ text: JSON.stringify(structuredContent),+ },+ ],+ structuredContent,+ };+};++const toResourceContent = (+ envelope: Parameters<typeof getProjectSessionMeta>[0]+) => ({+ data: envelope.result,+ meta: {+ session: getProjectSessionMeta(envelope),+ },+});++const builderNamespaceSet = new Set<string>(builderNamespaces);++const isBuilderNamespace = (value: unknown): value is BuilderNamespace =>+ typeof value === "string" && builderNamespaceSet.has(value);++const getRefreshNamespaces = (input: unknown): readonly BuilderNamespace[] => {+ const namespaces =+ typeof input === "object" && input !== null && "namespaces" in input+ ? (input as { namespaces?: unknown }).namespaces+ : undefined;+ if (namespaces === undefined) {+ return builderNamespaces;+ }+ if (Array.isArray(namespaces) === false) {+ throw new Error("refresh namespaces must be an array.");+ }+ const result: BuilderNamespace[] = [];+ for (const namespace of namespaces) {+ if (isBuilderNamespace(namespace) === false) {+ throw new Error(`Unknown ProjectSession namespace "${namespace}".`);+ }+ result.push(namespace);+ }+ return result;+};++const getScreenshotInput = (input: unknown): ProjectSessionScreenshotInput => {+ if (isRecord(input) === false) {+ throw new Error("screenshot input must be an object.");+ }+ const url =+ typeof input.url === "string" && input.url.length > 0+ ? input.url+ : undefined;+ const path =+ typeof input.path === "string" && input.path.length > 0+ ? input.path+ : undefined;+ if (url === undefined && path === undefined) {+ throw new Error("screenshot requires url or path.");+ }+ if (url !== undefined && path !== undefined) {+ throw new Error("screenshot accepts either url or path, not both.");+ }+ const viewport = isRecord(input.viewport) ? input.viewport : {};+ const width =+ typeof viewport.width === "number" && Number.isInteger(viewport.width)+ ? viewport.width+ : 1440;+ const height =+ typeof viewport.height === "number" && Number.isInteger(viewport.height)+ ? viewport.height+ : 900;+ if (width <= 0 || height <= 0) {+ throw new Error("screenshot viewport width and height must be positive.");+ }+ const browser = input.browser === undefined ? "auto" : input.browser;+ if (isScreenshotBrowser(browser) === false) {+ throw new Error(+ "screenshot browser must be auto, chromium, chrome, edge, or brave."+ );+ }+ const waitUntil = input.waitUntil === undefined ? undefined : input.waitUntil;+ if (waitUntil !== undefined && isScreenshotWaitUntil(waitUntil) === false) {+ throw new Error(+ "screenshot waitUntil must be commit, domcontentloaded, load, or networkidle."+ );+ }+ const waitForTimeout = input.waitForTimeout;+ if (+ waitForTimeout !== undefined &&+ (typeof waitForTimeout !== "number" ||+ Number.isInteger(waitForTimeout) === false ||+ waitForTimeout < 0)+ ) {+ throw new Error(+ "screenshot waitForTimeout must be a non-negative integer."+ );+ }+ const timeout = input.timeout;+ if (+ timeout !== undefined &&+ (typeof timeout !== "number" ||+ Number.isInteger(timeout) === false ||+ timeout <= 0)+ ) {+ throw new Error("screenshot timeout must be a positive integer.");+ }+ const waitForSelector = input.waitForSelector;+ if (waitForSelector !== undefined) {+ if (typeof waitForSelector !== "string" || waitForSelector.length === 0) {+ throw new Error("screenshot waitForSelector must be a non-empty string.");+ }+ }+ return {+ url,+ path,+ output: typeof input.output === "string" ? input.output : undefined,+ viewport: { width, height },+ browser,+ browserPath:+ typeof input.browserPath === "string" ? input.browserPath : undefined,+ waitUntil,+ waitForSelector,+ waitForTimeout,+ timeout,+ };+};++const getScreenshotDiffInput = (+ input: unknown+): ProjectSessionScreenshotDiffInput => {+ if (isRecord(input) === false) {+ throw new Error("screenshot.diff input must be an object.");+ }+ const baselinePath =+ typeof input.baselinePath === "string" && input.baselinePath.length > 0+ ? input.baselinePath+ : undefined;+ const currentPath =+ typeof input.currentPath === "string" && input.currentPath.length > 0+ ? input.currentPath+ : undefined;+ if (baselinePath === undefined || currentPath === undefined) {+ throw new Error("screenshot.diff requires baselinePath and currentPath.");+ }+ const threshold =+ typeof input.threshold === "number" ? input.threshold : undefined;+ if (+ threshold !== undefined &&+ (Number.isFinite(threshold) === false || threshold < 0 || threshold > 1)+ ) {+ throw new Error("screenshot.diff threshold must be between 0 and 1.");+ }+ const ignoreTopNormalizedY =+ typeof input.ignoreTopNormalizedY === "number"+ ? input.ignoreTopNormalizedY+ : undefined;+ if (+ ignoreTopNormalizedY !== undefined &&+ (Number.isFinite(ignoreTopNormalizedY) === false ||+ ignoreTopNormalizedY < 0 ||+ ignoreTopNormalizedY > 1)+ ) {+ throw new Error(+ "screenshot.diff ignoreTopNormalizedY must be between 0 and 1."+ );+ }+ return {+ baselinePath,+ currentPath,+ outputDir:+ typeof input.outputDir === "string" && input.outputDir.length > 0+ ? input.outputDir+ : path.dirname(currentPath),+ threshold,+ ignoreTopNormalizedY,+ };+};++const assertInstallOcrConfirmed = (input: unknown) => {+ if (isRecord(input) === false) {+ throw new Error("vision.install-ocr input must be an object.");+ }+ if (input.confirm !== true) {+ throw new Error(+ "vision.install-ocr requires confirm: true after explicit user consent."+ );+ }+};++const getPreviewInput = (input: unknown): ProjectSessionPreviewInput => {+ if (isRecord(input) === false) {+ return {};+ }+ const host = typeof input.host === "string" ? input.host : undefined;+ if (host !== undefined && host.length === 0) {+ throw new Error("preview host must not be empty.");+ }+ const port = typeof input.port === "number" ? input.port : undefined;+ if (+ port !== undefined &&+ (Number.isInteger(port) === false || port <= 0 || port > 65535)+ ) {+ throw new Error("preview port must be an integer between 1 and 65535.");+ }+ return {+ host,+ port,+ };+};++export const createProjectSessionMcpCore = <Command extends string = string>({+ operations,+ createProjectSession,+ executeOperation,+ captureScreenshot,+ diffScreenshots,+ installOcr,+ startPreview,+ getPreviewStatus,+ guidance,+}: {+ operations: readonly (PublicMcpOperation & { command: Command })[];+ createProjectSession: CreateProjectSession;+ executeOperation: ExecuteMcpOperation<Command>;+ captureScreenshot?: CaptureScreenshot;+ diffScreenshots?: DiffScreenshots;+ installOcr?: InstallOcr;+ startPreview?: StartPreview;+ getPreviewStatus?: GetPreviewStatus;+ guidance?: ProjectSessionMcpGuidance;+}) => {+ let session: ReturnType<CreateProjectSession> | undefined;+ const operationCommands = new Set(+ operations.map((operation) => operation.command)+ );+ const listTools = () =>+ listProjectSessionMcpTools(operations, {+ includeScreenshot: captureScreenshot !== undefined,+ includeScreenshotDiff: diffScreenshots !== undefined,+ includeInstallOcr: installOcr !== undefined,+ includePreview:+ startPreview !== undefined && getPreviewStatus !== undefined,+ });+ const getSession = () => {+ session ??= createProjectSession();+ return session;+ };+ return {+ listTools,+ listResources: listProjectSessionMcpResources,+ async readResource({ uri }: { uri: string }) {+ if (uri === "webstudio://project/tools") {+ return {+ contents: [+ {+ uri,+ mimeType: "application/json",+ text: JSON.stringify({ tools: listTools() }),+ },+ ],+ };+ }+ if (uri === "webstudio://project/guide") {+ return {+ contents: [+ {+ uri,+ mimeType: "application/json",+ text: JSON.stringify(getMetaIndex(listTools(), guidance)),+ },+ ],+ };+ }+ if (uri === "webstudio://project/status") {+ const session = getSession();+ return {+ contents: [+ {+ uri,+ mimeType: "application/json",+ text: JSON.stringify(+ toResourceContent(await session.initialize())+ ),+ },+ ],+ };+ }+ throw new Error(`Unknown MCP resource "${uri}".`);+ },+ async callTool({+ name,+ input = {},+ dryRun = false,+ }: {+ name: string;+ input?: unknown;+ dryRun?: boolean;+ }): Promise<ProjectSessionMcpCallResult> {+ if (name === "meta.index") {+ return toMetaResult(getMetaIndex(listTools(), guidance));+ }+ if (name === "meta.guide") {+ return toMetaResult(+ getMetaGuide(getBrief(input), listTools(), guidance)+ );+ }+ if (name === "meta.get_more_tools") {+ return toMetaResult(getMoreTools(getBrief(input), listTools()));+ }+ if (name === "status") {+ const session = getSession();+ return toCallResult(await session.initialize());+ }+ if (name === "refresh") {+ const session = getSession();+ await session.initialize();+ return toCallResult(await session.refresh(getRefreshNamespaces(input)));+ }+ if (name === "reset-session") {+ const session = getSession();+ return toCallResult(await session.reset());+ }+ if (name === "screenshot" && captureScreenshot !== undefined) {+ return toMetaResult(await captureScreenshot(getScreenshotInput(input)));+ }+ if (name === "screenshot.diff" && diffScreenshots !== undefined) {+ return toMetaResult(+ await diffScreenshots(getScreenshotDiffInput(input))+ );+ }+ if (name === "vision.install-ocr" && installOcr !== undefined) {+ assertInstallOcrConfirmed(input);+ return toMetaResult(await installOcr());+ }+ if (name === "preview.start" && startPreview !== undefined) {+ return toMetaResult(await startPreview(getPreviewInput(input)));+ }+ if (name === "preview.status" && getPreviewStatus !== undefined) {+ return toMetaResult(await getPreviewStatus());+ }+ if (operationCommands.has(name as Command) === false) {+ throw new Error(`Unknown MCP tool "${name}".`);+ }+ const envelope = await executeOperation({+ command: name as Command,+ input,+ dryRun,+ });+ return toCallResult(envelope);+ },+ };+};++const getToolCallInput = (input: unknown) => {+ if (isRecord(input) === false) {+ return { input, dryRun: false };+ }+ const dryRun = input.dryRun === true || input["dry-run"] === true;+ const { dryRun: _dryRun, "dry-run": _dashDryRun, ...rest } = input;+ return { input: rest, dryRun };+};++type ProjectSessionMcpErrorResult = {+ isError: true;+ content: [{ type: "text"; text: string }];+ structuredContent: {+ ok: false;+ error: {+ message: string;+ code: string;+ };+ meta: Record<string, never>;+ };+};++const toToolErrorResult = (+ error: unknown,+ getErrorCode: McpErrorCodeResolver | undefined+): ProjectSessionMcpErrorResult => {+ const message = error instanceof Error ? error.message : String(error);+ const structuredContent = {+ ok: false as const,+ error: {+ message,+ code: getErrorCode?.(error) ?? "MCP_TOOL_FAILED",+ },+ meta: {},+ };+ return {+ isError: true,+ content: [{ type: "text", text: JSON.stringify(structuredContent) }],+ structuredContent,+ };+};++export const createProjectSessionMcpServer = async <+ Command extends string = string,+>({+ operations,+ createProjectSession,+ executeOperation,+ captureScreenshot,+ diffScreenshots,+ installOcr,+ startPreview,+ getPreviewStatus,+ guidance,+ getErrorCode,+}: {+ operations: readonly (PublicMcpOperation & { command: Command })[];+ createProjectSession: CreateProjectSession;+ executeOperation: ExecuteMcpOperation<Command>;+ captureScreenshot?: CaptureScreenshot;+ diffScreenshots?: DiffScreenshots;+ installOcr?: InstallOcr;+ startPreview?: StartPreview;+ getPreviewStatus?: GetPreviewStatus;+ guidance?: ProjectSessionMcpGuidance;+ getErrorCode?: McpErrorCodeResolver;+}) => {+ const core = createProjectSessionMcpCore({+ operations,+ createProjectSession,+ executeOperation,+ captureScreenshot,+ diffScreenshots,+ installOcr,+ startPreview,+ getPreviewStatus,+ guidance,+ });+ const server = new Server(+ { name: "webstudio", version: "0.0.0" },+ {+ capabilities: {+ tools: {},+ resources: {},+ },+ instructions:+ "Use meta.index, meta.guide, and meta.get_more_tools to discover Webstudio project capabilities. Read ids before writing and prefer semantic tools over apply-patch.",+ }+ );++ server.setRequestHandler(ListToolsRequestSchema, async () => ({+ tools: core.listTools().map(toSdkTool),+ }));++ server.setRequestHandler(ListResourcesRequestSchema, async () => ({+ resources: core.listResources(),+ }));++ server.setRequestHandler(ReadResourceRequestSchema, async (request) => {+ const params = getRequestParams(request);+ const uri = typeof params.uri === "string" ? params.uri : "";+ try {+ return await core.readResource({+ uri,+ });+ } catch (error) {+ const message = error instanceof Error ? error.message : String(error);+ return {+ contents: [+ {+ uri,+ mimeType: "application/json",+ text: JSON.stringify({+ ok: false,+ error: {+ message,+ code: getErrorCode?.(error) ?? "MCP_RESOURCE_FAILED",+ },+ meta: {},+ }),+ },+ ],+ };+ }+ });++ server.setRequestHandler(CallToolRequestSchema, async (request) => {+ const params = getRequestParams(request);+ const name = typeof params.name === "string" ? params.name : "";+ const { input, dryRun } = getToolCallInput(params.arguments ?? {});+ try {+ return await core.callTool({+ name,+ input,+ dryRun,+ });+ } catch (error) {+ return toToolErrorResult(error, getErrorCode);+ }+ });++ return server;+};++export const connectProjectSessionMcpServer = async <Command extends string>({+ transport,+ ...options+}: Parameters<typeof createProjectSessionMcpServer<Command>>[0] & {+ transport: McpTransport;+}) => {+ const server = await createProjectSessionMcpServer(options);+ await server.connect(transport);+ return server;+};++export const createMcpStdioTransport = async ({+ stdin,+ stdout,+}: {+ stdin: ConstructorParameters<typeof StdioServerTransport>[0];+ stdout: ConstructorParameters<typeof StdioServerTransport>[1];+}): Promise<McpTransport> => {+ return new StdioServerTransport(stdin, stdout);+};diff --git a/packages/project-build/src/project-session.test.ts b/packages/project-build/src/project-session.test.tsnew file mode 100644index 0000000000..2bdbf12c8d--- /dev/null+++ b/packages/project-build/src/project-session.test.ts@@ -0,0 +1,442 @@+import { describe, expect, test } from "vitest";+import type { BuilderNamespace } from "./contracts/namespaces";+import type { BuilderPatchTransaction } from "./contracts/patch";+import {+ createProjectSession,+ hasProjectSessionPermit,+ redactProjectSessionValue,+} from "./project-session";+import type {+ ProjectSessionCompatibility,+ ProjectSessionPersistedSnapshot,+ ProjectSessionRemoteSnapshot,+ ProjectSessionStorage,+ ProjectSessionTransport,+} from "./project-session";+import { createBuilderStateFromSnapshot } from "./state/adapters";+import { createBuilderStateFreshness } from "./state/freshness";+import { build } from "./state/fixtures.test-utils";++const compatibilityVersion = "test-session";+const compatibility: ProjectSessionCompatibility = {+ sessionVersion: compatibilityVersion,+ runtimeContractVersion: "test-runtime-contracts",+ projectSchemaVersion: "test-project-schema",+ apiCompatibilityVersion: "test-api",+};++const createSnapshot = (+ overrides: Partial<ProjectSessionRemoteSnapshot> = {}+) => {+ const state = createBuilderStateFromSnapshot(build);+ return {+ projectId: "project-1",+ buildId: "build-1",+ version: 1,+ state,+ ...overrides,+ };+};++const createPersistedSnapshot = (+ overrides: Partial<ProjectSessionPersistedSnapshot> = {}+): ProjectSessionPersistedSnapshot => {+ const snapshot = createSnapshot(overrides);+ return {+ ...snapshot,+ freshness: createBuilderStateFreshness({+ state: snapshot.state,+ version: snapshot.version,+ }),+ compatibilityVersion,+ compatibility,+ revision: "rev-1",+ ...overrides,+ };+};++const createStorage = (+ initial?: ProjectSessionPersistedSnapshot+): ProjectSessionStorage & {+ saved: ProjectSessionPersistedSnapshot[];+ cleared: boolean;+} => {+ let current = initial;+ let revision = initial?.revision;+ return {+ saved: [],+ cleared: false,+ async load() {+ return current;+ },+ async save(snapshot, options) {+ expect(options.expectedRevision).toBe(revision);+ revision = `rev-${Number(revision?.replace("rev-", "") ?? 0) + 1}`;+ current = { ...snapshot, revision };+ this.saved.push(current);+ return { revision };+ },+ async clear() {+ current = undefined;+ revision = undefined;+ this.cleared = true;+ },+ };+};++const createTransport = (+ remote = createSnapshot()+): ProjectSessionTransport & {+ loadedNamespaces: BuilderNamespace[][];+ commits: BuilderPatchTransaction[][];+ permissionReads: number;+} => ({+ loadedNamespaces: [],+ commits: [],+ permissionReads: 0,+ async fetchNamespaces(input) {+ this.loadedNamespaces.push([...input.namespaces]);+ return remote;+ },+ async commitPatch(input) {+ this.commits.push([...input.transactions]);+ return { version: input.baseVersion + 1 };+ },+ async getPermissions() {+ this.permissionReads += 1;+ return {+ canView: true,+ canEdit: true,+ canBuild: true,+ canAdmin: false,+ canUseApi: true,+ };+ },+ async getCompatibility() {+ return compatibility;+ },+ async executeServerOperation<Result>(input: {+ operationId: string;+ input: unknown;+ }) {+ return { operationId: input.operationId } as unknown as Result;+ },+});++const createSession = ({+ storage = createStorage(),+ transport = createTransport(),+}: {+ storage?: ProjectSessionStorage;+ transport?: ProjectSessionTransport;+} = {}) =>+ createProjectSession({+ projectId: "project-1",+ storage,+ transport,+ compatibilityVersion,+ runtimeContext: {+ createId: () => "generated-id",+ now: () => new Date("2024-01-01T00:00:00.000Z"),+ },+ });++describe("project session", () => {+ test("initializes from compatible persisted state and serves reads locally", async () => {+ const storage = createStorage(createPersistedSnapshot());+ const transport = createTransport();+ const session = createSession({ storage, transport });++ await session.initialize();+ const result = await session.read("pages.list", { projectId: "project-1" });++ expect(result.source).toBe("local");+ expect(result.state.committed).toBe(false);+ expect(result.namespaces.read).toEqual(["pages"]);+ expect(transport.loadedNamespaces).toEqual([]);+ });++ test("clears persisted state when compatibility metadata changed", async () => {+ const storage = createStorage(+ createPersistedSnapshot({+ compatibility: {+ ...compatibility,+ runtimeContractVersion: "old-runtime-contracts",+ },+ })+ );+ const session = createSession({ storage });++ const result = await session.initialize();++ expect(result.result).toEqual({ loaded: false });+ expect(storage.cleared).toBe(true);+ });++ test("refreshes missing namespaces from remote and persists atomically", async () => {+ const storage = createStorage();+ const transport = createTransport();+ const session = createSession({ storage, transport });++ const result = await session.read("pages.list", { projectId: "project-1" });++ expect(result.source).toBe("local");+ expect(transport.loadedNamespaces).toEqual([["pages"]]);+ expect(storage.saved).toHaveLength(1);+ });++ test("does not update local state during dry-run mutations", async () => {+ const storage = createStorage(createPersistedSnapshot());+ const transport = createTransport();+ const session = createSession({ storage, transport });++ await session.initialize();+ const result = await session.mutate(+ "folders.create",+ { name: "Draft", slug: "draft" },+ { dryRun: true }+ );++ expect(result.source).toBe("dry-run");+ expect(result.state.committed).toBe(false);+ expect(result.transaction?.payload).toHaveLength(1);+ expect(transport.commits).toEqual([]);+ expect(storage.saved).toHaveLength(0);+ });++ test("commits remotely before applying mutation locally", async () => {+ const storage = createStorage(createPersistedSnapshot());+ const transport = createTransport();+ const session = createSession({ storage, transport });++ await session.initialize();+ const result = await session.mutate("folders.create", {+ name: "New",+ slug: "new",+ });++ expect(result.source).toBe("remote");+ expect(result.state.committed).toBe(true);+ expect(result.version).toBe(2);+ expect(transport.commits).toHaveLength(1);+ expect(storage.saved.at(-1)?.version).toBe(2);+ expect(storage.saved.at(-1)?.state.pages?.folders.has("generated-id")).toBe(+ true+ );+ });++ test("refreshes required namespaces and returns conflict diagnostic", async () => {+ const storage = createStorage(createPersistedSnapshot());+ const transport = createTransport();+ transport.commitPatch = async () => {+ throw Object.assign(new Error("Build version mismatch"), {+ code: "CONFLICT",+ });+ };+ const session = createSession({ storage, transport });++ await session.initialize();+ const result = await session.mutate("folders.create", {+ name: "New",+ slug: "new",+ });++ expect(result.state.committed).toBe(false);+ expect(result.diagnostics).toEqual([+ expect.objectContaining({ code: "CONFLICT" }),+ expect.objectContaining({ code: "CONFLICT_REFRESHED" }),+ ]);+ expect(transport.loadedNamespaces).toEqual([["pages"]]);+ });++ test("retries retry-safe mutations once after conflict refresh", async () => {+ const storage = createStorage(createPersistedSnapshot());+ const transport = createTransport(createSnapshot({ version: 2 }));+ let attempts = 0;+ transport.commitPatch = async (input) => {+ attempts += 1;+ transport.commits.push([...input.transactions]);+ if (attempts === 1) {+ throw Object.assign(new Error("Build version mismatch"), {+ code: "CONFLICT",+ });+ }+ return { version: input.baseVersion + 1 };+ };+ const session = createSession({ storage, transport });++ await session.initialize();+ const result = await session.mutate("pages.update", {+ pageId: "page-home",+ values: { name: "Home updated" },+ });++ expect(result.state.committed).toBe(true);+ expect(result.version).toBe(3);+ expect(result.diagnostics).toEqual([+ expect.objectContaining({ code: "CONFLICT" }),+ expect.objectContaining({ code: "CONFLICT_REFRESHED" }),+ expect.objectContaining({ code: "CONFLICT_RETRY" }),+ ]);+ expect(transport.loadedNamespaces).toEqual([["pages"]]);+ expect(transport.commits).toHaveLength(2);+ });++ test("checks and caches permissions for local runtime mutations", async () => {+ const storage = createStorage(createPersistedSnapshot());+ const transport = createTransport();+ const session = createSession({ storage, transport });++ await session.initialize();+ await session.mutate(+ "folders.create",+ { name: "First", slug: "first" },+ { permit: "build" }+ );+ await session.mutate(+ "folders.create",+ { name: "Second", slug: "second" },+ { permit: "build" }+ );++ expect(transport.permissionReads).toBe(1);+ });++ test("returns diagnostic when cached permissions deny local mutation", async () => {+ const storage = createStorage(createPersistedSnapshot());+ const transport = createTransport();+ transport.getPermissions = async () => {+ transport.permissionReads += 1;+ return {+ canView: true,+ canEdit: false,+ canBuild: false,+ canAdmin: false,+ canUseApi: true,+ };+ };+ const session = createSession({ storage, transport });++ await session.initialize();+ const result = await session.mutate(+ "folders.create",+ { name: "New", slug: "new" },+ { permit: "build" }+ );++ expect(result.state.committed).toBe(false);+ expect(result.diagnostics).toEqual([+ expect.objectContaining({+ level: "error",+ message: "Authorization token does not have build permission.",+ }),+ ]);+ expect(transport.commits).toEqual([]);+ });++ test("clears cached permissions after plan errors", async () => {+ const storage = createStorage(createPersistedSnapshot());+ const transport = createTransport();+ let attempts = 0;+ transport.commitPatch = async () => {+ attempts += 1;+ if (attempts === 1) {+ throw Object.assign(new Error("API permission requires an upgrade."), {+ code: "PLAN_REQUIRED",+ });+ }+ return { version: 2 };+ };+ const session = createSession({ storage, transport });++ await session.initialize();+ await session.mutate(+ "folders.create",+ { name: "First", slug: "first" },+ { permit: "build" }+ );+ await session.mutate(+ "folders.create",+ { name: "Second", slug: "second" },+ { permit: "build" }+ );++ expect(transport.permissionReads).toBe(2);+ });++ test("marks server-only invalidated namespaces stale without guessing semantics", async () => {+ const storage = createStorage(createPersistedSnapshot());+ const transport = createTransport();+ const session = createSession({ storage, transport });++ await session.initialize();+ const result = await session.executeServerOperation(+ { id: "upload-asset", invalidatesNamespaces: ["assets"] },+ { file: "image.png" }+ );++ expect(result.source).toBe("server");+ expect(result.namespaces.invalidated).toEqual(["assets"]);+ expect(storage.saved.at(-1)?.freshness.assets?.status).toBe("invalidated");+ });++ test("returns refreshed snapshot metadata after server-only invalidation refetch", async () => {+ const storage = createStorage(createPersistedSnapshot());+ const transport = createTransport(createSnapshot({ version: 5 }));+ const session = createSession({ storage, transport });++ await session.initialize();+ const result = await session.executeServerOperation(+ {+ id: "upload-asset",+ invalidatesNamespaces: ["assets"],+ refetchInvalidatedNamespaces: true,+ },+ { file: "image.png" }+ );++ expect(result.version).toBe(5);+ expect(result.state.freshness.assets?.status).toBe("fresh");+ expect(transport.loadedNamespaces).toEqual([["assets"]]);+ expect(storage.saved.at(-1)?.version).toBe(5);+ });++ test("redacts sensitive diagnostic values", () => {+ expect(+ redactProjectSessionValue({+ authToken: "secret",+ nested: { token: "secret", value: "visible" },+ })+ ).toEqual({+ authToken: "[redacted]",+ nested: { token: "[redacted]", value: "visible" },+ });+ });++ test("requires api permission before local project permits", () => {+ expect(+ hasProjectSessionPermit(+ {+ canView: true,+ canEdit: true,+ canBuild: true,+ canAdmin: true,+ canUseApi: false,+ },+ "build"+ )+ ).toBe(false);+ expect(+ hasProjectSessionPermit(+ {+ canView: true,+ canEdit: false,+ canBuild: false,+ canAdmin: false,+ canUseApi: true,+ },+ "view"+ )+ ).toBe(true);+ });+});diff --git a/packages/project-build/src/project-session.ts b/packages/project-build/src/project-session.tsnew file mode 100644index 0000000000..7eb2c7715b--- /dev/null+++ b/packages/project-build/src/project-session.ts@@ -0,0 +1,900 @@+import type {+ RuntimeOperationContract,+ RuntimeOperationId,+} from "./contracts/builder-runtime";+import { runtimeOperationContracts } from "./contracts/builder-runtime";+import type { BuilderNamespace } from "./contracts/namespaces";+import type { BuilderPatchTransaction } from "./contracts/patch";+import type { BuilderRuntimeContext } from "./runtime/context";+import { BuilderRuntimeError } from "./runtime/errors";+import type { BuilderRuntimeMutation } from "./runtime/mutation";+import { executeBuilderRuntimeOperation } from "./runtime/registry";+import type { BuilderState } from "./state/builder-state";+import { getMissingBuilderStateNamespaces } from "./state/builder-state";+import {+ createBuilderStateFreshness,+ getBuilderStateNamespaceFreshness,+ markBuilderStateNamespacesInvalidated,+ markBuilderStateNamespacesStale,+ type BuilderStateFreshness,+} from "./state/freshness";+import { applyBuilderPatchTransactions } from "./state/patch";++type ProjectSessionSource = "local" | "remote" | "dry-run" | "server";+type ProjectSessionDiagnosticLevel = "info" | "warning" | "error";++export type ProjectSessionDiagnostic = {+ level: ProjectSessionDiagnosticLevel;+ code: string;+ message: string;+ details?: unknown;+};++export type ProjectSessionSnapshot = {+ projectId: string;+ buildId: string;+ version: number;+ state: BuilderState;+ freshness: BuilderStateFreshness;+ compatibilityVersion: string;+ compatibility: ProjectSessionCompatibility;+};++export type ProjectSessionPersistedSnapshot = ProjectSessionSnapshot & {+ revision?: string;+};++export type ProjectSessionRemoteSnapshot = {+ projectId: string;+ buildId: string;+ version: number;+ state: BuilderState;+};++export type ProjectSessionCommitResult = {+ version: number;+};++export type ProjectSessionPermit = "api" | "view" | "build" | "edit" | "admin";++export type ProjectSessionPermissions = {+ canView: boolean;+ canEdit: boolean;+ canBuild: boolean;+ canAdmin: boolean;+ canUseApi: boolean;+};++export type ProjectSessionCompatibility = {+ sessionVersion: string;+ runtimeContractVersion: string;+ projectSchemaVersion: string;+ apiCompatibilityVersion?: string;+};++export type ProjectSessionTransport = {+ getCompatibility?: (input: {+ projectId: string;+ }) => Promise<ProjectSessionCompatibility>;+ fetchNamespaces: (input: {+ projectId: string;+ namespaces: readonly BuilderNamespace[];+ }) => Promise<ProjectSessionRemoteSnapshot>;+ commitPatch: (input: {+ projectId: string;+ buildId: string;+ baseVersion: number;+ transactions: readonly BuilderPatchTransaction[];+ }) => Promise<ProjectSessionCommitResult>;+ executeServerOperation?: <Result>(input: {+ operationId: string;+ input: unknown;+ }) => Promise<Result>;+ getPermissions?: (input: {+ projectId: string;+ }) => Promise<ProjectSessionPermissions>;+};++export type ProjectSessionStorage = {+ load: () => Promise<ProjectSessionPersistedSnapshot | undefined>;+ save: (+ snapshot: ProjectSessionSnapshot,+ options: { expectedRevision?: string }+ ) => Promise<{ revision?: string } | undefined>;+ clear: () => Promise<void>;+};++export type ProjectSessionOptions = {+ projectId: string;+ transport: ProjectSessionTransport;+ storage: ProjectSessionStorage;+ runtimeContext: BuilderRuntimeContext;+ compatibilityVersion?: string;+};++export type ProjectSessionEnvelope<Result = unknown> = {+ operationId: string;+ projectId: string;+ buildId?: string;+ version?: number;+ source: ProjectSessionSource;+ result: Result;+ state: {+ committed: boolean;+ freshness: BuilderStateFreshness;+ compatibility?: ProjectSessionCompatibility;+ };+ namespaces: {+ read: readonly BuilderNamespace[];+ write: readonly BuilderNamespace[];+ invalidated: readonly BuilderNamespace[];+ missing: readonly BuilderNamespace[];+ };+ diagnostics: ProjectSessionDiagnostic[];+ transaction?: BuilderPatchTransaction;+};++export type ProjectSessionMutationOptions = {+ dryRun?: boolean;+ permit?: ProjectSessionPermit;+};++export type ProjectSessionReadOptions = {+ permit?: ProjectSessionPermit;+};++export type ProjectSessionServerOperationDescriptor = {+ id: string;+ invalidatesNamespaces?: readonly BuilderNamespace[];+ refetchInvalidatedNamespaces?: boolean;+};++const defaultCompatibilityVersion = "project-session-v1";+const defaultRuntimeContractVersion = `runtime-contracts:${runtimeOperationContracts+ .map((contract) => contract.id)+ .join(",")}`;+const defaultProjectSchemaVersion = "builder-state-v1";++export const createDefaultProjectSessionCompatibility = (+ sessionVersion: string+): ProjectSessionCompatibility => ({+ sessionVersion,+ runtimeContractVersion: defaultRuntimeContractVersion,+ projectSchemaVersion: defaultProjectSchemaVersion,+});++const isCompatible = (+ snapshot: ProjectSessionPersistedSnapshot,+ compatibility: ProjectSessionCompatibility+) => {+ const snapshotCompatibility =+ snapshot.compatibility ??+ createDefaultProjectSessionCompatibility(snapshot.compatibilityVersion);+ return (+ snapshotCompatibility.sessionVersion === compatibility.sessionVersion &&+ snapshotCompatibility.runtimeContractVersion ===+ compatibility.runtimeContractVersion &&+ snapshotCompatibility.projectSchemaVersion ===+ compatibility.projectSchemaVersion &&+ snapshotCompatibility.apiCompatibilityVersion ===+ compatibility.apiCompatibilityVersion+ );+};++const operationContractById = new Map(+ runtimeOperationContracts.map((contract) => [contract.id, contract])+);++const getRuntimeOperationContract = (+ operationId: RuntimeOperationId+): RuntimeOperationContract => {+ const contract = operationContractById.get(operationId);+ if (contract === undefined) {+ throw new Error(`Runtime operation "${operationId}" is not in contracts.`);+ }+ return contract;+};++const mergeBuilderState = (+ current: BuilderState,+ incoming: BuilderState,+ namespaces: readonly BuilderNamespace[]+): BuilderState => {+ const next = { ...current };+ for (const namespace of namespaces) {+ const value = incoming[namespace];+ if (value !== undefined) {+ (next as Record<string, unknown>)[namespace] = value;+ }+ }+ return next;+};++const isFresh = (+ freshness: BuilderStateFreshness,+ namespace: BuilderNamespace+) => getBuilderStateNamespaceFreshness(freshness, namespace).status === "fresh";++const getNamespacesNeedingRemote = (+ snapshot: ProjectSessionSnapshot | undefined,+ namespaces: readonly BuilderNamespace[]+) => {+ if (snapshot === undefined) {+ return namespaces;+ }+ return namespaces.filter(+ (namespace) =>+ snapshot.state[namespace] === undefined ||+ isFresh(snapshot.freshness, namespace) === false+ );+};++const createFreshness = (+ state: BuilderState,+ version: number+): BuilderStateFreshness => createBuilderStateFreshness({ state, version });++const mergeFreshness = ({+ current,+ state,+ namespaces,+ version,+}: {+ current: BuilderStateFreshness | undefined;+ state: BuilderState;+ namespaces: readonly BuilderNamespace[];+ version: number;+}): BuilderStateFreshness => {+ const next =+ current === undefined+ ? createBuilderStateFreshness({ state })+ : { ...current };+ const fresh = createFreshness(state, version);+ for (const namespace of namespaces) {+ next[namespace] = fresh[namespace];+ }+ return next;+};++const mergeSnapshot = ({+ current,+ remote,+ namespaces,+ compatibilityVersion,+ compatibility,+}: {+ current: ProjectSessionSnapshot | undefined;+ remote: ProjectSessionRemoteSnapshot;+ namespaces: readonly BuilderNamespace[];+ compatibilityVersion: string;+ compatibility: ProjectSessionCompatibility;+}): ProjectSessionSnapshot => {+ const state = mergeBuilderState(+ current?.state ?? {},+ remote.state,+ namespaces+ );+ return {+ projectId: remote.projectId,+ buildId: remote.buildId,+ version: remote.version,+ state,+ freshness: mergeFreshness({+ current: current?.freshness,+ state,+ namespaces,+ version: remote.version,+ }),+ compatibilityVersion,+ compatibility,+ };+};++const redactKeys = new Set([+ "authorization",+ "auth",+ "authToken",+ "cookie",+ "cookies",+ "password",+ "secret",+ "token",+ "x-auth-token",+]);++const getProjectSessionErrorCode = (error: unknown) => {+ if (error instanceof BuilderRuntimeError) {+ return error.code;+ }+ if (+ error instanceof Error &&+ error.message.includes("Project session snapshot changed on disk")+ ) {+ return "PROJECT_SESSION_BUSY";+ }+ if (typeof error === "object" && error !== null) {+ if ("code" in error) {+ const code = error.code;+ if (typeof code === "string") {+ return code;+ }+ }+ }+ return error instanceof Error ? error.name : "UNKNOWN_ERROR";+};++export const redactProjectSessionValue = (value: unknown): unknown => {+ if (Array.isArray(value)) {+ return value.map(redactProjectSessionValue);+ }+ if (typeof value !== "object" || value === null) {+ return value;+ }+ const redacted: Record<string, unknown> = {};+ for (const [key, entry] of Object.entries(value)) {+ redacted[key] = redactKeys.has(key)+ ? "[redacted]"+ : redactProjectSessionValue(entry);+ }+ return redacted;+};++const errorDiagnostic = (error: unknown): ProjectSessionDiagnostic => ({+ level: "error",+ code: getProjectSessionErrorCode(error),+ message: error instanceof Error ? error.message : "Unknown error",+ details: redactProjectSessionValue(error),+});++const shouldRefreshPermissionsAfterError = (error: unknown) => {+ const code = getProjectSessionErrorCode(error);+ return (+ code === "UNAUTHORIZED" || code === "FORBIDDEN" || code === "PLAN_REQUIRED"+ );+};++const isVersionConflictError = (error: unknown) =>+ getProjectSessionErrorCode(error) === "CONFLICT";++export const hasProjectSessionPermit = (+ permissions: ProjectSessionPermissions,+ permit: ProjectSessionPermit+) => {+ if (permit === "api") {+ return permissions.canUseApi;+ }+ if (permissions.canUseApi === false) {+ return false;+ }+ if (permit === "view") {+ return permissions.canView;+ }+ if (permit === "edit") {+ return permissions.canEdit;+ }+ if (permit === "build") {+ return permissions.canBuild;+ }+ return permissions.canAdmin;+};++export class ProjectSession {+ #snapshot: ProjectSessionSnapshot | undefined;+ #revision: string | undefined;+ #permissions: ProjectSessionPermissions | undefined;+ #mutationQueue: Promise<unknown> = Promise.resolve();+ #options: Required<Pick<ProjectSessionOptions, "compatibilityVersion">> &+ ProjectSessionOptions;++ constructor(options: ProjectSessionOptions) {+ this.#options = {+ ...options,+ compatibilityVersion:+ options.compatibilityVersion ?? defaultCompatibilityVersion,+ };+ }++ get snapshot() {+ return this.#snapshot;+ }++ async getCompatibility() {+ return (+ (await this.#options.transport.getCompatibility?.({+ projectId: this.#options.projectId,+ })) ??+ createDefaultProjectSessionCompatibility(+ this.#options.compatibilityVersion+ )+ );+ }++ async initialize() {+ const persisted = await this.#options.storage.load();+ if (persisted === undefined) {+ return this.status(["No persisted project session snapshot found."]);+ }+ const compatibility = await this.getCompatibility();+ if (+ persisted.projectId !== this.#options.projectId ||+ isCompatible(persisted, compatibility) === false+ ) {+ await this.#options.storage.clear();+ this.#snapshot = undefined;+ this.#revision = undefined;+ return this.status([+ "Persisted project session snapshot is incompatible.",+ ]);+ }+ const { revision, ...snapshot } = persisted;+ this.#snapshot = { ...snapshot, compatibility };+ this.#revision = revision;+ return this.status();+ }++ async reset() {+ await this.#options.storage.clear();+ this.#snapshot = undefined;+ this.#revision = undefined;+ return this.status(["Project session snapshot was reset."]);+ }++ status(messages: string[] = []): ProjectSessionEnvelope<{+ loaded: boolean;+ }> {+ const diagnostics = messages.map(+ (message): ProjectSessionDiagnostic => ({+ level: "info",+ code: "SESSION_STATUS",+ message,+ })+ );+ return this.createEnvelope({+ source: "local",+ result: { loaded: this.#snapshot !== undefined },+ committed: false,+ contract: emptyContract,+ diagnostics,+ });+ }++ async refresh(namespaces: readonly BuilderNamespace[]) {+ const snapshot = await this.fetchAndSave(namespaces);+ return this.createEnvelope({+ source: "remote",+ result: {+ refreshedNamespaces: namespaces,+ },+ committed: false,+ contract: {+ ...emptyContract,+ readNamespaces: namespaces,+ },+ snapshot,+ });+ }++ async read<Result = unknown>(+ operationId: RuntimeOperationId,+ input: unknown,+ options: ProjectSessionReadOptions = {}+ ): Promise<ProjectSessionEnvelope<Result>> {+ const contract = getRuntimeOperationContract(operationId);+ if (contract.kind !== "read") {+ throw new Error(`Runtime operation "${operationId}" is not a read.`);+ }+ const snapshot = await this.ensureNamespaces(contract.readNamespaces);+ try {+ await this.assertPermit(options.permit);+ const result = executeBuilderRuntimeOperation<Result>({+ id: operationId,+ state: snapshot.state,+ input,+ context: this.#options.runtimeContext,+ });+ return this.createEnvelope({+ source: "local",+ result,+ committed: false,+ contract,+ snapshot,+ });+ } catch (error) {+ this.clearPermissionsAfterAuthorizationError(error);+ return this.createEnvelope({+ source: "local",+ result: undefined as unknown as Result,+ committed: false,+ contract,+ snapshot,+ diagnostics: [errorDiagnostic(error)],+ });+ }+ }++ async mutate<+ Result extends Record<string, unknown> = Record<string, unknown>,+ >(+ operationId: RuntimeOperationId,+ input: unknown,+ options: ProjectSessionMutationOptions = {}+ ): Promise<ProjectSessionEnvelope<Result>> {+ return (await this.enqueueMutation(() =>+ this.mutateUnqueued<Result>(operationId, input, options)+ )) as ProjectSessionEnvelope<Result>;+ }++ async executeServerOperation<Result = unknown>(+ descriptor: ProjectSessionServerOperationDescriptor,+ input: unknown+ ): Promise<ProjectSessionEnvelope<Result>> {+ if (this.#options.transport.executeServerOperation === undefined) {+ throw new Error(+ "Project session transport cannot execute server operations."+ );+ }+ const result = await this.#options.transport.executeServerOperation<Result>(+ {+ operationId: descriptor.id,+ input,+ }+ );+ const invalidated = descriptor.invalidatesNamespaces ?? [];+ let snapshot = this.#snapshot;+ if (snapshot !== undefined && invalidated.length > 0) {+ snapshot = {+ ...snapshot,+ freshness: markBuilderStateNamespacesInvalidated(+ snapshot.freshness,+ invalidated,+ descriptor.id+ ),+ };+ await this.saveSnapshot(snapshot);+ }+ if (descriptor.refetchInvalidatedNamespaces && invalidated.length > 0) {+ snapshot = await this.fetchAndSave(invalidated);+ }+ return this.createEnvelope({+ source: "server",+ result,+ committed: true,+ contract: {+ ...emptyContract,+ id: descriptor.id,+ invalidatesNamespaces: invalidated,+ },+ snapshot,+ });+ }++ async markStale(namespaces: readonly BuilderNamespace[]) {+ if (this.#snapshot === undefined) {+ return this.status(["Project session has no snapshot to mark stale."]);+ }+ this.#snapshot = {+ ...this.#snapshot,+ freshness: markBuilderStateNamespacesStale(+ this.#snapshot.freshness,+ namespaces+ ),+ };+ await this.saveSnapshot(this.#snapshot);+ return this.status(["Project session namespaces were marked stale."]);+ }++ async #loadLocalSnapshot() {+ if (this.#snapshot !== undefined) {+ return this.#snapshot;+ }+ const initialized = await this.#options.storage.load();+ const compatibility = await this.getCompatibility();+ if (+ initialized !== undefined &&+ initialized.projectId === this.#options.projectId &&+ isCompatible(initialized, compatibility)+ ) {+ const { revision, ...snapshot } = initialized;+ this.#snapshot = { ...snapshot, compatibility };+ this.#revision = revision;+ }+ return this.#snapshot;+ }++ async ensureNamespaces(namespaces: readonly BuilderNamespace[]) {+ const snapshot = await this.#loadLocalSnapshot();+ const missing = getNamespacesNeedingRemote(snapshot, namespaces);+ if (missing.length === 0 && snapshot !== undefined) {+ return snapshot;+ }+ return await this.fetchAndSave(missing.length === 0 ? namespaces : missing);+ }++ async fetchAndSave(namespaces: readonly BuilderNamespace[]) {+ const current = await this.#loadLocalSnapshot();+ const compatibility = await this.getCompatibility();+ const remote = await this.#options.transport.fetchNamespaces({+ projectId: this.#options.projectId,+ namespaces,+ });+ const snapshot = mergeSnapshot({+ current,+ remote,+ namespaces,+ compatibilityVersion: this.#options.compatibilityVersion,+ compatibility,+ });+ await this.saveSnapshot(snapshot);+ return snapshot;+ }++ async saveSnapshot(snapshot: ProjectSessionSnapshot) {+ const result = await this.#options.storage.save(snapshot, {+ expectedRevision: this.#revision,+ });+ this.#snapshot = snapshot;+ this.#revision = result?.revision;+ }++ async mutateUnqueued<+ Result extends Record<string, unknown> = Record<string, unknown>,+ >(+ operationId: RuntimeOperationId,+ input: unknown,+ options: ProjectSessionMutationOptions+ ) {+ const contract = getRuntimeOperationContract(operationId);+ if (contract.kind !== "mutation") {+ throw new Error(`Runtime operation "${operationId}" is not a mutation.`);+ }+ const requiredNamespaces = [+ ...new Set([...contract.readNamespaces, ...contract.writeNamespaces]),+ ];+ const snapshot = await this.ensureNamespaces(requiredNamespaces);+ try {+ await this.assertPermit(options.permit);+ return await this.commitMutation({+ operationId,+ input,+ options,+ contract,+ snapshot,+ });+ } catch (error) {+ this.clearPermissionsAfterAuthorizationError(error);+ let latestSnapshot = snapshot;+ const diagnostics = [errorDiagnostic(error)];+ if (isVersionConflictError(error)) {+ try {+ latestSnapshot = await this.fetchAndSave(requiredNamespaces);+ diagnostics.push({+ level: "info",+ code: "CONFLICT_REFRESHED",+ message:+ "Remote build changed. Required namespaces were refreshed; rerun the operation against the latest snapshot.",+ });+ if (contract.retryOnConflict && options.dryRun !== true) {+ return await this.commitMutation({+ operationId,+ input,+ options,+ contract,+ snapshot: latestSnapshot,+ diagnostics: [+ ...diagnostics,+ {+ level: "info",+ code: "CONFLICT_RETRY",+ message:+ "Operation is retry-safe and was retried against the refreshed snapshot.",+ },+ ],+ });+ }+ } catch (refreshError) {+ diagnostics.push(errorDiagnostic(refreshError));+ }+ }+ return this.createEnvelope({+ source: "local",+ result: undefined as unknown as Result,+ committed: false,+ contract,+ snapshot: latestSnapshot,+ diagnostics,+ });+ }+ }++ async commitMutation<+ Result extends Record<string, unknown> = Record<string, unknown>,+ >({+ operationId,+ input,+ options,+ contract,+ snapshot,+ diagnostics = [],+ }: {+ operationId: RuntimeOperationId;+ input: unknown;+ options: ProjectSessionMutationOptions;+ contract: RuntimeOperationContract;+ snapshot: ProjectSessionSnapshot;+ diagnostics?: ProjectSessionDiagnostic[];+ }) {+ const mutation = executeBuilderRuntimeOperation<+ BuilderRuntimeMutation<Result>+ >({+ id: operationId,+ state: snapshot.state,+ input,+ context: this.#options.runtimeContext,+ });+ if (mutation.noop) {+ return this.createEnvelope({+ source: "local",+ result: mutation.result,+ committed: false,+ contract,+ snapshot,+ diagnostics,+ });+ }+ const transaction: BuilderPatchTransaction = {+ id: this.#options.runtimeContext.createId(),+ payload: mutation.payload,+ };+ if (options.dryRun) {+ return this.createEnvelope({+ source: "dry-run",+ result: mutation.result,+ committed: false,+ contract,+ snapshot,+ transaction,+ diagnostics: [+ ...diagnostics,+ {+ level: "info",+ code: "DRY_RUN",+ message: "Mutation was planned locally and was not committed.",+ },+ ],+ });+ }+ const commit = await this.#options.transport.commitPatch({+ projectId: snapshot.projectId,+ buildId: snapshot.buildId,+ baseVersion: snapshot.version,+ transactions: [transaction],+ });+ const applied = applyBuilderPatchTransactions(snapshot.state, [+ transaction,+ ]);+ const committedSnapshot: ProjectSessionSnapshot = {+ ...snapshot,+ version: commit.version,+ state: applied.state,+ freshness: createBuilderStateFreshness({+ state: applied.state,+ version: commit.version,+ invalidatedNamespaces: mutation.invalidatesNamespaces,+ invalidatedBy: operationId,+ }),+ };+ await this.saveSnapshot(committedSnapshot);+ return this.createEnvelope({+ source: "remote",+ result: mutation.result,+ committed: true,+ contract: {+ ...contract,+ invalidatesNamespaces: mutation.invalidatesNamespaces,+ },+ snapshot: committedSnapshot,+ transaction,+ diagnostics,+ });+ }++ enqueueMutation<Result>(+ task: () => Promise<ProjectSessionEnvelope<Result>>+ ): Promise<ProjectSessionEnvelope<Result>> {+ const run = this.#mutationQueue.then(task, task);+ this.#mutationQueue = run.catch(() => undefined);+ return run;+ }++ async getPermissions({ force = false }: { force?: boolean } = {}) {+ if (force === false && this.#permissions !== undefined) {+ return this.#permissions;+ }+ if (this.#options.transport.getPermissions === undefined) {+ throw new Error("Project session transport cannot read permissions.");+ }+ this.#permissions = await this.#options.transport.getPermissions({+ projectId: this.#options.projectId,+ });+ return this.#permissions;+ }++ async assertPermit(permit: ProjectSessionPermit | undefined) {+ if (permit === undefined) {+ return;+ }+ const permissions = await this.getPermissions();+ if (hasProjectSessionPermit(permissions, permit) === false) {+ throw new Error(+ `Authorization token does not have ${permit} permission.`+ );+ }+ }++ clearPermissionsAfterAuthorizationError(error: unknown) {+ if (shouldRefreshPermissionsAfterError(error)) {+ this.#permissions = undefined;+ }+ }++ createEnvelope<Result>({+ source,+ result,+ committed,+ contract,+ snapshot = this.#snapshot,+ diagnostics = [],+ transaction,+ }: {+ source: ProjectSessionSource;+ result: Result;+ committed: boolean;+ contract: Pick<+ RuntimeOperationContract,+ "id" | "readNamespaces" | "writeNamespaces" | "invalidatesNamespaces"+ >;+ snapshot?: ProjectSessionSnapshot;+ diagnostics?: ProjectSessionDiagnostic[];+ transaction?: BuilderPatchTransaction;+ }): ProjectSessionEnvelope<Result> {+ return {+ operationId: contract.id,+ projectId: this.#options.projectId,+ buildId: snapshot?.buildId,+ version: snapshot?.version,+ source,+ result,+ state: {+ committed,+ freshness: snapshot?.freshness ?? {},+ compatibility: snapshot?.compatibility,+ },+ namespaces: {+ read: contract.readNamespaces,+ write: contract.writeNamespaces,+ invalidated: contract.invalidatesNamespaces,+ missing:+ snapshot === undefined+ ? [...contract.readNamespaces, ...contract.writeNamespaces]+ : getMissingBuilderStateNamespaces(snapshot.state, [+ ...contract.readNamespaces,+ ...contract.writeNamespaces,+ ]),+ },+ diagnostics,+ transaction,+ };+ }+}++const emptyContract: RuntimeOperationContract = {+ id: "project-session.status",+ kind: "read",+ readNamespaces: [],+ writeNamespaces: [],+ invalidatesNamespaces: [],+ retryOnConflict: false,+};++export const createProjectSession = (options: ProjectSessionOptions) =>+ new ProjectSession(options);diff --git a/packages/project-build/src/runtime/assets.test.ts b/packages/project-build/src/runtime/assets.test.tsnew file mode 100644index 0000000000..a1c35a983e--- /dev/null+++ b/packages/project-build/src/runtime/assets.test.ts@@ -0,0 +1,1057 @@+import { describe, expect, test } from "vitest";+import type { StyleValue } from "@webstudio-is/css-engine";+import {+ createDefaultPages,+ type CompactBuild,+} from "@webstudio-is/project-build";+import type {+ Asset,+ Page,+ Pages,+ Prop,+ Props,+ StyleDecl,+ Styles,+} from "@webstudio-is/sdk";+import type { BuilderState } from "../state/builder-state";+import {+ calculateUsagesByAssetId,+ createAssetDeletePayload,+ createAssetReplacementPayload,+ createAssetUsageList,+ deleteAssets,+ findAsset,+ findAssetUsage,+ listAssets,+ replaceAsset,+ replaceAssetInStyleValueMutable,+ replaceAssetMutable,+} from "./assets";++const imageAsset = (id: string, name = `${id}.png`): Asset =>+ ({+ id,+ projectId: "project",+ name,+ type: "image",+ size: 1,+ format: "png",+ createdAt: "2026-01-01T00:00:00.000Z",+ description: null,+ meta: { width: 100, height: 100 },+ }) as Asset;++const assetProp: Prop = {+ id: "prop",+ instanceId: "body",+ name: "src",+ type: "asset",+ value: "asset",+};++const pages: Pages = {+ homePageId: "home",+ rootFolderId: "root",+ meta: {},+ pages: new Map([+ [+ "home",+ {+ id: "home",+ name: "Home",+ title: "Home",+ path: "",+ rootInstanceId: "body",+ meta: {},+ },+ ],+ ]),+ folders: new Map([+ [+ "root",+ {+ id: "root",+ name: "Root",+ slug: "",+ children: ["home"],+ },+ ],+ ]),+};++const state = {+ pages,+ assets: new Map([+ ["asset", imageAsset("asset", "asset.png")],+ ["next", imageAsset("next", "next.png")],+ ["unused", imageAsset("unused", "unused.png")],+ ]),+ props: new Map([["prop", assetProp]]),+ styles: new Map(),+ resources: new Map(),+ dataSources: new Map(),+} satisfies BuilderState;++describe("asset runtime operations", () => {+ test("lists assets with usage counts", () => {+ expect(listAssets(state, { sort: "usage" })).toMatchObject({+ items: [+ { id: "asset", usageCount: 1 },+ { id: "next", usageCount: 0 },+ { id: "unused", usageCount: 0 },+ ],+ nextCursor: null,+ });+ });++ test("paginates assets and rejects invalid cursors", () => {+ expect(listAssets(state, { cursor: "1", limit: 1 })).toMatchObject({+ items: [{ id: "next" }],+ nextCursor: "2",+ });+ expect(() => listAssets(state, { cursor: "nope" })).toThrow(+ "Invalid asset cursor"+ );+ });++ test("finds asset usage", () => {+ expect(findAssetUsage(state, { assetId: "asset" })).toEqual({+ usages: [+ { namespace: "props", instanceId: "body", path: ["prop", "value"] },+ ],+ });+ });++ test("builds asset replacement mutations", () => {+ expect(+ replaceAsset(state, { fromAssetId: "asset", toAssetId: "next" })+ ).toMatchObject({+ kind: "mutation",+ result: { fromAssetId: "asset", toAssetId: "next" },+ payload: [+ { namespace: "props" },+ { namespace: "assets", patches: [{ op: "remove", path: ["asset"] }] },+ ],+ });+ });++ test("blocks replacing assets referenced by resources or variables", () => {+ expect(() =>+ replaceAsset(+ {+ ...state,+ resources: new Map([+ [+ "resource",+ {+ id: "resource",+ name: "Resource",+ method: "get",+ url: "asset",+ headers: [],+ },+ ],+ ]),+ },+ { fromAssetId: "asset", toAssetId: "next" }+ )+ ).toThrow(+ "Asset is referenced in resources or variables. Update those references before replacing the asset."+ );+ });++ test("blocks deleting referenced assets without force", () => {+ expect(() =>+ deleteAssets(state, { assetIdsOrPrefixes: ["asset"] })+ ).toThrow("Assets are still referenced: asset");+ });++ test("builds asset delete mutations", () => {+ expect(+ deleteAssets(state, { assetIdsOrPrefixes: ["unused"] })+ ).toMatchObject({+ kind: "mutation",+ result: { assetIds: ["unused"] },+ payload: [+ { namespace: "assets", patches: [{ op: "remove", path: ["unused"] }] },+ ],+ });+ });+});+const createPages = ({+ meta = {},+ homeMeta = {},+ pages = new Map(),+}: {+ meta?: Pages["meta"];+ homeMeta?: Page["meta"];+ pages?: Map<Page["id"], Page>;+} = {}): Pages => ({+ meta,+ homePageId: "home",+ rootFolderId: "root",+ pages: new Map([+ [+ "home",+ {+ id: "home",+ name: "Home",+ path: "",+ title: "Home",+ meta: homeMeta,+ rootInstanceId: "root",+ },+ ],+ ...pages,+ ]),+ folders: new Map([+ [+ "root",+ {+ id: "root",+ name: "Root",+ slug: "",+ children: ["home", ...pages.keys()],+ },+ ],+ ]),+});++describe("asset-info", () => {+ describe("calculateUsagesByAssetId", () => {+ test("tracks favicon asset usage", () => {+ const pages = createPages({+ meta: { faviconAssetId: "favicon-asset" },+ });+ const props: Props = new Map();+ const styles: Styles = new Map();+ const assets = new Map<Asset["id"], Asset>();++ const usages = calculateUsagesByAssetId({ pages, props, styles, assets });++ expect(usages.get("favicon-asset")).toEqual([{ type: "favicon" }]);+ });++ test("tracks social image asset usage", () => {+ const pages = createPages({+ homeMeta: { socialImageAssetId: "social-asset" },+ });+ const props: Props = new Map();+ const styles: Styles = new Map();+ const assets = new Map<Asset["id"], Asset>();++ const usages = calculateUsagesByAssetId({ pages, props, styles, assets });++ expect(usages.get("social-asset")).toEqual([+ { type: "socialImage", pageId: "home" },+ ]);+ });++ test("tracks marketplace thumbnail asset usage", () => {+ const pages = createPages({+ pages: new Map([+ [+ "page-1",+ {+ id: "page-1",+ name: "Page 1",+ path: "/page-1",+ title: "Page 1",+ meta: {},+ rootInstanceId: "root-1",+ marketplace: { thumbnailAssetId: "thumbnail-asset" },+ },+ ],+ ]),+ });+ const props: Props = new Map();+ const styles: Styles = new Map();+ const assets = new Map<Asset["id"], Asset>();++ const usages = calculateUsagesByAssetId({ pages, props, styles, assets });++ expect(usages.get("thumbnail-asset")).toEqual([+ { type: "marketplaceThumbnail", pageId: "page-1" },+ ]);+ });++ test("tracks prop asset usage", () => {+ const pages = createPages();+ 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 assets = new Map<Asset["id"], Asset>();++ const usages = calculateUsagesByAssetId({ pages, props, styles, assets });++ expect(usages.get("asset-1")).toEqual([+ { type: "prop", propId: "prop-1" },+ ]);+ });++ test("ignores width and height props", () => {+ const pages = createPages();+ 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 assets = new Map<Asset["id"], Asset>();++ const usages = calculateUsagesByAssetId({ pages, props, styles, assets });++ expect(usages.get("asset-1")).toBeUndefined();+ });++ test("tracks image asset usage in styles", () => {+ const pages = createPages();+ 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 assets = new Map<Asset["id"], Asset>();++ const usages = calculateUsagesByAssetId({ pages, props, styles, assets });++ expect(usages.get("asset-1")).toEqual([+ { type: "style", styleDeclKey: "style-1:breakpoint-1:property" },+ ]);+ });++ test("returns empty map when no usages", () => {+ const pages = createPages();+ const props: Props = new Map();+ const styles: Styles = new Map();+ const assets = new Map<Asset["id"], Asset>();++ const usages = calculateUsagesByAssetId({ pages, props, styles, assets });++ expect(usages.size).toBe(0);+ });++ test("aggregates multiple usages for same asset", () => {+ const pages = createPages({+ meta: { faviconAssetId: "asset-1" },+ homeMeta: { socialImageAssetId: "asset-1" },+ });+ 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 assets = new Map<Asset["id"], Asset>();++ const usages = calculateUsagesByAssetId({ pages, props, styles, assets });++ 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 assets = new Map<Asset["id"], Asset>();++ const usages = calculateUsagesByAssetId({ pages, props, styles, assets });++ expect(usages.size).toBe(0);+ });++ test("tracks multiple assets in tuple style value", () => {+ const pages = createPages();+ 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 assets = new Map<Asset["id"], Asset>();++ const usages = calculateUsagesByAssetId({ pages, props, styles, assets });++ 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" },+ ]);+ });++ test("tracks font asset usage in fontFamily styles", () => {+ const pages = createPages();+ const props: Props = new Map();+ const styles: Styles = new Map([+ [+ "style-1:breakpoint-1:fontFamily",+ {+ breakpointId: "breakpoint-1",+ styleSourceId: "style-1",+ property: "fontFamily",+ value: {+ type: "fontFamily",+ value: ["CustomFont", "Arial", "sans-serif"],+ },+ },+ ],+ ]);+ const assets = new Map<Asset["id"], Asset>([+ [+ "font-asset-1",+ {+ id: "font-asset-1",+ type: "font",+ name: "CustomFont",+ format: "woff2",+ size: 5000,+ meta: { family: "CustomFont", style: "normal", weight: 400 },+ createdAt: "2024-01-01",+ projectId: "project-id",+ },+ ],+ ]);++ const usages = calculateUsagesByAssetId({ pages, props, styles, assets });++ expect(usages.get("font-asset-1")).toEqual([+ { type: "style", styleDeclKey: "style-1:breakpoint-1:fontFamily" },+ ]);+ });++ test("tracks multiple font assets in same fontFamily style", () => {+ const pages = createPages();+ const props: Props = new Map();+ const styles: Styles = new Map([+ [+ "style-1:breakpoint-1:fontFamily",+ {+ breakpointId: "breakpoint-1",+ styleSourceId: "style-1",+ property: "fontFamily",+ value: {+ type: "fontFamily",+ value: ["CustomFont", "AnotherFont"],+ },+ },+ ],+ ]);+ const assets = new Map<Asset["id"], Asset>([+ [+ "font-asset-1",+ {+ id: "font-asset-1",+ type: "font",+ name: "CustomFont",+ format: "woff2",+ size: 5000,+ meta: { family: "CustomFont", style: "normal", weight: 400 },+ createdAt: "2024-01-01",+ projectId: "project-id",+ },+ ],+ [+ "font-asset-2",+ {+ id: "font-asset-2",+ type: "font",+ name: "AnotherFont",+ format: "woff2",+ size: 6000,+ meta: { family: "AnotherFont", style: "normal", weight: 400 },+ createdAt: "2024-01-01",+ projectId: "project-id",+ },+ ],+ ]);++ const usages = calculateUsagesByAssetId({ pages, props, styles, assets });++ expect(usages.get("font-asset-1")).toEqual([+ { type: "style", styleDeclKey: "style-1:breakpoint-1:fontFamily" },+ ]);+ expect(usages.get("font-asset-2")).toEqual([+ { type: "style", styleDeclKey: "style-1:breakpoint-1:fontFamily" },+ ]);+ });++ test("ignores font families without matching assets", () => {+ const pages = createPages();+ const props: Props = new Map();+ const styles: Styles = new Map([+ [+ "style-1:breakpoint-1:fontFamily",+ {+ breakpointId: "breakpoint-1",+ styleSourceId: "style-1",+ property: "fontFamily",+ value: {+ type: "fontFamily",+ value: ["Arial", "sans-serif"],+ },+ },+ ],+ ]);+ const assets = new Map<Asset["id"], Asset>();++ const usages = calculateUsagesByAssetId({ pages, props, styles, assets });++ expect(usages.size).toBe(0);+ });++ test("tracks same font used in multiple styles", () => {+ const pages = createPages();+ const props: Props = new Map();+ const styles: Styles = new Map([+ [+ "style-1:breakpoint-1:fontFamily",+ {+ breakpointId: "breakpoint-1",+ styleSourceId: "style-1",+ property: "fontFamily",+ value: {+ type: "fontFamily",+ value: ["CustomFont"],+ },+ },+ ],+ [+ "style-2:breakpoint-1:fontFamily",+ {+ breakpointId: "breakpoint-1",+ styleSourceId: "style-2",+ property: "fontFamily",+ value: {+ type: "fontFamily",+ value: ["CustomFont"],+ },+ },+ ],+ ]);+ const assets = new Map<Asset["id"], Asset>([+ [+ "font-asset-1",+ {+ id: "font-asset-1",+ type: "font",+ name: "CustomFont",+ format: "woff2",+ size: 5000,+ meta: { family: "CustomFont", style: "normal", weight: 400 },+ createdAt: "2024-01-01",+ projectId: "project-id",+ },+ ],+ ]);++ const usages = calculateUsagesByAssetId({ pages, props, styles, assets });++ expect(usages.get("font-asset-1")).toEqual([+ { type: "style", styleDeclKey: "style-1:breakpoint-1:fontFamily" },+ { type: "style", styleDeclKey: "style-2:breakpoint-1:fontFamily" },+ ]);+ });+ });+});+const createAsset = (id: string): Asset =>+ ({+ id,+ projectId: "project",+ name: `${id}.png`,+ type: "image",+ size: 1,+ format: "png",+ createdAt: "2024-01-01T00:00:00.000Z",+ description: null,+ }) as Asset;++test("creates asset delete payload", () => {+ expect(createAssetDeletePayload([createAsset("asset-1")])).toEqual([+ {+ namespace: "assets",+ patches: [{ op: "remove", path: ["asset-1"] }],+ },+ ]);+});++test("creates asset usage list from project, pages, props, styles, and resources", () => {+ const asset = createAsset("asset-1");+ const fontAsset: Asset = {+ ...createAsset("font-1"),+ type: "font",+ name: "font.woff2",+ format: "woff2",+ meta: { family: "Inter", style: "normal", weight: 400 },+ };+ const build = {+ pages: {+ meta: { faviconAssetId: asset.id },+ homePage: { id: "page-1" },+ pages: new Map([+ [+ "page-1",+ {+ id: "page-1",+ name: "Home",+ path: "/",+ title: "",+ meta: { socialImageAssetId: asset.id },+ rootInstanceId: "root",+ },+ ],+ [+ "page-2",+ {+ id: "page-2",+ name: "Product",+ path: "/product",+ title: "",+ meta: {},+ marketplace: { thumbnailAssetId: asset.id },+ rootInstanceId: "root",+ },+ ],+ ]),+ folders: new Map([["root", { id: "root", name: "", children: [] }]]),+ },+ props: [+ {+ id: "prop-1",+ instanceId: "box",+ name: "src",+ type: "asset",+ value: asset.id,+ },+ ],+ styles: [+ {+ styleSourceId: "local",+ breakpointId: "base",+ property: "backgroundImage",+ value: { type: "image", value: { type: "asset", value: asset.id } },+ },+ {+ styleSourceId: "local",+ breakpointId: "base",+ property: "fontFamily",+ value: { type: "fontFamily", value: ["Inter"] },+ },+ ],+ resources: [+ {+ id: "resource-1",+ name: "Resource",+ method: "get",+ url: asset.id,+ headers: [],+ },+ ],+ dataSources: [+ {+ id: "data-source-1",+ type: "variable",+ name: "Variable",+ value: { type: "string", value: asset.id },+ },+ ],+ } as unknown as CompactBuild;++ expect(+ createAssetUsageList({ asset, assets: [asset, fontAsset], build })+ ).toEqual([+ { namespace: "project", path: ["meta", "faviconAssetId"] },+ {+ namespace: "pages",+ pageId: "page-1",+ path: ["pages", "page-1", "meta", "socialImageAssetId"],+ },+ {+ namespace: "pages",+ pageId: "page-2",+ path: ["pages", "page-2", "marketplace", "thumbnailAssetId"],+ },+ { namespace: "props", instanceId: "box", path: ["prop-1", "value"] },+ { namespace: "styles", path: ["local:base:backgroundImage:", "value"] },+ { namespace: "resources", path: ["resource-1"] },+ { namespace: "dataSources", path: ["data-source-1"] },+ ]);++ expect(+ createAssetUsageList({+ asset: fontAsset,+ assets: [asset, fontAsset],+ build,+ })+ ).toEqual([+ { namespace: "styles", path: ["local:base:fontFamily:", "value"] },+ ]);+});++test("does not count resource or data source metadata as asset usage", () => {+ const asset = createAsset("asset-1");+ const build = {+ pages: createDefaultPages({ rootInstanceId: "root" }),+ props: [],+ styles: [],+ resources: [+ {+ id: asset.id,+ name: asset.id,+ method: "get",+ url: "https://example.com",+ headers: [{ name: asset.id, value: "header-value" }],+ },+ ],+ dataSources: [+ {+ id: asset.id,+ type: "resource",+ name: asset.id,+ resourceId: asset.id,+ },+ ],+ } as unknown as CompactBuild;++ expect(createAssetUsageList({ asset, assets: [asset], build })).toEqual([]);+});++const replaceAssetInStyleValue = (+ value: StyleValue,+ fromAssetId: string,+ toAssetId: string+) => replaceAssetInStyleValueMutable(value, { fromAssetId, toAssetId });++describe("replaceAssetInStyleValue", () => {+ test("finds assets by id", () => {+ expect(+ findAsset(+ [+ { id: "asset-1", type: "image" },+ { id: "asset-2", type: "image" },+ ] as never,+ "asset-2"+ )+ ).toEqual({ id: "asset-2", type: "image" });+ expect(findAsset([], "missing")).toBeUndefined();+ });++ test("replaces asset id in a direct image value", () => {+ const value: StyleValue = {+ type: "image",+ value: { type: "asset", value: "old-id" },+ };+ replaceAssetInStyleValue(value, "old-id", "new-id");+ expect(value).toEqual({+ type: "image",+ value: { type: "asset", value: "new-id" },+ });+ });++ test("does not mutate image value with a different asset id", () => {+ const value: StyleValue = {+ type: "image",+ value: { type: "asset", value: "other-id" },+ };+ replaceAssetInStyleValue(value, "old-id", "new-id");+ expect(value).toEqual({+ type: "image",+ value: { type: "asset", value: "other-id" },+ });+ });++ test("does not mutate image value with url type", () => {+ const value: StyleValue = {+ type: "image",+ value: { type: "url", url: "https://example.com/img.png" },+ };+ replaceAssetInStyleValue(value, "old-id", "new-id");+ expect(value).toEqual({+ type: "image",+ value: { type: "url", url: "https://example.com/img.png" },+ });+ });++ test("replaces asset id inside a tuple value", () => {+ const value: StyleValue = {+ type: "tuple",+ value: [+ { type: "image", value: { type: "asset", value: "old-id" } },+ { type: "image", value: { type: "asset", value: "other-id" } },+ ],+ };+ replaceAssetInStyleValue(value, "old-id", "new-id");+ expect(value).toEqual({+ type: "tuple",+ value: [+ { type: "image", value: { type: "asset", value: "new-id" } },+ { type: "image", value: { type: "asset", value: "other-id" } },+ ],+ });+ });++ test("replaces asset id inside a layers value", () => {+ const value: StyleValue = {+ type: "layers",+ value: [+ { type: "image", value: { type: "asset", value: "old-id" } },+ { type: "image", value: { type: "asset", value: "old-id" } },+ ],+ };+ replaceAssetInStyleValue(value, "old-id", "new-id");+ expect(value).toEqual({+ type: "layers",+ value: [+ { type: "image", value: { type: "asset", value: "new-id" } },+ { type: "image", value: { type: "asset", value: "new-id" } },+ ],+ });+ });++ test("does not mutate non-image value types", () => {+ const value: StyleValue = { type: "keyword", value: "auto" };+ replaceAssetInStyleValue(value, "old-id", "new-id");+ expect(value).toEqual({ type: "keyword", value: "auto" });+ });++ test("replaces font family when provided", () => {+ const value: StyleValue = {+ type: "fontFamily",+ value: ["Inter", "sans-serif"],+ };+ replaceAssetInStyleValueMutable(value, {+ fromAssetId: "old-id",+ toAssetId: "new-id",+ fromFontFamily: "Inter",+ toFontFamily: "Roboto",+ });+ expect(value).toEqual({+ type: "fontFamily",+ value: ["Roboto", "sans-serif"],+ });+ });++ test("replaces asset references in pages props and styles", () => {+ const pages = createDefaultPages({ rootInstanceId: "root" });+ pages.meta = { faviconAssetId: "old-id" };+ const homePage = pages.pages.get(pages.homePageId);+ if (homePage === undefined) {+ throw new Error("Expected home page");+ }+ homePage.meta.socialImageAssetId = "old-id";+ homePage.marketplace = { thumbnailAssetId: "old-id" };+ const prop = {+ id: "prop",+ instanceId: "root",+ name: "src",+ type: "asset" as const,+ value: "old-id",+ };+ const style: StyleDecl = {+ styleSourceId: "local",+ breakpointId: "base",+ property: "backgroundImage",+ value: {+ type: "image" as const,+ value: { type: "asset" as const, value: "old-id" },+ },+ };++ replaceAssetMutable({+ pages,+ props: [prop],+ styles: [style],+ replacement: { fromAssetId: "old-id", toAssetId: "new-id" },+ });++ expect(pages.meta.faviconAssetId).toBe("new-id");+ expect(homePage.meta.socialImageAssetId).toBe("new-id");+ expect(homePage.marketplace.thumbnailAssetId).toBe("new-id");+ expect(prop.value).toBe("new-id");+ expect(style.value).toEqual({+ type: "image",+ value: { type: "asset", value: "new-id" },+ });+ });++ test("creates asset replacement payload", () => {+ const pages = createDefaultPages({ rootInstanceId: "root" });+ pages.meta = { faviconAssetId: "old-id" };+ const homePage = pages.pages.get(pages.homePageId);+ if (homePage === undefined) {+ throw new Error("Expected home page");+ }+ homePage.meta.socialImageAssetId = "old-id";++ expect(+ createAssetReplacementPayload({+ build: {+ pages,+ props: [+ {+ id: "prop",+ instanceId: "root",+ name: "src",+ type: "asset",+ value: "old-id",+ },+ ],+ styles: [+ {+ styleSourceId: "local",+ breakpointId: "base",+ property: "backgroundImage",+ value: {+ type: "image",+ value: { type: "asset", value: "old-id" },+ },+ },+ ],+ } as never,+ fromAsset: {+ id: "old-id",+ type: "image",+ } as never,+ toAsset: {+ id: "new-id",+ type: "image",+ } as never,+ })+ ).toEqual([+ {+ namespace: "pages",+ patches: [+ {+ op: "replace",+ path: ["meta", "faviconAssetId"],+ value: "new-id",+ },+ {+ op: "replace",+ path: ["pages", pages.homePageId, "meta", "socialImageAssetId"],+ value: "new-id",+ },+ ],+ },+ {+ namespace: "props",+ patches: [+ {+ op: "replace",+ path: ["prop"],+ value: {+ id: "prop",+ instanceId: "root",+ name: "src",+ type: "asset",+ value: "new-id",+ },+ },+ ],+ },+ {+ namespace: "styles",+ patches: [+ {+ op: "replace",+ path: ["local:base:backgroundImage:"],+ value: {+ styleSourceId: "local",+ breakpointId: "base",+ property: "backgroundImage",+ value: {+ type: "image",+ value: { type: "asset", value: "new-id" },+ },+ },+ },+ ],+ },+ {+ namespace: "assets",+ patches: [{ op: "remove", path: ["old-id"] }],+ },+ ]);+ });+});diff --git a/packages/project-build/src/runtime/assets.ts b/packages/project-build/src/runtime/assets.tsnew file mode 100644index 0000000000..9db5e6dc87--- /dev/null+++ b/packages/project-build/src/runtime/assets.ts@@ -0,0 +1,701 @@+import type { StyleValue } from "@webstudio-is/css-engine";+import deepEqual from "fast-deep-equal";+import {+ getAllPages,+ getStyleDeclKey,+ type Asset,+ type DataSource,+ type Pages,+ type Prop,+ type Props,+ type Resource,+ type StyleDecl,+ type Styles,+} from "@webstudio-is/sdk";+import type { BuilderPatchChange } from "../contracts/patch";+import type { BuilderState } from "../state/builder-state";+import type { CompactBuild } from "../types";+import { throwBuilderRuntimeError } from "./errors";+import { createRuntimeMutation } from "./mutation";++export type AssetUsage =+ | { type: "favicon" }+ | { type: "socialImage"; pageId: string }+ | { type: "marketplaceThumbnail"; pageId: string }+ | { type: "prop"; propId: string }+ | { type: "style"; styleDeclKey: string };++type AssetStyleValueReplacement = {+ fromAssetId: string;+ toAssetId: string;+ fromFontFamily?: string;+ toFontFamily?: string;+};++const traverseAssetStyleValue = (+ value: StyleValue,+ callback: (value: StyleValue) => void+) => {+ callback(value);+ if (value.type === "tuple" || value.type === "layers") {+ for (const item of value.value) {+ traverseAssetStyleValue(item, callback);+ }+ }+};++export const replaceAssetInStyleValueMutable = (+ value: StyleValue,+ replacement: AssetStyleValueReplacement+) => {+ let didReplace = false;+ const { fromFontFamily, toFontFamily } = replacement;+ traverseAssetStyleValue(value, (item) => {+ if (+ item.type === "image" &&+ item.value.type === "asset" &&+ item.value.value === replacement.fromAssetId+ ) {+ item.value.value = replacement.toAssetId;+ didReplace = true;+ }+ if (+ item.type === "fontFamily" &&+ fromFontFamily !== undefined &&+ toFontFamily !== undefined &&+ item.value.includes(fromFontFamily)+ ) {+ item.value = item.value.map((fontFamily) =>+ fontFamily === fromFontFamily ? toFontFamily : fontFamily+ );+ didReplace = true;+ }+ });+ return didReplace;+};++export const replaceAssetMutable = ({+ pages,+ props,+ styles,+ replacement,+}: {+ pages?: Pages;+ props: Iterable<Prop>;+ styles: Iterable<StyleDecl>;+ replacement: AssetStyleValueReplacement;+}) => {+ if (pages !== undefined) {+ if (pages.meta?.faviconAssetId === replacement.fromAssetId) {+ pages.meta.faviconAssetId = replacement.toAssetId;+ }+ for (const page of getAllPages(pages)) {+ if (page.meta.socialImageAssetId === replacement.fromAssetId) {+ page.meta.socialImageAssetId = replacement.toAssetId;+ }+ if (page.marketplace?.thumbnailAssetId === replacement.fromAssetId) {+ page.marketplace.thumbnailAssetId = replacement.toAssetId;+ }+ }+ }+ for (const prop of props) {+ if (prop.type === "asset" && prop.value === replacement.fromAssetId) {+ prop.value = replacement.toAssetId;+ }+ }+ for (const styleDecl of styles) {+ replaceAssetInStyleValueMutable(styleDecl.value, replacement);+ }+};++export const calculateUsagesByAssetId = ({+ pages,+ props,+ styles,+ assets,+}: {+ pages: Pages | undefined;+ props: Props;+ styles: Styles;+ assets: Map<Asset["id"], Asset>;+}): Map<Asset["id"], AssetUsage[]> => {+ const usagesByAsset = new Map<Asset["id"], AssetUsage[]>();+ const addUsage = (assetId: Asset["id"], usage: AssetUsage) => {+ const usages = usagesByAsset.get(assetId) ?? [];+ usages.push(usage);+ usagesByAsset.set(assetId, usages);+ };++ const fontFamilyToAssetId = new Map<string, Asset["id"]>();+ for (const asset of assets.values()) {+ if (asset.type === "font") {+ fontFamilyToAssetId.set(asset.meta.family, asset.id);+ }+ }++ if (pages?.meta?.faviconAssetId) {+ addUsage(pages.meta.faviconAssetId, { type: "favicon" });+ }+ if (pages) {+ for (const page of getAllPages(pages)) {+ if (page.meta.socialImageAssetId) {+ addUsage(page.meta.socialImageAssetId, {+ type: "socialImage",+ pageId: page.id,+ });+ }+ if (page.marketplace?.thumbnailAssetId) {+ addUsage(page.marketplace.thumbnailAssetId, {+ type: "marketplaceThumbnail",+ pageId: page.id,+ });+ }+ }+ }+ for (const prop of props.values()) {+ if (+ prop.type === "asset" &&+ prop.name !== "width" &&+ prop.name !== "height"+ ) {+ addUsage(prop.value, { type: "prop", propId: prop.id });+ }+ }+ for (const [styleDeclKey, styleDecl] of styles) {+ traverseAssetStyleValue(styleDecl.value, (value) => {+ if (value.type === "image" && value.value.type === "asset") {+ addUsage(value.value.value, {+ type: "style",+ styleDeclKey,+ });+ }+ if (value.type === "fontFamily") {+ for (const fontFamily of value.value) {+ const assetId = fontFamilyToAssetId.get(fontFamily);+ if (assetId !== undefined) {+ addUsage(assetId, {+ type: "style",+ styleDeclKey,+ });+ }+ }+ }+ });+ }+ return usagesByAsset;+};++type AssetReferenceBuild = Pick<+ CompactBuild,+ "pages" | "props" | "styles" | "resources" | "dataSources"+>;++const getRequiredAssets = (state: Pick<BuilderState, "assets">) => {+ if (state.assets === undefined) {+ return throwBuilderRuntimeError(+ "BAD_REQUEST",+ "Assets namespace is missing"+ );+ }+ return state.assets;+};++const getRequiredAssetReferenceBuild = (+ state: Pick<+ BuilderState,+ "pages" | "props" | "styles" | "resources" | "dataSources"+ >+): AssetReferenceBuild => {+ if (+ state.pages === undefined ||+ state.props === undefined ||+ state.styles === undefined ||+ state.resources === undefined ||+ state.dataSources === undefined+ ) {+ return throwBuilderRuntimeError(+ "BAD_REQUEST",+ "Asset reference namespaces are missing"+ );+ }+ return {+ pages: state.pages,+ props: Array.from(state.props.values()),+ styles: Array.from(state.styles.values()),+ resources: Array.from(state.resources.values()),+ dataSources: Array.from(state.dataSources.values()),+ };+};++export const createAssetReplacementPayload = ({+ build,+ fromAsset,+ toAsset,+}: {+ build: Pick<CompactBuild, "pages" | "props" | "styles">;+ fromAsset: Asset;+ toAsset: Asset;+}) => {+ const pages = structuredClone(build.pages);+ const props = new Map(+ build.props.map((item) => [item.id, structuredClone(item)])+ );+ const styles = new Map(+ build.styles.map((item) => [getStyleDeclKey(item), structuredClone(item)])+ );++ replaceAssetMutable({+ pages,+ props: props.values(),+ styles: styles.values(),+ replacement: {+ fromAssetId: fromAsset.id,+ toAssetId: toAsset.id,+ fromFontFamily:+ fromAsset.type === "font" ? fromAsset.meta.family : undefined,+ toFontFamily: toAsset.type === "font" ? toAsset.meta.family : undefined,+ },+ });++ const pagePatches = [];+ if (build.pages.meta?.faviconAssetId !== pages.meta?.faviconAssetId) {+ pagePatches.push({+ op: "replace" as const,+ path: ["meta", "faviconAssetId"],+ value: pages.meta?.faviconAssetId,+ });+ }+ for (const page of getAllPages(build.pages)) {+ const nextPage = pages.pages.get(page.id);+ if (nextPage === undefined) {+ continue;+ }+ if (page.meta.socialImageAssetId !== nextPage.meta.socialImageAssetId) {+ pagePatches.push({+ op: "replace" as const,+ path: ["pages", page.id, "meta", "socialImageAssetId"],+ value: nextPage.meta.socialImageAssetId,+ });+ }+ if (+ page.marketplace?.thumbnailAssetId !==+ nextPage.marketplace?.thumbnailAssetId+ ) {+ pagePatches.push({+ op: "replace" as const,+ path: ["pages", page.id, "marketplace", "thumbnailAssetId"],+ value: nextPage.marketplace?.thumbnailAssetId,+ });+ }+ }++ const propPatches = [];+ for (const item of build.props) {+ const nextItem = props.get(item.id);+ if (nextItem !== undefined && deepEqual(item, nextItem) === false) {+ propPatches.push({+ op: "replace" as const,+ path: [item.id],+ value: nextItem,+ });+ }+ }++ const stylePatches = [];+ for (const item of build.styles) {+ const key = getStyleDeclKey(item);+ const nextItem = styles.get(key);+ if (+ nextItem !== undefined &&+ deepEqual(item.value, nextItem.value) === false+ ) {+ stylePatches.push({+ op: "replace" as const,+ path: [key],+ value: nextItem,+ });+ }+ }++ const payload = [];+ if (pagePatches.length > 0) {+ payload.push({ namespace: "pages" as const, patches: pagePatches });+ }+ if (propPatches.length > 0) {+ payload.push({ namespace: "props" as const, patches: propPatches });+ }+ if (stylePatches.length > 0) {+ payload.push({ namespace: "styles" as const, patches: stylePatches });+ }+ payload.push({+ namespace: "assets" as const,+ patches: [{ op: "remove" as const, path: [fromAsset.id] }],+ });+ return payload;+};++export const findAsset = (assets: Iterable<Asset>, assetId: Asset["id"]) => {+ for (const asset of assets) {+ if (asset.id === assetId) {+ return asset;+ }+ }+};++const countStringReferences = (value: unknown, target: string): number => {+ if (value === target) {+ return 1;+ }+ if (Array.isArray(value)) {+ return value.reduce(+ (count, item) => count + countStringReferences(item, target),+ 0+ );+ }+ if (typeof value === "object" && value !== null) {+ return Object.values(value).reduce(+ (count, item) => count + countStringReferences(item, target),+ 0+ );+ }+ return 0;+};++const countResourceAssetReferences = (resource: Resource, assetId: string) =>+ countStringReferences(resource.url, assetId) ++ countStringReferences(resource.body, assetId) ++ countStringReferences(+ resource.searchParams?.map((param) => param.value),+ assetId+ ) ++ countStringReferences(+ resource.headers.map((header) => header.value),+ assetId+ );++const countDataSourceAssetReferences = (+ dataSource: DataSource,+ assetId: string+) =>+ dataSource.type === "variable"+ ? countStringReferences(dataSource.value, assetId)+ : 0;++const countApiOnlyAssetUsage = (build: AssetReferenceBuild, assetId: string) =>+ build.resources.reduce(+ (count, resource) =>+ count + countResourceAssetReferences(resource, assetId),+ 0+ ) ++ build.dataSources.reduce(+ (count, dataSource) =>+ count + countDataSourceAssetReferences(dataSource, assetId),+ 0+ );++const getAssetUsageCounts = (build: AssetReferenceBuild, assets: Asset[]) => {+ const usageMap = calculateUsagesByAssetId({+ pages: build.pages,+ props: new Map(build.props.map((item) => [item.id, item])),+ styles: new Map(build.styles.map((item) => [getStyleDeclKey(item), item])),+ assets: new Map(assets.map((asset) => [asset.id, asset])),+ });+ const counts = new Map<Asset["id"], number>();+ for (const asset of assets) {+ counts.set(+ asset.id,+ (usageMap.get(asset.id)?.length ?? 0) ++ countApiOnlyAssetUsage(build, asset.id)+ );+ }+ return counts;+};++const serializeAssetSummary = (asset: Asset) => ({+ id: asset.id,+ name: asset.name,+ type: asset.type,+ size: asset.size,+ contentType: asset.format,+ createdAt: asset.createdAt,+});++export const serializeAssetList = ({+ assets,+ build,+ input,+}: {+ assets: Asset[];+ build?: AssetReferenceBuild;+ input: {+ type?: "image" | "font";+ withUsage?: boolean;+ sort?: "name" | "size" | "createdAt" | "usage";+ cursor?: string;+ limit?: number;+ };+}) => {+ const shouldCountUsage = input.withUsage === true || input.sort === "usage";+ const usageCounts =+ shouldCountUsage && build !== undefined+ ? getAssetUsageCounts(build, assets)+ : undefined;+ const sorted = assets+ .filter((asset) => input.type === undefined || asset.type === input.type)+ .map((asset) => ({+ ...serializeAssetSummary(asset),+ usageCount: shouldCountUsage+ ? (usageCounts?.get(asset.id) ?? 0)+ : undefined,+ }));+ sorted.sort((left, right) => {+ switch (input.sort) {+ case "size":+ return right.size - left.size;+ case "createdAt":+ return right.createdAt.localeCompare(left.createdAt);+ case "usage":+ return (right.usageCount ?? 0) - (left.usageCount ?? 0);+ case "name":+ default:+ return left.name.localeCompare(right.name);+ }+ });+ const start = input.cursor === undefined ? 0 : Number(input.cursor);+ if (Number.isInteger(start) === false || start < 0) {+ throw new Error("Invalid asset cursor");+ }+ const limit = input.limit ?? sorted.length;+ const items = sorted.slice(start, start + limit);+ const nextIndex = start + items.length;+ return {+ items,+ nextCursor: nextIndex < sorted.length ? String(nextIndex) : null,+ };+};++export const createAssetUsageList = ({+ asset,+ assets,+ build,+}: {+ asset: Asset;+ assets: Asset[];+ build: AssetReferenceBuild;+}) => {+ const usages: Array<{+ namespace:+ | "props"+ | "styles"+ | "resources"+ | "dataSources"+ | "pages"+ | "project";+ pageId?: string;+ instanceId?: string;+ path: Array<string | number>;+ }> = [];+ const props = new Map(build.props.map((item) => [item.id, item]));+ const styles = new Map(+ build.styles.map((item) => [getStyleDeclKey(item), item])+ );+ const usageMap = calculateUsagesByAssetId({+ pages: build.pages,+ props,+ styles,+ assets: new Map(assets.map((item) => [item.id, item])),+ });+ for (const usage of usageMap.get(asset.id) ?? []) {+ if (usage.type === "favicon") {+ usages.push({ namespace: "project", path: ["meta", "faviconAssetId"] });+ }+ if (usage.type === "socialImage") {+ usages.push({+ namespace: "pages",+ pageId: usage.pageId,+ path: ["pages", usage.pageId, "meta", "socialImageAssetId"],+ });+ }+ if (usage.type === "marketplaceThumbnail") {+ usages.push({+ namespace: "pages",+ pageId: usage.pageId,+ path: ["pages", usage.pageId, "marketplace", "thumbnailAssetId"],+ });+ }+ if (usage.type === "prop") {+ usages.push({+ namespace: "props",+ instanceId: props.get(usage.propId)?.instanceId,+ path: [usage.propId, "value"],+ });+ }+ if (usage.type === "style") {+ usages.push({+ namespace: "styles",+ path: [usage.styleDeclKey, "value"],+ });+ }+ }+ for (const resource of build.resources) {+ if (countResourceAssetReferences(resource, asset.id) > 0) {+ usages.push({ namespace: "resources", path: [resource.id] });+ }+ }+ for (const dataSource of build.dataSources) {+ if (countDataSourceAssetReferences(dataSource, asset.id) > 0) {+ usages.push({ namespace: "dataSources", path: [dataSource.id] });+ }+ }+ return usages;+};++export const createAssetDeletePayload = (+ assets: Asset[]+): BuilderPatchChange[] => [+ {+ namespace: "assets",+ patches: assets.map((asset) => ({+ op: "remove" as const,+ path: [asset.id],+ })),+ },+];++export const listAssets = (+ state: Pick<+ BuilderState,+ "assets" | "pages" | "props" | "styles" | "resources" | "dataSources"+ >,+ input: {+ type?: "image" | "font";+ withUsage?: boolean;+ sort?: "name" | "size" | "createdAt" | "usage";+ cursor?: string;+ limit?: number;+ } = {}+) => {+ try {+ return serializeAssetList({+ assets: Array.from(getRequiredAssets(state).values()),+ build:+ input.withUsage === true || input.sort === "usage"+ ? getRequiredAssetReferenceBuild(state)+ : undefined,+ input,+ });+ } catch (error) {+ if (error instanceof Error && error.message === "Invalid asset cursor") {+ return throwBuilderRuntimeError("BAD_REQUEST", error.message);+ }+ throw error;+ }+};++export const findAssetUsage = (+ state: Pick<+ BuilderState,+ "assets" | "pages" | "props" | "styles" | "resources" | "dataSources"+ >,+ input: { assetId: string }+) => {+ const assets = Array.from(getRequiredAssets(state).values());+ const asset = findAsset(assets, input.assetId);+ if (asset === undefined) {+ return throwBuilderRuntimeError("NOT_FOUND", "Asset not found");+ }+ return {+ usages: createAssetUsageList({+ asset,+ assets,+ build: getRequiredAssetReferenceBuild(state),+ }),+ };+};++export const replaceAsset = (+ state: Pick<+ BuilderState,+ "assets" | "pages" | "props" | "styles" | "resources" | "dataSources"+ >,+ input: { fromAssetId: string; toAssetId: string }+) => {+ const assets = Array.from(getRequiredAssets(state).values());+ const fromAsset = findAsset(assets, input.fromAssetId);+ const toAsset = findAsset(assets, input.toAssetId);+ if (fromAsset === undefined || toAsset === undefined) {+ return throwBuilderRuntimeError("NOT_FOUND", "Asset not found");+ }+ const build = getRequiredAssetReferenceBuild(state);+ const unrewritableUsages = createAssetUsageList({+ asset: fromAsset,+ assets,+ build,+ }).filter(+ (usage) =>+ usage.namespace === "resources" || usage.namespace === "dataSources"+ );+ if (unrewritableUsages.length > 0) {+ return throwBuilderRuntimeError(+ "BAD_REQUEST",+ "Asset is referenced in resources or variables. Update those references before replacing the asset."+ );+ }+ return createRuntimeMutation({+ payload: createAssetReplacementPayload({+ build,+ fromAsset,+ toAsset,+ }),+ result: { fromAssetId: fromAsset.id, toAssetId: toAsset.id },+ invalidatesNamespaces: ["pages", "props", "styles", "assets"],+ });+};++export const deleteAssets = (+ state: Pick<+ BuilderState,+ "assets" | "pages" | "props" | "styles" | "resources" | "dataSources"+ >,+ input: {+ assetIdsOrPrefixes: string[];+ force?: boolean;+ }+) => {+ const assets = Array.from(getRequiredAssets(state).values());+ const selectedAssets = assets.filter((asset) =>+ input.assetIdsOrPrefixes.some(+ (value) => asset.id === value || asset.id.startsWith(value)+ )+ );+ if (selectedAssets.length === 0) {+ return createRuntimeMutation({+ payload: [],+ result: { assetIds: [] },+ invalidatesNamespaces: ["assets"],+ });+ }+ const build = getRequiredAssetReferenceBuild(state);+ const usagesByAsset = new Map(+ selectedAssets.map((asset) => [+ asset.id,+ createAssetUsageList({ asset, assets, build }),+ ])+ );+ if (input.force !== true) {+ const usedAssetIds = selectedAssets+ .filter((asset) => (usagesByAsset.get(asset.id)?.length ?? 0) > 0)+ .map((asset) => asset.id);+ if (usedAssetIds.length > 0) {+ return throwBuilderRuntimeError(+ "BAD_REQUEST",+ `Assets are still referenced: ${usedAssetIds.join(", ")}`+ );+ }+ }+ return createRuntimeMutation({+ payload: createAssetDeletePayload(selectedAssets),+ result: { assetIds: selectedAssets.map((asset) => asset.id) },+ invalidatesNamespaces: ["assets"],+ });+};diff --git a/packages/project-build/src/runtime/breakpoints.test.ts b/packages/project-build/src/runtime/breakpoints.test.tsnew file mode 100644index 0000000000..1775572b9e--- /dev/null+++ b/packages/project-build/src/runtime/breakpoints.test.ts@@ -0,0 +1,137 @@+import { describe, expect, test, vi } from "vitest";+import type { Breakpoint, Breakpoints } from "@webstudio-is/sdk";+import {+ breakpointLimitWarning,+ breakpointPasteLimitWarning,+ buildMergedBreakpointIds,+ findClosestBreakpoint,+ groupBreakpoints,+ hasReachedBreakpointLimit,+ isBaseBreakpoint,+ maxBreakpoints,+} from "./breakpoints";++const breakpoint = (id: string, value: Partial<Breakpoint> = {}): Breakpoint =>+ ({ id, label: id, ...value }) satisfies Breakpoint;++describe("breakpoint limits", () => {+ test("describes and checks the maximum breakpoint count", () => {+ expect(maxBreakpoints).toBe(8);+ expect(breakpointLimitWarning).toContain("up to 8 breakpoints");+ expect(breakpointPasteLimitWarning).toContain(breakpointLimitWarning);+ expect(hasReachedBreakpointLimit(7)).toBe(false);+ expect(hasReachedBreakpointLimit(7, 1)).toBe(true);+ });+});++describe("breakpoint grouping and matching", () => {+ test("detects base breakpoints", () => {+ expect(isBaseBreakpoint({})).toBe(true);+ expect(isBaseBreakpoint({ minWidth: 768 })).toBe(false);+ expect(isBaseBreakpoint({ maxWidth: 767 })).toBe(false);+ });++ test("groups width-based breakpoints separately from custom conditions", () => {+ const custom = { id: "motion", condition: "(prefers-reduced-motion)" };+ const grouped = groupBreakpoints([+ breakpoint("max", { maxWidth: 767 }),+ custom,+ breakpoint("base"),+ breakpoint("desktop", { minWidth: 1280 }),+ breakpoint("tablet", { minWidth: 768 }),+ ]);++ expect(grouped.widthBased.map(({ id }) => id)).toEqual([+ "desktop",+ "tablet",+ "base",+ "max",+ ]);+ expect(grouped.custom).toEqual([custom]);+ });++ test("groups max-width-only and empty breakpoint lists", () => {+ expect(+ groupBreakpoints([+ breakpoint("mobile", { maxWidth: 479 }),+ breakpoint("tablet", { maxWidth: 991 }),+ ]).widthBased.map(({ id }) => id)+ ).toEqual(["tablet", "mobile"]);++ expect(groupBreakpoints([])).toEqual({ widthBased: [], custom: [] });+ });++ test("finds closest width breakpoint and falls back to base", () => {+ const existing = [+ breakpoint("base"),+ breakpoint("tablet", { minWidth: 768 }),+ breakpoint("desktop", { minWidth: 1280 }),+ ];++ expect(+ findClosestBreakpoint(breakpoint("incoming", { minWidth: 900 }), existing)+ ?.id+ ).toBe("tablet");+ expect(+ findClosestBreakpoint(+ breakpoint("custom", { condition: "(hover: hover)" }),+ existing+ )?.id+ ).toBe("base");+ });++ test("maps duplicate breakpoints and merges overflow into closest existing", () => {+ const onMerged = vi.fn();+ const existing: Breakpoints = new Map([+ ["base", breakpoint("base")],+ ["tablet", breakpoint("tablet", { minWidth: 768 })],+ ]);++ const merged = buildMergedBreakpointIds(+ [+ breakpoint("same-tablet", { minWidth: 768 }),+ breakpoint("desktop", { minWidth: 1280 }),+ ],+ existing,+ { maxBreakpointCount: 1, onBreakpointMergedDueToLimit: onMerged }+ );++ expect(merged.get("same-tablet")).toBe("tablet");+ expect(merged.get("desktop")).toBe("tablet");+ expect(onMerged).toHaveBeenCalledTimes(1);+ });++ test("merges matching media even when labels differ", () => {+ const existing: Breakpoints = new Map([+ ["tablet", breakpoint("tablet", { minWidth: 768, label: "Tablet" })],+ ]);++ const merged = buildMergedBreakpointIds(+ [breakpoint("ipad", { minWidth: 768, label: "iPad" })],+ existing+ );++ expect(merged.get("ipad")).toBe("tablet");+ });++ test("does not count the base breakpoint against the max breakpoint count", () => {+ const existing: Breakpoints = new Map([+ ["base", breakpoint("base")],+ ["0", breakpoint("0", { maxWidth: 320 })],+ ["1", breakpoint("1", { maxWidth: 480 })],+ ["2", breakpoint("2", { maxWidth: 768 })],+ ["3", breakpoint("3", { maxWidth: 1024 })],+ ["4", breakpoint("4", { minWidth: 1280 })],+ ["5", breakpoint("5", { minWidth: 1440 })],+ ["6", breakpoint("6", { minWidth: 1920 })],+ ]);++ const merged = buildMergedBreakpointIds(+ [breakpoint("incoming", { minWidth: 1500 })],+ existing,+ { maxBreakpointCount: maxBreakpoints }+ );++ expect(merged.has("incoming")).toBe(false);+ });+});diff --git a/packages/project-build/src/runtime/breakpoints.ts b/packages/project-build/src/runtime/breakpoints.tsnew file mode 100644index 0000000000..36dc5fd3d7--- /dev/null+++ b/packages/project-build/src/runtime/breakpoints.ts@@ -0,0 +1,148 @@+import { compareMedia, equalMedia } from "@webstudio-is/css-engine";+import type { Breakpoint, Breakpoints } from "@webstudio-is/sdk";++export const maxBreakpoints = 8;++export const breakpointLimitWarning =+ "You can have up to 8 breakpoints. More breakpoints can make the project harder to maintain.";++export const breakpointPasteLimitWarning = `${breakpointLimitWarning} Pasted breakpoint styles were merged into the closest existing breakpoints.`;++export const hasReachedBreakpointLimit = (+ breakpointCount: number,+ pendingBreakpointCount = 0+) => breakpointCount + pendingBreakpointCount >= maxBreakpoints;++/**+ * Check if a breakpoint is the base breakpoint (no min or max width).+ * Note: Does not check for custom conditions.+ */+export const isBaseBreakpoint = (breakpoint: {+ minWidth?: number;+ maxWidth?: number;+}) => breakpoint.minWidth === undefined && breakpoint.maxWidth === undefined;++/**+ * Group breakpoints into width-based and custom condition categories.+ * Width-based breakpoints are ordered: min-width (largest to smallest), base, max-width (largest to smallest).+ * Custom condition breakpoints are kept separate and not sorted.+ *+ * Note: minWidth/maxWidth and condition are mutually exclusive - a breakpoint has either+ * width-based properties OR a custom condition, never both.+ */+export const groupBreakpoints = <+ T extends { minWidth?: number; maxWidth?: number; condition?: string },+>(+ breakpoints: Array<T>+): { widthBased: Array<T>; custom: Array<T> } => {+ const custom = breakpoints.filter(+ (breakpoint) => breakpoint.condition !== undefined+ );+ const widthBased = breakpoints.filter(+ (breakpoint) => breakpoint.condition === undefined+ );++ const sorted = [...widthBased].sort(compareMedia);+ const maxs = sorted.filter((breakpoint) => breakpoint.maxWidth !== undefined);+ const mins = sorted+ .filter((breakpoint) => breakpoint.minWidth !== undefined)+ .reverse();+ const base = sorted.filter(isBaseBreakpoint);++ return {+ widthBased: [...mins, ...base, ...maxs],+ custom,+ };+};++const getBreakpointWidthValue = (breakpoint: Breakpoint) => {+ if (breakpoint.minWidth !== undefined && breakpoint.maxWidth !== undefined) {+ return (breakpoint.minWidth + breakpoint.maxWidth) / 2;+ }+ return breakpoint.minWidth ?? breakpoint.maxWidth;+};++export const findClosestBreakpoint = (+ breakpoint: Breakpoint,+ existingBreakpoints: Breakpoint[]+): Breakpoint | undefined => {+ let closestBreakpoint: Breakpoint | undefined;+ let closestDistance = Number.POSITIVE_INFINITY;+ const widthValue = getBreakpointWidthValue(breakpoint);++ if (widthValue !== undefined) {+ for (const existingBreakpoint of existingBreakpoints) {+ const existingWidthValue = getBreakpointWidthValue(existingBreakpoint);+ if (existingWidthValue === undefined) {+ continue;+ }+ const distance = Math.abs(widthValue - existingWidthValue);+ if (distance < closestDistance) {+ closestBreakpoint = existingBreakpoint;+ closestDistance = distance;+ }+ }+ }++ return (+ closestBreakpoint ??+ existingBreakpoints.find(+ (existingBreakpoint) =>+ existingBreakpoint.condition === undefined &&+ isBaseBreakpoint(existingBreakpoint)+ ) ??+ existingBreakpoints[0]+ );+};++/**+ * Build a map of merged breakpoint IDs from fragment breakpoints to existing breakpoints.+ * Breakpoints are merged when they have matching minWidth, maxWidth, condition, and label.+ * Note: minWidth/maxWidth and condition are mutually exclusive.+ *+ * @param fragmentBreakpoints - Breakpoints from the fragment being inserted+ * @param existingBreakpoints - Existing breakpoints in the project+ * @param options.maxBreakpointCount - When provided, overflow fragment breakpoints are merged into the closest existing breakpoint.+ * @returns Map of fragment breakpoint IDs to existing breakpoint IDs+ */+export const buildMergedBreakpointIds = (+ fragmentBreakpoints: Breakpoint[],+ existingBreakpoints: Breakpoints,+ options?: {+ maxBreakpointCount?: number;+ onBreakpointMergedDueToLimit?: () => void;+ }+): Map<Breakpoint["id"], Breakpoint["id"]> => {+ const mergedBreakpointIds = new Map<Breakpoint["id"], Breakpoint["id"]>();+ const acceptedBreakpoints = Array.from(existingBreakpoints.values());++ for (const newBreakpoint of fragmentBreakpoints) {+ for (const breakpoint of acceptedBreakpoints) {+ if (equalMedia(breakpoint, newBreakpoint)) {+ mergedBreakpointIds.set(newBreakpoint.id, breakpoint.id);+ break;+ }+ }+ if (mergedBreakpointIds.has(newBreakpoint.id)) {+ continue;+ }++ if (+ options?.maxBreakpointCount !== undefined &&+ acceptedBreakpoints.length >= options.maxBreakpointCount + 1+ ) {+ const closestBreakpoint = findClosestBreakpoint(+ newBreakpoint,+ acceptedBreakpoints+ );+ if (closestBreakpoint !== undefined) {+ mergedBreakpointIds.set(newBreakpoint.id, closestBreakpoint.id);+ options.onBreakpointMergedDueToLimit?.();+ }+ continue;+ }++ acceptedBreakpoints.push(newBreakpoint);+ }+ return mergedBreakpointIds;+};diff --git a/packages/project-build/src/runtime/context.ts b/packages/project-build/src/runtime/context.tsnew file mode 100644index 0000000000..baea305b32--- /dev/null+++ b/packages/project-build/src/runtime/context.ts@@ -0,0 +1,4 @@+export type BuilderRuntimeContext = {+ createId: () => string;+ now: () => Date;+};diff --git a/packages/project-build/src/runtime/cutover.test.ts b/packages/project-build/src/runtime/cutover.test.tsnew file mode 100644index 0000000000..04cc7d6621--- /dev/null+++ b/packages/project-build/src/runtime/cutover.test.ts@@ -0,0 +1,24 @@+import { expect, test } from "vitest";+import { runtimeOperationContracts } from "../contracts/builder-runtime";+import { builderRuntimeCutoverManifests } from "./cutover";++test("documents cutover families with known runtime operation ids", () => {+ const operationIds = new Set(+ runtimeOperationContracts.map((contract) => contract.id)+ );+ const cutoverOperationIds = new Set<string>();+ const familyNames = builderRuntimeCutoverManifests.map(+ (manifest) => manifest.family+ );++ expect(new Set(familyNames).size).toBe(familyNames.length);+ for (const manifest of builderRuntimeCutoverManifests) {+ expect(manifest.operationIds.length).toBeGreaterThan(0);+ expect(manifest.callers.length).toBeGreaterThan(0);+ for (const operationId of manifest.operationIds) {+ expect(operationIds.has(operationId)).toBe(true);+ cutoverOperationIds.add(operationId);+ }+ }+ expect(cutoverOperationIds).toEqual(operationIds);+});diff --git a/packages/project-build/src/runtime/cutover.ts b/packages/project-build/src/runtime/cutover.tsnew file mode 100644index 0000000000..17e198299b--- /dev/null+++ b/packages/project-build/src/runtime/cutover.ts@@ -0,0 +1,191 @@+export const builderRuntimeCutoverManifests = [+ {+ family: "pages-read",+ operationIds: ["pages.list", "pages.get", "pages.getByPath"] as const,+ callers: ["appRouter.api.pages"] as const,+ },+ {+ family: "page-create-update-mutations",+ operationIds: ["pages.create", "pages.update"] as const,+ callers: ["appRouter.api.pages", "Builder pages UI"] as const,+ },+ {+ family: "page-delete-mutations",+ operationIds: ["pages.delete"] as const,+ callers: ["appRouter.api.pages"] as const,+ },+ {+ family: "page-duplicate-mutations",+ operationIds: ["pages.duplicate"] as const,+ callers: [+ "appRouter.api.pages",+ "Builder pages UI",+ "Builder copy/paste",+ ] as const,+ },+ {+ family: "page-template-operations",+ operationIds: ["pageTemplates.list", "pageTemplates.createPage"] as const,+ callers: ["appRouter.api.pageTemplates", "Builder pages UI"] as const,+ },+ {+ family: "project-settings-operations",+ operationIds: ["projectSettings.get", "projectSettings.update"] as const,+ callers: ["appRouter.api.projectSettings"] as const,+ },+ {+ family: "redirect-operations",+ operationIds: [+ "redirects.list",+ "redirects.create",+ "redirects.update",+ "redirects.delete",+ ] as const,+ callers: ["appRouter.api.redirects"] as const,+ },+ {+ family: "breakpoint-operations",+ operationIds: [+ "breakpoints.list",+ "breakpoints.create",+ "breakpoints.update",+ "breakpoints.delete",+ ] as const,+ callers: [+ "appRouter.api.breakpoints",+ "Builder breakpoint utilities",+ ] as const,+ },+ {+ family: "folders-read",+ operationIds: ["folders.list"] as const,+ callers: ["appRouter.api.folders"] as const,+ },+ {+ family: "folder-create-update-mutations",+ operationIds: ["folders.create", "folders.update"] as const,+ callers: ["appRouter.api.folders", "Builder pages UI"] as const,+ },+ {+ family: "folder-delete-mutations",+ operationIds: ["folders.delete"] as const,+ callers: ["appRouter.api.folders"] as const,+ },+ {+ family: "instances-read",+ operationIds: [+ "instances.list",+ "instances.inspect",+ "instances.listTexts",+ ] as const,+ callers: ["appRouter.api.instances"] as const,+ },+ {+ family: "instance-structural-api-mutations",+ operationIds: [+ "instances.append",+ "instances.move",+ "instances.clone",+ "instances.delete",+ ] as const,+ callers: ["appRouter.api.instances"] as const,+ },+ {+ family: "text-content-mutations",+ operationIds: ["instances.updateText"] as const,+ callers: [+ "appRouter.api.instances",+ "Builder text-content controls",+ ] as const,+ },+ {+ family: "prop-mutations",+ operationIds: [+ "instances.updateProps",+ "instances.deleteProps",+ "instances.bindProps",+ ] as const,+ callers: [+ "appRouter.api.instances",+ "Builder props utilities",+ "Builder settings panel",+ "Builder CSS variable utilities",+ ] as const,+ },+ {+ family: "style-reads",+ operationIds: ["styles.getDeclarations", "designTokens.list"] as const,+ callers: ["appRouter.api.styles", "appRouter.api.designTokens"] as const,+ },+ {+ family: "style-declaration-mutations",+ operationIds: [+ "styles.updateDeclarations",+ "styles.deleteDeclarations",+ "styles.replaceValues",+ ] as const,+ callers: ["appRouter.api.styles"] as const,+ },+ {+ family: "design-token-mutations",+ operationIds: [+ "designTokens.create",+ "designTokens.updateStyles",+ "designTokens.deleteStyles",+ "designTokens.attach",+ "designTokens.detach",+ "designTokens.extract",+ ] as const,+ callers: ["appRouter.api.designTokens"] as const,+ },+ {+ family: "css-variable-operations",+ operationIds: [+ "cssVariables.list",+ "cssVariables.define",+ "cssVariables.delete",+ "cssVariables.rewriteRefs",+ ] as const,+ callers: [+ "appRouter.api.cssVariables",+ "Builder CSS variable utilities",+ ] as const,+ },+ {+ family: "data-reads",+ operationIds: ["variables.list", "resources.list"] as const,+ callers: ["appRouter.api.variables", "appRouter.api.resources"] as const,+ },+ {+ family: "resource-mutations",+ operationIds: [+ "resources.create",+ "resources.update",+ "resources.delete",+ ] as const,+ callers: ["appRouter.api.resources"] as const,+ },+ {+ family: "asset-reference-operations",+ operationIds: [+ "assets.list",+ "assets.findUsage",+ "assets.replace",+ "assets.delete",+ ] as const,+ callers: [+ "appRouter.api.assets",+ "Builder asset manager",+ "Builder asset replacement",+ ] as const,+ },+ {+ family: "variable-mutations",+ operationIds: [+ "variables.create",+ "variables.update",+ "variables.delete",+ ] as const,+ callers: ["appRouter.api.variables"] as const,+ },+] as const;diff --git a/apps/builder/app/shared/data-variables.test.tsx b/packages/project-build/src/runtime/data.test.tsxsimilarity index 65%rename from apps/builder/app/shared/data-variables.test.tsxrename to packages/project-build/src/runtime/data.test.tsxindex 3e0fa6fee8..31b62fd715 100644--- a/apps/builder/app/shared/data-variables.test.tsx+++ b/packages/project-build/src/runtime/data.test.tsx@@ -1,4 +1,4 @@-import { expect, test, vi } from "vitest";+import { describe, expect, test, vi } from "vitest";import {$,ActionValue,@@ -15,21 +15,41 @@ import {getHomePage,ROOT_INSTANCE_ID,SYSTEM_VARIABLE_ID,+ type DataSource,+ type Instance,+ type Prop,+ type Resource,} from "@webstudio-is/sdk";import { createDefaultPages } from "@webstudio-is/project-build";import {computeExpression,+ createDataVariableCreatePayload,+ createDataVariableDeletePayload,+ createDataVariableUpdatePayload,+ createResourceCreatePayload,+ createResourceDeletePayload,+ createResourceUpdatePayload,+ createResourceUpsertPatchPayload,+ createResourceValue,decodeDataVariableName,- encodeDataVariableName,- findUnsetVariableNames,- restoreExpressionVariables,- rebindTreeVariablesMutable,- unsetExpressionVariables,deleteVariableMutable,+ encodeDataVariableName,findAvailableVariables,+ findResource,+ findUnsetVariableNames,findVariableUsagesByInstance,+ getResourceExpressionErrors,+ rebindTreeVariablesMutable,replaceDataSourcesInExpression,-} from "./data-variables";+ restoreExpressionVariables,+ resourceFieldsInput,+ resourceFieldsUpdateInput,+ serializeDataVariables,+ serializeResources,+ unsetExpressionVariables,+ upsertResourceMutable,+ validateDataVariableNameWithSources,+} from "./data";test("encode data variable name when necessary", () => {expect(encodeDataVariableName("formState")).toEqual("formState");@@ -48,6 +68,228 @@ test("dencode data variable name", () => {).toEqual("Collection Item");});+test("validate data variable name", () => {+ const dataSources = [+ {+ id: "variable-1",+ scopeInstanceId: "instance-1",+ name: "existingVariable",+ type: "variable",+ value: { type: "string", value: "" },+ },+ {+ id: "resource-1",+ scopeInstanceId: "instance-1",+ name: "existingResource",+ type: "resource",+ resourceId: "resource-value-1",+ },+ ] as const;++ expect(+ validateDataVariableNameWithSources({+ dataSources,+ name: "",+ scopeInstanceId: "instance-1",+ })+ ).toEqual({+ type: "required",+ message: "Variable name is required",+ });+ expect(+ validateDataVariableNameWithSources({+ dataSources,+ name: "existingVariable",+ scopeInstanceId: "instance-1",+ })+ ).toEqual({+ type: "duplicate",+ message: "Name is already used by another variable on this instance",+ });+ expect(+ validateDataVariableNameWithSources({+ dataSources,+ name: "existingVariable",+ scopeInstanceId: "instance-2",+ })+ ).toBeUndefined();+ expect(+ validateDataVariableNameWithSources({+ dataSources,+ name: "existingResource",+ scopeInstanceId: "instance-1",+ })+ ).toBeUndefined();+});++test("serialize data variables filters by scope", () => {+ const dataSources = [+ {+ id: "variable-1",+ scopeInstanceId: "box-1",+ name: "title",+ type: "variable",+ value: { type: "string", value: "Hello" },+ },+ {+ id: "variable-2",+ scopeInstanceId: "box-2",+ name: "count",+ type: "variable",+ value: { type: "number", value: 1 },+ },+ {+ id: "resource-1",+ scopeInstanceId: "box-1",+ name: "users",+ type: "resource",+ resourceId: "resource-value-1",+ },+ ] as const;++ expect(serializeDataVariables({ dataSources })).toEqual({+ variables: [+ {+ id: "variable-1",+ name: "title",+ scopeInstanceId: "box-1",+ value: { type: "string", value: "Hello" },+ },+ {+ id: "variable-2",+ name: "count",+ scopeInstanceId: "box-2",+ value: { type: "number", value: 1 },+ },+ ],+ });+ expect(+ serializeDataVariables({ dataSources, scopeInstanceId: "box-1" })+ ).toEqual({+ variables: [+ {+ id: "variable-1",+ name: "title",+ scopeInstanceId: "box-1",+ value: { type: "string", value: "Hello" },+ },+ ],+ });+});++test("create data variable payload validates ids and names", () => {+ expect(+ createDataVariableCreatePayload({+ dataSourceId: "variable-2",+ scopeInstanceId: "instance-1",+ name: "newVariable",+ value: { type: "string", value: "hello" },+ dataSources: [+ {+ id: "variable-1",+ scopeInstanceId: "instance-1",+ name: "existingVariable",+ type: "variable",+ value: { type: "string", value: "" },+ },+ ],+ })+ ).toEqual({+ errors: [],+ payload: [+ {+ namespace: "dataSources",+ patches: [+ {+ op: "add",+ path: ["variable-2"],+ value: {+ id: "variable-2",+ scopeInstanceId: "instance-1",+ name: "newVariable",+ type: "variable",+ value: { type: "string", value: "hello" },+ },+ },+ ],+ },+ ],+ });++ expect(+ createDataVariableCreatePayload({+ dataSourceId: "variable-1",+ scopeInstanceId: "instance-1",+ name: "existingVariable",+ value: { type: "string", value: "" },+ dataSources: [+ {+ id: "variable-1",+ scopeInstanceId: "instance-1",+ name: "existingVariable",+ type: "variable",+ value: { type: "string", value: "" },+ },+ ],+ }).errors+ ).toEqual([{ type: "duplicate-id", dataSourceId: "variable-1" }]);+});++test("update data variable payload validates renamed variables", () => {+ const variable = {+ id: "variable-1",+ scopeInstanceId: "instance-1",+ name: "oldName",+ type: "variable",+ value: { type: "string", value: "" },+ } as const;++ expect(+ createDataVariableUpdatePayload({+ variable,+ values: {+ name: "newName",+ value: { type: "number", value: 1 },+ },+ dataSources: [variable],+ })+ ).toEqual({+ payload: [+ {+ namespace: "dataSources",+ patches: [+ { op: "replace", path: ["variable-1", "name"], value: "newName" },+ {+ op: "replace",+ path: ["variable-1", "value"],+ value: { type: "number", value: 1 },+ },+ ],+ },+ ],+ });++ expect(+ createDataVariableUpdatePayload({+ variable,+ values: { name: "duplicateName" },+ dataSources: [+ variable,+ {+ id: "variable-2",+ scopeInstanceId: "instance-1",+ name: "duplicateName",+ type: "variable",+ value: { type: "string", value: "" },+ },+ ],+ }).error+ ).toEqual({+ type: "duplicate",+ message: "Name is already used by another variable on this instance",+ });+});+test("dencode data variable name with dollar sign", () => {expect(decodeDataVariableName(encodeDataVariableName("$my$Variable"))@@ -221,11 +463,9 @@ test("compute expression with decoded names", () => {});test("compute expression when invalid syntax", () => {- // prevent error message in test reportconst spy = vi.spyOn(console, "error");- spy.mockImplementationOnce(() => {});expect(computeExpression("https://github.com", new Map())).toEqual(undefined);- expect(spy).toHaveBeenCalledOnce();+ expect(spy).not.toHaveBeenCalled();spy.mockRestore();});@@ -739,6 +979,80 @@ test("delete variable and unset it in expressions", () => {]);});+test("delete data variable payload reuses mutable cleanup semantics", () => {+ const bodyVariable = new Variable("bodyVariable", "one value of body");+ const resourceVariable = new ResourceValue("resourceVariable", {+ url: expression`${bodyVariable}`,+ method: "post",+ searchParams: [],+ headers: [{ name: "auth", value: expression`${bodyVariable}` }],+ });+ const data = renderData(+ <$.Body ws:id="bodyId" data-body-vars={expression`${bodyVariable}`}>+ <$.Box ws:id="boxId" data-box-vars={expression`${resourceVariable}`}>+ {expression`${bodyVariable}`}+ </$.Box>+ </$.Body>+ );+ const [bodyVariableId] = data.dataSources.keys();++ const { payload, deletedVariable } = createDataVariableDeletePayload({+ variableId: bodyVariableId,+ ...data,+ });++ expect(deletedVariable).toEqual(+ expect.objectContaining({ name: "bodyVariable" })+ );+ expect(payload).toEqual([+ {+ namespace: "instances",+ patches: [+ {+ op: "replace",+ path: ["boxId"],+ value: expect.objectContaining({+ children: [{ type: "expression", value: "bodyVariable" }],+ }),+ },+ ],+ },+ {+ namespace: "props",+ patches: [+ {+ op: "replace",+ path: expect.any(Array),+ value: expect.objectContaining({+ name: "data-body-vars",+ value: "bodyVariable",+ }),+ },+ ],+ },+ {+ namespace: "dataSources",+ patches: [{ op: "remove", path: [bodyVariableId] }],+ },+ {+ namespace: "resources",+ patches: [+ {+ op: "replace",+ path: expect.any(Array),+ value: expect.objectContaining({+ url: "bodyVariable",+ headers: [{ name: "auth", value: "bodyVariable" }],+ }),+ },+ ],+ },+ ]);+ expect(data.instances.get("boxId")?.children).toEqual([+ { type: "expression", value: encodeDataVariableId(bodyVariableId) },+ ]);+});+test("delete variable and unset it in resources", () => {const bodyVariable = new Variable("bodyVariable", "one value of body");const resourceVariable = new ResourceValue("resourceVariable", {@@ -1161,3 +1475,534 @@ test("find variable usages counts unique instances not expressions", () => {expect(usagesByInstance.get(bodyVariableId)).toEqual(new Set(["bodyId"]));expect(usagesByInstance.get(bodyVariableId)?.size).toBe(1);});++describe("createResourceValue", () => {+ test("parse resource create and update inputs used by the API", () => {+ expect(+ resourceFieldsInput.parse({+ name: "Users",+ method: "get",+ url: '"https://example.com/users"',+ searchParams: [{ name: "page", value: '"1"' }],+ headers: [{ name: "Accept", value: '"application/json"' }],+ control: "system",+ })+ ).toEqual({+ name: "Users",+ method: "get",+ url: '"https://example.com/users"',+ searchParams: [{ name: "page", value: '"1"' }],+ headers: [{ name: "Accept", value: '"application/json"' }],+ control: "system",+ });++ expect(resourceFieldsUpdateInput.parse({ name: "Updated" })).toEqual({+ name: "Updated",+ });+ });++ test("reject invalid resource controls", () => {+ expect(() =>+ resourceFieldsInput.parse({+ name: "Users",+ method: "get",+ url: '"https://example.com/users"',+ searchParams: [],+ headers: [],+ control: "manual",+ })+ ).toThrow();+ });++ test("creates resource values through the sdk schema", () => {+ expect(+ createResourceValue({+ id: "resource-id",+ name: "Users",+ method: "post",+ url: '"https://example.com/users"',+ searchParams: [{ name: "page", value: '"1"' }],+ headers: [{ name: "Authorization", value: '"Bearer token"' }],+ body: '"body"',+ })+ ).toEqual({+ id: "resource-id",+ name: "Users",+ method: "post",+ url: '"https://example.com/users"',+ searchParams: [{ name: "page", value: '"1"' }],+ headers: [{ name: "Authorization", value: '"Bearer token"' }],+ body: '"body"',+ });+ });++ test("omits empty body values", () => {+ expect(+ createResourceValue({+ id: "resource-id",+ name: "Users",+ method: "get",+ url: '"https://example.com/users"',+ searchParams: [],+ headers: [],+ body: "",+ })+ ).toHaveProperty("body", undefined);+ });+});++describe("findResource", () => {+ test("finds resources by id", () => {+ expect(+ findResource(+ [+ {+ id: "resource-id",+ name: "Users",+ method: "get",+ url: '"https://example.com/users"',+ searchParams: [],+ headers: [],+ },+ ],+ "resource-id"+ )?.name+ ).toBe("Users");+ expect(findResource([], "missing")).toBeUndefined();+ });+});++describe("serializeResources", () => {+ test("reports resource exposure and filters by scoped data source", () => {+ const resources: Resource[] = [+ {+ id: "resource-1",+ name: "Users",+ method: "get",+ url: '"https://example.com/users"',+ searchParams: [],+ headers: [],+ },+ {+ id: "resource-2",+ name: "Posts",+ method: "post",+ url: '"https://example.com/posts"',+ searchParams: [],+ headers: [],+ },+ ];+ const dataSources: DataSource[] = [+ {+ id: "data-source-other-scope",+ scopeInstanceId: "other-box",+ name: "usersOther",+ type: "resource",+ resourceId: "resource-1",+ },+ {+ id: "data-source-1",+ scopeInstanceId: "box",+ name: "users",+ type: "resource",+ resourceId: "resource-1",+ },+ ];++ expect(serializeResources({ resources, dataSources })).toEqual({+ resources: [+ {+ id: "resource-1",+ name: "Users",+ method: "get",+ url: '"https://example.com/users"',+ scopeInstanceId: "other-box",+ exposedAsDataSource: true,+ dataSourceId: "data-source-other-scope",+ },+ {+ id: "resource-2",+ name: "Posts",+ method: "post",+ url: '"https://example.com/posts"',+ scopeInstanceId: undefined,+ exposedAsDataSource: false,+ dataSourceId: undefined,+ },+ ],+ });+ expect(+ serializeResources({ resources, dataSources, scopeInstanceId: "box" })+ ).toEqual({+ resources: [+ {+ id: "resource-1",+ name: "Users",+ method: "get",+ url: '"https://example.com/users"',+ scopeInstanceId: "box",+ exposedAsDataSource: true,+ dataSourceId: "data-source-1",+ },+ ],+ });+ });+});++describe("resource patch helpers", () => {+ const resource: Resource = {+ id: "resource",+ name: "Users",+ method: "get",+ url: '"https://example.com/users"',+ searchParams: [],+ headers: [],+ };++ test("upserts resource variables and rebinds expressions", () => {+ const body: Instance = {+ type: "instance",+ id: "body",+ component: "Body",+ children: [{ type: "id", value: "box" }],+ };+ const box: Instance = {+ type: "instance",+ id: "box",+ component: "Box",+ children: [+ { type: "expression", value: encodeDataVariableId("body-var") },+ ],+ };+ const data = {+ pages: undefined,+ instances: new Map([+ [body.id, body],+ [box.id, box],+ ]),+ props: new Map(),+ dataSources: new Map<DataSource["id"], DataSource>([+ [+ "body-var",+ {+ id: "body-var",+ scopeInstanceId: "body",+ name: "Users",+ type: "variable",+ value: { type: "string", value: "fallback" },+ },+ ],+ ]),+ resources: new Map<Resource["id"], Resource>(),+ };++ upsertResourceMutable({+ data,+ resource,+ dataSourceId: "resource-var",+ scopeInstanceId: "box",+ dataSourceName: "Users",+ });++ expect(data.resources.get("resource")).toEqual(resource);+ expect(data.dataSources.get("resource-var")).toEqual({+ id: "resource-var",+ scopeInstanceId: "box",+ name: "Users",+ type: "resource",+ resourceId: "resource",+ });+ expect(data.instances.get("box")?.children).toEqual([+ { type: "expression", value: encodeDataVariableId("resource-var") },+ ]);+ });++ test("creates resource upsert patches from builder data", () => {+ const body: Instance = {+ type: "instance",+ id: "body",+ component: "Body",+ children: [{ type: "id", value: "box" }],+ };+ const box: Instance = {+ type: "instance",+ id: "box",+ component: "Box",+ children: [+ { type: "expression", value: encodeDataVariableId("body-var") },+ ],+ };++ expect(+ createResourceUpsertPatchPayload({+ build: {+ pages: {+ homePageId: "page",+ rootFolderId: "root-folder",+ pages: new Map([+ [+ "page",+ {+ id: "page",+ name: "Home",+ path: "",+ title: "Home",+ rootInstanceId: "body",+ meta: {},+ },+ ],+ ]),+ folders: new Map([+ [+ "root-folder",+ {+ id: "root-folder",+ name: "Root",+ slug: "",+ children: ["page"],+ },+ ],+ ]),+ },+ instances: [body, box],+ props: [],+ dataSources: [+ {+ id: "body-var",+ scopeInstanceId: "body",+ name: "Users",+ type: "variable",+ value: { type: "string", value: "fallback" },+ },+ ],+ resources: [],+ breakpoints: [],+ styleSources: [],+ styleSourceSelections: [],+ styles: [],+ },+ resource,+ dataSourceId: "resource-var",+ scopeInstanceId: "box",+ dataSourceName: "Users",+ })+ ).toEqual([+ {+ namespace: "instances",+ patches: [+ {+ op: "replace",+ path: ["box"],+ value: {+ ...box,+ children: [+ {+ type: "expression",+ value: encodeDataVariableId("resource-var"),+ },+ ],+ },+ },+ ],+ },+ {+ namespace: "dataSources",+ patches: [+ {+ op: "add",+ path: ["resource-var"],+ value: {+ id: "resource-var",+ scopeInstanceId: "box",+ name: "Users",+ type: "resource",+ resourceId: "resource",+ },+ },+ ],+ },+ {+ namespace: "resources",+ patches: [{ op: "add", path: ["resource"], value: resource }],+ },+ ]);+ });++ test("creates resource and optional data source patches", () => {+ expect(+ createResourceCreatePayload({+ resourceId: "resource",+ resource,+ resources: [],+ dataSources: [],+ dataSourceId: "data-source",+ scopeInstanceId: "box",+ })+ ).toEqual({+ payload: [+ {+ namespace: "resources",+ patches: [{ op: "add", path: ["resource"], value: resource }],+ },+ {+ namespace: "dataSources",+ patches: [+ {+ op: "add",+ path: ["data-source"],+ value: {+ id: "data-source",+ scopeInstanceId: "box",+ name: "Users",+ type: "resource",+ resourceId: "resource",+ },+ },+ ],+ },+ ],+ dataSourceId: "data-source",+ errors: [],+ });+ });++ test("reports resource create id conflicts", () => {+ expect(+ createResourceCreatePayload({+ resourceId: "resource",+ resource,+ resources: [resource],+ dataSources: [+ {+ id: "data-source",+ scopeInstanceId: "box",+ name: "Users",+ type: "resource",+ resourceId: "resource",+ },+ ],+ dataSourceId: "data-source",+ scopeInstanceId: "box",+ }).errors+ ).toEqual([+ { type: "duplicate-resource-id", resourceId: "resource" },+ { type: "duplicate-data-source-id", dataSourceId: "data-source" },+ ]);+ });++ test("creates resource update patches with data source metadata", () => {+ const dataSource: DataSource = {+ id: "data-source",+ scopeInstanceId: "box",+ name: "Users",+ type: "resource",+ resourceId: "resource",+ };++ expect(+ createResourceUpdatePayload({+ resource,+ values: { name: "Updated" },+ dataSources: [dataSource],+ dataSourceName: "Updated source",+ scopeInstanceId: "root",+ })+ ).toEqual([+ {+ namespace: "resources",+ patches: [+ { op: "replace", path: ["resource", "name"], value: "Updated" },+ ],+ },+ {+ namespace: "dataSources",+ patches: [+ {+ op: "replace",+ path: ["data-source", "name"],+ value: "Updated source",+ },+ {+ op: "replace",+ path: ["data-source", "scopeInstanceId"],+ value: "root",+ },+ ],+ },+ ]);+ });++ test("creates resource delete payload and guards prop usages", () => {+ const prop: Prop = {+ id: "prop",+ instanceId: "box",+ name: "data",+ type: "resource",+ value: "resource",+ };+ const dataSource: DataSource = {+ id: "data-source",+ scopeInstanceId: "box",+ name: "Users",+ type: "resource",+ resourceId: "resource",+ };++ expect(+ createResourceDeletePayload({+ resource,+ props: [prop],+ dataSources: [dataSource],+ })+ ).toEqual({ payload: [], dataSourceIds: [], propIds: [], isUsed: true });++ expect(+ createResourceDeletePayload({+ resource,+ props: [prop],+ dataSources: [dataSource],+ force: true,+ })+ ).toEqual({+ payload: [+ {+ namespace: "resources",+ patches: [{ op: "remove", path: ["resource"] }],+ },+ {+ namespace: "dataSources",+ patches: [{ op: "remove", path: ["data-source"] }],+ },+ {+ namespace: "props",+ patches: [{ op: "remove", path: ["prop"] }],+ },+ ],+ dataSourceIds: ["data-source"],+ propIds: ["prop"],+ isUsed: false,+ });+ });+});++describe("getResourceExpressionErrors", () => {+ test("returns field-prefixed expression errors", () => {+ expect(+ getResourceExpressionErrors({+ url: "invalid +",+ body: "body +",+ headers: [{ name: "Authorization", value: "header +" }],+ searchParams: [{ name: "q", value: "query +" }],+ })+ ).toEqual([+ expect.stringMatching(/^url: /),+ expect.stringMatching(/^body: /),+ expect.stringMatching(/^headers\.0\.value: /),+ expect.stringMatching(/^searchParams\.0\.value: /),+ ]);+ });++ test("allows omitted optional expressions", () => {+ expect(getResourceExpressionErrors({})).toEqual([]);+ });+});diff --git a/packages/project-build/src/runtime/data.ts b/packages/project-build/src/runtime/data.tsnew file mode 100644index 0000000000..d4d1e2a574--- /dev/null+++ b/packages/project-build/src/runtime/data.ts@@ -0,0 +1,1928 @@+import {+ type Asset,+ collectionComponent,+ dataSourceVariableValue,+ decodeDataVariableId,+ decodeDataSourceVariable,+ encodeDataVariableId,+ encodeDataSourceVariable,+ findTreeInstanceIds,+ findTreeInstanceIdsExcludingSlotDescendants,+ getAllPages,+ getExpressionIdentifiers,+ getStyleDeclKey,+ lintExpression,+ ROOT_INSTANCE_ID,+ resource,+ SYSTEM_VARIABLE_ID,+ systemParameter,+ transpileExpression,+ type DataSource,+ type DataSources,+ type Instance,+ type Instances,+ type Pages,+ type Prop,+ type Props,+ type Resource,+ type Resources,+ type WebstudioData,+} from "@webstudio-is/sdk";+import { z } from "zod";+import deepEqual from "fast-deep-equal";+import {+ createJsonStringifyProxy,+ isPlainObject,+} from "@webstudio-is/sdk/runtime";+import type { CompactBuild } from "../types";+import {+ compactBuilderPatchPayload,+ type BuilderPatchChange,+} from "../contracts/patch";+import type { BuilderState } from "../state/builder-state";+import type { BuilderRuntimeContext } from "./context";+import { throwBuilderRuntimeError } from "./errors";+import { createRuntimeMutation } from "./mutation";++const getRequiredDataSources = (state: Pick<BuilderState, "dataSources">) => {+ if (state.dataSources === undefined) {+ return throwBuilderRuntimeError(+ "BAD_REQUEST",+ "Data sources namespace is missing"+ );+ }+ return state.dataSources;+};++const getRequiredResources = (state: Pick<BuilderState, "resources">) => {+ if (state.resources === undefined) {+ return throwBuilderRuntimeError(+ "BAD_REQUEST",+ "Resources namespace is missing"+ );+ }+ return state.resources;+};++const getRequiredProps = (state: Pick<BuilderState, "props">) => {+ if (state.props === undefined) {+ return throwBuilderRuntimeError(+ "BAD_REQUEST",+ "Props namespace is missing"+ );+ }+ return state.props;+};++const getRequiredBuildData = (+ state: Pick<+ BuilderState,+ | "pages"+ | "instances"+ | "props"+ | "dataSources"+ | "resources"+ | "breakpoints"+ | "styleSources"+ | "styleSourceSelections"+ | "styles"+ >+) => {+ const missing = (+ [+ "pages",+ "instances",+ "props",+ "dataSources",+ "resources",+ "breakpoints",+ "styleSources",+ "styleSourceSelections",+ "styles",+ ] as const+ ).find((namespace) => state[namespace] === undefined);+ if (missing !== undefined) {+ return throwBuilderRuntimeError(+ "BAD_REQUEST",+ `${missing} namespace is missing`+ );+ }+ return {+ pages: state.pages!,+ instances: Array.from(state.instances!.values()),+ props: Array.from(state.props!.values()),+ dataSources: Array.from(state.dataSources!.values()),+ resources: Array.from(state.resources!.values()),+ breakpoints: Array.from(state.breakpoints!.values()),+ styleSources: Array.from(state.styleSources!.values()),+ styleSourceSelections: Array.from(state.styleSourceSelections!.values()),+ styles: Array.from(state.styles!.values()),+ };+};++export const findDataVariable = (+ dataSources: Iterable<DataSource>,+ dataSourceId: DataSource["id"]+) => {+ for (const dataSource of dataSources) {+ if (dataSource.id === dataSourceId && dataSource.type === "variable") {+ return dataSource;+ }+ }+};++export const serializeDataVariables = ({+ dataSources,+ scopeInstanceId,+}: {+ dataSources: Iterable<DataSource> | Map<string, DataSource>;+ scopeInstanceId?: Instance["id"];+}) => ({+ variables: (dataSources instanceof Map+ ? Array.from(dataSources.values())+ : Array.from(dataSources)+ )+ .filter((dataSource) => dataSource.type === "variable")+ .filter(+ (dataSource) =>+ scopeInstanceId === undefined ||+ dataSource.scopeInstanceId === scopeInstanceId+ )+ .map((dataSource) => ({+ id: dataSource.id,+ name: dataSource.name,+ scopeInstanceId: dataSource.scopeInstanceId,+ value: dataSource.value,+ })),+});++export const listDataVariables = (+ state: Pick<BuilderState, "dataSources">,+ input: { scopeInstanceId?: string } = {}+) =>+ serializeDataVariables({+ dataSources: getRequiredDataSources(state),+ scopeInstanceId: input.scopeInstanceId,+ });++export const dataVariableValueInput = dataSourceVariableValue;++type DataVariable = Extract<DataSource, { type: "variable" }>;++export type DataVariableNameError = {+ type: "required" | "duplicate";+ message: string;+};++export const validateDataVariableNameWithSources = ({+ dataSources,+ name,+ variableId,+ scopeInstanceId,+}: {+ dataSources: Iterable<DataSource>;+ name: string;+ variableId?: DataSource["id"];+ scopeInstanceId?: Instance["id"];+}): DataVariableNameError | undefined => {+ if (name.trim().length === 0) {+ return {+ type: "required",+ message: "Variable name is required",+ };+ }++ for (const dataSource of dataSources) {+ if (+ dataSource.type === "variable" &&+ dataSource.scopeInstanceId === scopeInstanceId &&+ dataSource.name === name &&+ dataSource.id !== variableId+ ) {+ return {+ type: "duplicate",+ message: "Name is already used by another variable on this instance",+ };+ }+ }+};++const allowedJsChars = /[A-Za-z_]/;+const compiledExpressionCacheLimit = 10_000;+type CompiledExpression = (variables: {+ get: (key: DataSource["name"]) => unknown;+ // Dynamic expressions intentionally preserve the historical `any` result.+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+}) => any;++const compiledExpressionCache = new Map<string, CompiledExpression>();++const setUnion = <Item>(current: Set<Item>, other: Set<Item>) => {+ const result = new Set<Item>(current);+ for (const item of other) {+ result.add(item);+ }+ return result;+};++const getCompiledExpression = (expression: string) => {+ const cached = compiledExpressionCache.get(expression);+ if (cached) {+ return cached;+ }++ const usedVariables = new Map<string, DataSource["name"]>();+ const transpiled = transpileExpression({+ expression,+ executable: true,+ replaceVariable: (identifier) => {+ const id = decodeDataVariableId(identifier);+ if (id) {+ usedVariables.set(identifier, id);+ } else {+ const name = decodeDataVariableName(identifier);+ usedVariables.set(identifier, name);+ }+ },+ });+ let code = "";+ for (const [identifier, name] of usedVariables) {+ code += `let ${identifier} = _variables.get(${JSON.stringify(name)});\n`;+ }+ code += `return (${transpiled})`;++ const compiledExpression = new Function(+ "_variables",+ code+ ) as CompiledExpression;+ compiledExpressionCache.set(expression, compiledExpression);+ if (compiledExpressionCache.size > compiledExpressionCacheLimit) {+ const oldestExpression = compiledExpressionCache.keys().next().value;+ if (oldestExpression !== undefined) {+ compiledExpressionCache.delete(oldestExpression);+ }+ }+ return compiledExpression;+};++export const encodeDataVariableName = (name: string) => {+ let encodedName = "";+ for (let index = 0; index < name.length; index += 1) {+ const char = name[index];+ encodedName += allowedJsChars.test(char)+ ? char+ : `$${char.codePointAt(0)}$`;+ }+ return encodedName;+};++export const decodeDataVariableName = (identifier: string) => {+ const name = identifier.replaceAll(/\$(\d+)\$/g, (_match, code) =>+ String.fromCodePoint(code)+ );+ return name;+};++export const unsetExpressionVariables = ({+ expression,+ unsetNameById,+}: {+ expression: string;+ unsetNameById: Map<DataSource["id"], DataSource["name"]>;+}) => {+ try {+ return transpileExpression({+ expression,+ replaceVariable: (identifier) => {+ const id = decodeDataVariableId(identifier);+ if (id) {+ const name = unsetNameById.get(id);+ if (name) {+ return encodeDataVariableName(name);+ }+ }+ return identifier;+ },+ });+ } catch {+ return expression;+ }+};++export const restoreExpressionVariables = ({+ expression,+ maskedIdByName,+}: {+ expression: string;+ maskedIdByName: Map<DataSource["name"], DataSource["id"]>;+}) => {+ try {+ return transpileExpression({+ expression,+ replaceVariable: (identifier) => {+ const name = decodeDataVariableName(identifier);+ if (name) {+ const id = maskedIdByName.get(name);+ if (id) {+ return encodeDataVariableId(id);+ }+ }+ return identifier;+ },+ });+ } catch {+ return expression;+ }+};++export const replaceDataSourcesInExpression = (+ expression: string,+ replacements: Map<DataSource["id"], DataSource["id"]>+) => {+ return transpileExpression({+ expression,+ replaceVariable: (identifier) => {+ const dataSourceId = decodeDataSourceVariable(identifier);+ if (dataSourceId === undefined) {+ return;+ }+ return encodeDataSourceVariable(+ replacements.get(dataSourceId) ?? dataSourceId+ );+ },+ });+};++export const computeExpression = (+ expression: string,+ variables: Map<DataSource["name"], unknown>+) => {+ try {+ const proxiedVariables = new Map<DataSource["name"], unknown>();+ const getVariable = (key: DataSource["name"]) => {+ if (proxiedVariables.has(key)) {+ return proxiedVariables.get(key);+ }+ const value = variables.get(key);+ const proxiedValue = isPlainObject(value)+ ? createJsonStringifyProxy(+ Object.isFrozen(value) ? structuredClone(value) : value+ )+ : value;+ proxiedVariables.set(key, proxiedValue);+ return proxiedValue;+ };++ const result = getCompiledExpression(expression)({ get: getVariable });+ return result;+ } catch {+ return undefined;+ }+};++const getParentInstanceById = (instances: Instances) => {+ const parentInstanceById = new Map<Instance["id"], Instance["id"]>();+ for (const instance of instances.values()) {+ if (instance.component === "Slot") {+ continue;+ }+ for (const child of instance.children) {+ if (child.type === "id") {+ parentInstanceById.set(child.value, instance.id);+ }+ }+ }+ return parentInstanceById;+};++const getDataSourcesByScopeInstanceId = (dataSources: DataSources) => {+ const dataSourcesByScopeInstanceId = new Map<+ Instance["id"],+ Array<DataSource>+ >();+ for (const dataSource of dataSources.values()) {+ const instanceId = dataSource.scopeInstanceId ?? ROOT_INSTANCE_ID;+ const dataSourcesByScope =+ dataSourcesByScopeInstanceId.get(instanceId) ?? [];+ dataSourcesByScope.push(dataSource);+ dataSourcesByScopeInstanceId.set(instanceId, dataSourcesByScope);+ }+ return dataSourcesByScopeInstanceId;+};++const findMaskedVariablesByInstanceId = ({+ startingInstanceId,+ parentInstanceById,+ instances,+ dataSources,+ dataSourcesByScopeInstanceId = getDataSourcesByScopeInstanceId(dataSources),+}: {+ startingInstanceId: Instance["id"];+ parentInstanceById: Map<Instance["id"], Instance["id"]>;+ instances: Instances;+ dataSources: DataSources;+ dataSourcesByScopeInstanceId?: Map<Instance["id"], Array<DataSource>>;+}) => {+ let currentId: undefined | string = startingInstanceId;+ const instanceIdsPath: Instance["id"][] = [];+ while (currentId) {+ instanceIdsPath.push(currentId);+ currentId = parentInstanceById.get(currentId);+ }+ instanceIdsPath.push(ROOT_INSTANCE_ID);+ const maskedVariables = new Map<DataSource["name"], DataSource["id"]>();+ maskedVariables.set("system", SYSTEM_VARIABLE_ID);+ for (const instanceId of instanceIdsPath.reverse()) {+ const instance = instances.get(instanceId);+ const scopedDataSources = dataSourcesByScopeInstanceId.get(instanceId);+ if (scopedDataSources === undefined) {+ continue;+ }+ for (const dataSource of scopedDataSources) {+ if (+ instanceId === startingInstanceId &&+ instance?.component === collectionComponent &&+ dataSource.type === "parameter"+ ) {+ continue;+ }+ maskedVariables.set(dataSource.name, dataSource.id);+ }+ }+ return maskedVariables;+};++export const findAvailableVariables = ({+ startingInstanceId,+ instances,+ dataSources,+}: {+ startingInstanceId: Instance["id"];+ instances: Instances;+ dataSources: DataSources;+}) => {+ const maskedVariables = findMaskedVariablesByInstanceId({+ startingInstanceId,+ parentInstanceById: getParentInstanceById(instances),+ instances,+ dataSources,+ dataSourcesByScopeInstanceId: getDataSourcesByScopeInstanceId(dataSources),+ });+ const availableVariables: DataSource[] = [];+ for (const dataSourceId of maskedVariables.values()) {+ const dataSource = dataSources.get(dataSourceId);+ if (dataSource) {+ availableVariables.push(dataSource);+ }+ if (dataSourceId === SYSTEM_VARIABLE_ID) {+ availableVariables.push(systemParameter);+ }+ }+ return availableVariables;+};++const traverseExpressions = ({+ startingInstanceId,+ pages,+ instances,+ props,+ dataSources,+ resources,+ update,+}: {+ startingInstanceId: undefined | Instance["id"];+ pages: undefined | Pages;+ instances: Instances;+ props: Props;+ dataSources: DataSources;+ resources: Resources;+ update: (+ expression: string,+ instanceId: Instance["id"],+ args?: string[]+ ) => void | string;+}) => {+ const pagesList = pages ? getAllPages(pages) : [];++ let instanceIds =+ startingInstanceId === undefined+ ? new Set(instances.keys())+ : findTreeInstanceIdsExcludingSlotDescendants(+ instances,+ startingInstanceId+ );+ for (const page of pagesList) {+ if (startingInstanceId === ROOT_INSTANCE_ID) {+ instanceIds = setUnion(+ instanceIds,+ findTreeInstanceIds(instances, page.rootInstanceId)+ );+ }++ if (+ startingInstanceId === page.rootInstanceId ||+ startingInstanceId === ROOT_INSTANCE_ID+ ) {+ const { rootInstanceId } = page;+ page.title = update(page.title, rootInstanceId) ?? page.title;+ if (page.meta.description) {+ page.meta.description =+ update(page.meta.description, rootInstanceId) ??+ page.meta.description;+ }+ if (page.meta.excludePageFromSearch) {+ page.meta.excludePageFromSearch =+ update(page.meta.excludePageFromSearch, rootInstanceId) ??+ page.meta.excludePageFromSearch;+ }+ if (page.meta.socialImageUrl) {+ page.meta.socialImageUrl =+ update(page.meta.socialImageUrl, rootInstanceId) ??+ page.meta.socialImageUrl;+ }+ if (page.meta.language) {+ page.meta.language =+ update(page.meta.language, rootInstanceId) ?? page.meta.language;+ }+ if (page.meta.status) {+ page.meta.status =+ update(page.meta.status, rootInstanceId) ?? page.meta.status;+ }+ if (page.meta.redirect) {+ page.meta.redirect =+ update(page.meta.redirect, rootInstanceId) ?? page.meta.redirect;+ }+ if (page.meta.custom) {+ for (const item of page.meta.custom) {+ item.content = update(item.content, rootInstanceId) ?? item.content;+ }+ }+ }+ }+ const instanceIdByResourceId = new Map<Resource["id"], Instance["id"]>();++ for (const instance of instances.values()) {+ if (instanceIds.has(instance.id) === false) {+ continue;+ }+ for (const child of instance.children) {+ if (child.type === "expression") {+ child.value = update(child.value, instance.id) ?? child.value;+ }+ }+ }++ for (const prop of props.values()) {+ if (instanceIds.has(prop.instanceId) === false) {+ continue;+ }+ if (prop.type === "expression") {+ prop.value = update(prop.value, prop.instanceId) ?? prop.value;+ continue;+ }+ if (prop.type === "action") {+ for (const action of prop.value) {+ action.code =+ update(action.code, prop.instanceId, action.args) ?? action.code;+ }+ continue;+ }+ if (prop.type === "resource") {+ instanceIdByResourceId.set(prop.value, prop.instanceId);+ continue;+ }+ }++ for (const dataSource of dataSources.values()) {+ const instanceId = dataSource.scopeInstanceId ?? ROOT_INSTANCE_ID;+ if (instanceIds.has(instanceId) && dataSource.type === "resource") {+ instanceIdByResourceId.set(dataSource.resourceId, instanceId);+ }+ }++ for (const resource of resources.values()) {+ const instanceId = instanceIdByResourceId.get(resource.id);+ if (instanceId === undefined) {+ continue;+ }+ resource.url = update(resource.url, instanceId) ?? resource.url;+ for (const header of resource.headers) {+ header.value = update(header.value, instanceId) ?? header.value;+ }+ if (resource.searchParams) {+ for (const searchParam of resource.searchParams) {+ searchParam.value =+ update(searchParam.value, instanceId) ?? searchParam.value;+ }+ }+ if (resource.body) {+ resource.body = update(resource.body, instanceId) ?? resource.body;+ }+ }+};++export const findUnsetVariableNames = ({+ instances,+ props,+ dataSources,+ resources,+}: {+ startingInstanceId: Instance["id"];+ instances: Instances;+ props: Props;+ dataSources: DataSources;+ resources: Resources;+}) => {+ const unsetVariables = new Set<DataSource["name"]>();+ traverseExpressions({+ startingInstanceId: undefined,+ pages: undefined,+ instances,+ props,+ dataSources,+ resources,+ update: (expression, _instanceId, args = []) => {+ transpileExpression({+ expression,+ replaceVariable: (identifier) => {+ const id = decodeDataVariableId(identifier);+ if (id === undefined && args.includes(identifier) === false) {+ unsetVariables.add(decodeDataVariableName(identifier));+ }+ },+ });+ },+ });+ return Array.from(unsetVariables);+};++export const findUsedVariables = ({+ startingInstanceId,+ pages,+ instances,+ props,+ dataSources,+ resources,+}: {+ startingInstanceId: Instance["id"];+ pages: undefined | Pages;+ instances: Instances;+ props: Props;+ dataSources: DataSources;+ resources: Resources;+}) => {+ const usedVariables = new Map<DataSource["id"], number>();+ traverseExpressions({+ startingInstanceId,+ pages,+ instances,+ props,+ dataSources,+ resources,+ update: (expression) => {+ const identifiers = getExpressionIdentifiers(expression);+ for (const identifier of identifiers) {+ const id = decodeDataVariableId(identifier);+ if (id !== undefined) {+ const count = usedVariables.get(id) ?? 0;+ usedVariables.set(id, count + 1);+ }+ }+ },+ });+ return usedVariables;+};++export const findVariableUsagesByInstance = ({+ startingInstanceId,+ pages,+ instances,+ props,+ dataSources,+ resources,+}: {+ startingInstanceId: Instance["id"];+ pages: undefined | Pages;+ instances: Instances;+ props: Props;+ dataSources: DataSources;+ resources: Resources;+}) => {+ const usedIn = new Map<DataSource["id"], Set<Instance["id"]>>();+ traverseExpressions({+ startingInstanceId,+ pages,+ instances,+ props,+ dataSources,+ resources,+ update: (expression, instanceId) => {+ const identifiers = getExpressionIdentifiers(expression);+ for (const identifier of identifiers) {+ const id = decodeDataVariableId(identifier);+ if (id !== undefined) {+ if (!usedIn.has(id)) {+ usedIn.set(id, new Set());+ }+ usedIn.get(id)?.add(instanceId);+ }+ }+ },+ });+ return usedIn;+};++export const rebindTreeVariablesMutable = ({+ startingInstanceId,+ pages,+ instances,+ props,+ dataSources,+ resources,+}: {+ startingInstanceId: Instance["id"];+ pages: undefined | Pages;+ instances: Instances;+ props: Props;+ dataSources: DataSources;+ resources: Resources;+}) => {+ const unsetNameById = new Map<DataSource["id"], DataSource["name"]>();+ for (const dataSource of dataSources.values()) {+ unsetNameById.set(dataSource.id, dataSource.name);+ }+ const parentInstanceById = getParentInstanceById(instances);+ const dataSourcesByScopeInstanceId =+ getDataSourcesByScopeInstanceId(dataSources);+ traverseExpressions({+ startingInstanceId,+ pages,+ instances,+ props,+ dataSources,+ resources,+ update: (expression, instanceId, args) => {+ const maskedVariables = findMaskedVariablesByInstanceId({+ startingInstanceId: instanceId,+ parentInstanceById,+ instances,+ dataSources,+ dataSourcesByScopeInstanceId,+ });+ const maskedIdByName = new Map(maskedVariables);+ if (args) {+ for (const arg of args) {+ maskedIdByName.delete(arg);+ }+ }+ expression = unsetExpressionVariables({+ expression,+ unsetNameById,+ });+ expression = restoreExpressionVariables({+ expression,+ maskedIdByName,+ });+ return expression;+ },+ });+};++export const deleteVariableMutable = (+ data: Pick<+ BuilderState,+ "instances" | "props" | "dataSources" | "resources"+ > & {+ pages?: Pages;+ },+ variableId: DataSource["id"]+) => {+ if (+ data.instances === undefined ||+ data.props === undefined ||+ data.dataSources === undefined ||+ data.resources === undefined+ ) {+ return;+ }+ const dataSource = data.dataSources.get(variableId);+ if (dataSource === undefined) {+ return;+ }+ data.dataSources.delete(variableId);+ if (dataSource.type === "resource") {+ data.resources.delete(dataSource.resourceId);+ }+ const unsetNameById = new Map<DataSource["id"], DataSource["name"]>();+ unsetNameById.set(dataSource.id, dataSource.name);+ const startingInstanceId = dataSource.scopeInstanceId ?? ROOT_INSTANCE_ID;+ const maskedIdByName = findMaskedVariablesByInstanceId({+ startingInstanceId,+ parentInstanceById: getParentInstanceById(data.instances),+ instances: data.instances,+ dataSources: data.dataSources,+ dataSourcesByScopeInstanceId: getDataSourcesByScopeInstanceId(+ data.dataSources+ ),+ });+ traverseExpressions({+ instances: data.instances,+ props: data.props,+ dataSources: data.dataSources,+ resources: data.resources,+ pages: data.pages,+ startingInstanceId,+ update: (expression) => {+ expression = unsetExpressionVariables({+ expression,+ unsetNameById,+ });+ expression = restoreExpressionVariables({+ expression,+ maskedIdByName,+ });+ return expression;+ },+ });+};++const valuesEqual = (left: unknown, right: unknown) => deepEqual(left, right);++const cloneMap = <Key, Value>(map: Map<Key, Value>) =>+ new Map<Key, Value>(+ Array.from(map, ([key, value]) => [key, structuredClone(value)])+ );++const createMapPatchPayload = <+ Namespace extends BuilderPatchChange["namespace"],+ Key extends string,+ Value,+>(+ namespace: Namespace,+ before: Map<Key, Value>,+ after: Map<Key, Value>+): BuilderPatchChange => {+ const patches: BuilderPatchChange["patches"] = [];+ for (const [key, value] of before) {+ const nextValue = after.get(key);+ if (nextValue === undefined) {+ patches.push({ op: "remove", path: [key] });+ continue;+ }+ if (valuesEqual(value, nextValue) === false) {+ patches.push({ op: "replace", path: [key], value: nextValue });+ }+ }+ for (const [key, value] of after) {+ if (before.has(key) === false) {+ patches.push({ op: "add", path: [key], value });+ }+ }+ return { namespace, patches };+};++export const createDataVariableDeletePayload = ({+ variableId,+ pages,+ instances,+ props,+ dataSources,+ resources,+}: Pick<BuilderState, "instances" | "props" | "dataSources" | "resources"> & {+ pages?: Pages;+ variableId: DataSource["id"];+}): {+ payload: BuilderPatchChange[];+ deletedVariable?: DataSource;+} => {+ if (+ instances === undefined ||+ props === undefined ||+ dataSources === undefined ||+ resources === undefined+ ) {+ return { payload: [] };+ }+ const deletedVariable = dataSources.get(variableId);+ if (deletedVariable === undefined) {+ return { payload: [] };+ }++ const beforePages = pages === undefined ? undefined : structuredClone(pages);+ const nextData = {+ pages: beforePages === undefined ? undefined : structuredClone(beforePages),+ instances: cloneMap(instances),+ props: cloneMap(props),+ dataSources: cloneMap(dataSources),+ resources: cloneMap(resources),+ };+ deleteVariableMutable(nextData, variableId);+ const payload = compactBuilderPatchPayload([+ beforePages === undefined || valuesEqual(beforePages, nextData.pages)+ ? { namespace: "pages" as const, patches: [] }+ : {+ namespace: "pages" as const,+ patches: [+ { op: "replace" as const, path: [], value: nextData.pages },+ ],+ },+ createMapPatchPayload("instances", instances, nextData.instances),+ createMapPatchPayload("props", props, nextData.props),+ createMapPatchPayload("dataSources", dataSources, nextData.dataSources),+ createMapPatchPayload("resources", resources, nextData.resources),+ ]);+ return { payload, deletedVariable };+};++const createDataVariableValue = ({+ dataSourceId,+ scopeInstanceId,+ name,+ value,+}: {+ dataSourceId: DataSource["id"];+ scopeInstanceId: Instance["id"];+ name: DataSource["name"];+ value: DataVariable["value"];+}): DataVariable => ({+ id: dataSourceId,+ scopeInstanceId,+ name,+ type: "variable",+ value,+});++export const createDataVariableCreatePayload = ({+ dataSourceId,+ scopeInstanceId,+ name,+ value,+ dataSources,+}: {+ dataSourceId: DataSource["id"];+ scopeInstanceId: Instance["id"];+ name: DataSource["name"];+ value: DataVariable["value"];+ dataSources: Iterable<DataSource>;+}) => {+ const errors = [];+ for (const dataSource of dataSources) {+ if (dataSource.id === dataSourceId) {+ errors.push({ type: "duplicate-id" as const, dataSourceId });+ break;+ }+ }+ const nameError = validateDataVariableNameWithSources({+ dataSources,+ name,+ variableId: dataSourceId,+ scopeInstanceId,+ });+ if (nameError) {+ errors.push(nameError);+ }+ if (errors.length > 0) {+ return { payload: [], errors };+ }+ return {+ payload: [+ {+ namespace: "dataSources" as const,+ patches: [+ {+ op: "add" as const,+ path: [dataSourceId],+ value: createDataVariableValue({+ dataSourceId,+ scopeInstanceId,+ name,+ value,+ }),+ },+ ],+ },+ ],+ errors,+ };+};++export const createDataVariableUpdatePayload = ({+ variable,+ values,+ dataSources,+}: {+ variable: DataVariable;+ values: Partial<Pick<DataVariable, "scopeInstanceId" | "name" | "value">>;+ dataSources: Iterable<DataSource>;+}) => {+ if (values.name !== undefined || values.scopeInstanceId !== undefined) {+ const error = validateDataVariableNameWithSources({+ dataSources,+ name: values.name ?? variable.name,+ variableId: variable.id,+ scopeInstanceId: values.scopeInstanceId ?? variable.scopeInstanceId,+ });+ if (error) {+ return { payload: [], error };+ }+ }+ return {+ payload: compactBuilderPatchPayload([+ {+ namespace: "dataSources",+ patches: Object.entries(values).flatMap(([name, value]) =>+ value === undefined+ ? []+ : [{ op: "replace" as const, path: [variable.id, name], value }]+ ),+ },+ ]),+ };+};++export const createDataVariable = (+ state: Pick<BuilderState, "dataSources">,+ input: {+ dataSourceId?: string;+ scopeInstanceId: string;+ name: string;+ value: z.infer<typeof dataVariableValueInput>;+ },+ context: BuilderRuntimeContext+) => {+ const dataSources = getRequiredDataSources(state);+ const dataSourceId = input.dataSourceId ?? context.createId();+ const { payload, errors } = createDataVariableCreatePayload({+ dataSourceId,+ scopeInstanceId: input.scopeInstanceId,+ name: input.name,+ value: input.value,+ dataSources: dataSources.values(),+ });+ const error = errors.at(0);+ if (error?.type === "duplicate-id") {+ return throwBuilderRuntimeError("CONFLICT", "Variable id already exists");+ }+ if (error) {+ return throwBuilderRuntimeError(+ "BAD_REQUEST",+ "message" in error ? error.message : "Invalid variable"+ );+ }+ return createRuntimeMutation({+ payload,+ result: { dataSourceId },+ invalidatesNamespaces: ["dataSources"],+ });+};++export const updateDataVariable = (+ state: Pick<BuilderState, "dataSources">,+ input: {+ dataSourceId: string;+ values: Partial<{+ scopeInstanceId: string;+ name: string;+ value: z.infer<typeof dataVariableValueInput>;+ }>;+ }+) => {+ const dataSources = getRequiredDataSources(state);+ const variable = findDataVariable(dataSources.values(), input.dataSourceId);+ if (variable === undefined) {+ return throwBuilderRuntimeError("NOT_FOUND", "Variable not found");+ }+ const { payload, error } = createDataVariableUpdatePayload({+ variable,+ values: input.values,+ dataSources: dataSources.values(),+ });+ if (error) {+ return throwBuilderRuntimeError("BAD_REQUEST", error.message);+ }+ return createRuntimeMutation({+ payload,+ result: { dataSourceId: variable.id },+ invalidatesNamespaces: ["dataSources"],+ });+};++export const deleteDataVariable = (+ state: Pick<+ BuilderState,+ "pages" | "instances" | "props" | "dataSources" | "resources"+ >,+ input: { dataSourceId: string }+) => {+ const { payload, deletedVariable } = createDataVariableDeletePayload({+ variableId: input.dataSourceId,+ pages: state.pages,+ instances: state.instances,+ props: state.props,+ dataSources: state.dataSources,+ resources: state.resources,+ });+ if (deletedVariable === undefined) {+ return throwBuilderRuntimeError("NOT_FOUND", "Variable not found");+ }+ return createRuntimeMutation({+ payload,+ result: { dataSourceId: deletedVariable.id },+ invalidatesNamespaces: [+ "pages",+ "instances",+ "props",+ "dataSources",+ "resources",+ ],+ });+};++export const findResource = (+ resources: Iterable<Resource>,+ resourceId: Resource["id"]+) => {+ for (const value of resources) {+ if (value.id === resourceId) {+ return value;+ }+ }+};++export const resourceFieldsInput = resource+ .omit({ id: true })+ .extend({ control: z.enum(["system", "graphql"]).optional() });++export const resourceFieldsUpdateInput = resourceFieldsInput.partial();++export const createResourceValue = ({+ id,+ control,+ name,+ url,+ searchParams,+ method,+ headers,+ body,+}: {+ id: Resource["id"];+ control?: unknown;+ name?: unknown;+ url: unknown;+ searchParams?: unknown;+ method: unknown;+ headers: unknown;+ body?: unknown;+}): Resource =>+ resource.parse({+ id,+ control,+ name,+ url,+ searchParams,+ method,+ headers,+ body: body || undefined,+ });++export const getResourceExpressionErrors = (+ fields: Partial<Pick<Resource, "url" | "body" | "headers" | "searchParams">>+) => {+ const errors: string[] = [];+ const validate = (name: string, expression: string | undefined) => {+ if (expression === undefined) {+ return;+ }+ for (const diagnostic of lintExpression({ expression })) {+ if (diagnostic.severity === "error") {+ errors.push(`${name}: ${diagnostic.message}`);+ }+ }+ };+ validate("url", fields.url);+ validate("body", fields.body);+ for (const [index, header] of (fields.headers ?? []).entries()) {+ validate(`headers.${index}.value`, header.value);+ }+ for (const [index, searchParam] of (fields.searchParams ?? []).entries()) {+ validate(`searchParams.${index}.value`, searchParam.value);+ }+ return errors;+};++const createResourceDataSource = ({+ dataSourceId,+ scopeInstanceId,+ name,+ resourceId,+}: {+ dataSourceId: DataSource["id"];+ scopeInstanceId: Instance["id"];+ name: DataSource["name"];+ resourceId: Resource["id"];+}): DataSource => ({+ id: dataSourceId,+ scopeInstanceId,+ name,+ type: "resource",+ resourceId,+});++const getClonedPair = <Item extends { id: string }>(item: Item) =>+ [item.id, structuredClone(item)] as const;++const getBuildItems = <Item>(items: Item[] | Map<string, Item>) =>+ items instanceof Map ? Array.from(items.values()) : items;++export const createWebstudioDataFromBuild = ({+ build,+ assets = [],+}: {+ build: Pick<+ CompactBuild | WebstudioData,+ | "pages"+ | "instances"+ | "props"+ | "dataSources"+ | "resources"+ | "breakpoints"+ | "styleSources"+ | "styleSourceSelections"+ | "styles"+ >;+ assets?: Asset[];+}): WebstudioData => ({+ pages: structuredClone(build.pages),+ assets: new Map(assets.map(getClonedPair)),+ instances: new Map(getBuildItems(build.instances).map(getClonedPair)),+ props: new Map(getBuildItems(build.props).map(getClonedPair)),+ dataSources: new Map(getBuildItems(build.dataSources).map(getClonedPair)),+ resources: new Map(getBuildItems(build.resources).map(getClonedPair)),+ breakpoints: new Map(getBuildItems(build.breakpoints).map(getClonedPair)),+ styleSources: new Map(getBuildItems(build.styleSources).map(getClonedPair)),+ styleSourceSelections: new Map(+ getBuildItems(build.styleSourceSelections).map((item) => [+ item.instanceId,+ structuredClone(item),+ ])+ ),+ styles: new Map(+ getBuildItems(build.styles).map((item) => [+ getStyleDeclKey(item),+ structuredClone(item),+ ])+ ),+});++const createMapPatches = <Value>({+ before,+ after,+ getPath,+}: {+ before: Map<string, Value>;+ after: Map<string, Value>;+ getPath: (id: string) => string[];+}) => {+ const patches: BuilderPatchChange["patches"] = [];+ for (const [id, value] of after) {+ if (before.has(id) === false) {+ patches.push({ op: "add", path: getPath(id), value });+ continue;+ }+ if (deepEqual(before.get(id), value) === false) {+ patches.push({ op: "replace", path: getPath(id), value });+ }+ }+ for (const id of before.keys()) {+ if (after.has(id) === false) {+ patches.push({ op: "remove", path: getPath(id) });+ }+ }+ return patches;+};++export const createWebstudioDataPatchPayload = ({+ before,+ after,+}: {+ before: WebstudioData;+ after: WebstudioData;+}): BuilderPatchChange[] => {+ const pagesPatches = [+ ...createMapPatches({+ before: before.pages.pages,+ after: after.pages.pages,+ getPath: (id) => ["pages", id],+ }),+ ...createMapPatches({+ before: before.pages.pageTemplates ?? new Map(),+ after: after.pages.pageTemplates ?? new Map(),+ getPath: (id) => ["pageTemplates", id],+ }),+ ...createMapPatches({+ before: before.pages.folders,+ after: after.pages.folders,+ getPath: (id) => ["folders", id],+ }),+ ];++ const payload: BuilderPatchChange[] = [+ { namespace: "pages", patches: pagesPatches },+ {+ namespace: "assets",+ patches: createMapPatches({+ before: before.assets,+ after: after.assets,+ getPath: (id) => [id],+ }),+ },+ {+ namespace: "instances",+ patches: createMapPatches({+ before: before.instances,+ after: after.instances,+ getPath: (id) => [id],+ }),+ },+ {+ namespace: "props",+ patches: createMapPatches({+ before: before.props,+ after: after.props,+ getPath: (id) => [id],+ }),+ },+ {+ namespace: "dataSources",+ patches: createMapPatches({+ before: before.dataSources,+ after: after.dataSources,+ getPath: (id) => [id],+ }),+ },+ {+ namespace: "resources",+ patches: createMapPatches({+ before: before.resources,+ after: after.resources,+ getPath: (id) => [id],+ }),+ },+ {+ namespace: "breakpoints",+ patches: createMapPatches({+ before: before.breakpoints,+ after: after.breakpoints,+ getPath: (id) => [id],+ }),+ },+ {+ namespace: "styleSourceSelections",+ patches: createMapPatches({+ before: before.styleSourceSelections,+ after: after.styleSourceSelections,+ getPath: (id) => [id],+ }),+ },+ {+ namespace: "styleSources",+ patches: createMapPatches({+ before: before.styleSources,+ after: after.styleSources,+ getPath: (id) => [id],+ }),+ },+ {+ namespace: "styles",+ patches: createMapPatches({+ before: before.styles,+ after: after.styles,+ getPath: (id) => [id],+ }),+ },+ ];+ return compactBuilderPatchPayload(payload);+};++export const upsertResourceMutable = ({+ data,+ resource,+ dataSourceId,+ scopeInstanceId,+ dataSourceName,+}: {+ data: Pick<+ WebstudioData,+ "instances" | "props" | "dataSources" | "resources"+ > & {+ pages: WebstudioData["pages"] | undefined;+ };+ resource: Resource;+ dataSourceId?: DataSource["id"];+ scopeInstanceId?: Instance["id"];+ dataSourceName?: DataSource["name"];+}) => {+ data.resources.set(resource.id, resource);+ if (dataSourceId !== undefined && scopeInstanceId !== undefined) {+ data.dataSources.set(+ dataSourceId,+ createResourceDataSource({+ dataSourceId,+ scopeInstanceId,+ name: dataSourceName ?? resource.name,+ resourceId: resource.id,+ })+ );+ rebindTreeVariablesMutable({+ startingInstanceId: scopeInstanceId,+ ...data,+ });+ if (data.pages !== undefined) {+ rebindTreeVariablesMutable({+ startingInstanceId: scopeInstanceId,+ ...data,+ pages: undefined,+ });+ }+ }+};++export const createResourceUpsertPatchPayload = ({+ build,+ resource,+ dataSourceId,+ scopeInstanceId,+ dataSourceName,+}: {+ build: Pick<+ CompactBuild,+ | "pages"+ | "instances"+ | "props"+ | "dataSources"+ | "resources"+ | "breakpoints"+ | "styleSources"+ | "styleSourceSelections"+ | "styles"+ >;+ resource: Resource;+ dataSourceId?: DataSource["id"];+ scopeInstanceId?: Instance["id"];+ dataSourceName?: DataSource["name"];+}) => {+ const before = createWebstudioDataFromBuild({ build });+ const after = createWebstudioDataFromBuild({ build });+ upsertResourceMutable({+ data: after,+ resource,+ dataSourceId,+ scopeInstanceId,+ dataSourceName,+ });+ return createWebstudioDataPatchPayload({ before, after });+};++export const createResourceCreatePayload = ({+ resourceId,+ resource: resourceInput,+ resources,+ dataSources,+ dataSourceId,+ scopeInstanceId,+ dataSourceName,+}: {+ resourceId: Resource["id"];+ resource: z.infer<typeof resourceFieldsInput>;+ resources: Iterable<Resource>;+ dataSources: Iterable<DataSource>;+ dataSourceId?: DataSource["id"];+ scopeInstanceId?: DataSource["scopeInstanceId"];+ dataSourceName?: DataSource["name"];+}): {+ payload: BuilderPatchChange[];+ dataSourceId?: DataSource["id"];+ errors: Array<+ | { type: "duplicate-resource-id"; resourceId: Resource["id"] }+ | { type: "duplicate-data-source-id"; dataSourceId: DataSource["id"] }+ >;+} => {+ const errors = [];+ if (Array.from(resources).some((resource) => resource.id === resourceId)) {+ errors.push({ type: "duplicate-resource-id" as const, resourceId });+ }+ const nextDataSourceId =+ scopeInstanceId === undefined ? undefined : dataSourceId;+ if (+ nextDataSourceId !== undefined &&+ Array.from(dataSources).some(+ (dataSource) => dataSource.id === nextDataSourceId+ )+ ) {+ errors.push({+ type: "duplicate-data-source-id" as const,+ dataSourceId: nextDataSourceId,+ });+ }+ if (errors.length > 0) {+ return { payload: [], dataSourceId: nextDataSourceId, errors };+ }++ const payload: BuilderPatchChange[] = [+ {+ namespace: "resources",+ patches: [+ {+ op: "add",+ path: [resourceId],+ value: createResourceValue({+ id: resourceId,+ name: resourceInput.name,+ control: resourceInput.control,+ method: resourceInput.method,+ url: resourceInput.url,+ searchParams: resourceInput.searchParams,+ headers: resourceInput.headers,+ body: resourceInput.body,+ }),+ },+ ],+ },+ ];+ if (nextDataSourceId !== undefined && scopeInstanceId !== undefined) {+ payload.push({+ namespace: "dataSources",+ patches: [+ {+ op: "add",+ path: [nextDataSourceId],+ value: createResourceDataSource({+ dataSourceId: nextDataSourceId,+ scopeInstanceId,+ name: dataSourceName ?? resourceInput.name,+ resourceId,+ }),+ },+ ],+ });+ }++ return { payload, dataSourceId: nextDataSourceId, errors };+};++export const createResourceUpdatePayload = ({+ resource,+ values,+ dataSources,+ dataSourceName,+ scopeInstanceId,+}: {+ resource: Resource;+ values: z.infer<typeof resourceFieldsUpdateInput>;+ dataSources: Iterable<DataSource>;+ dataSourceName?: string;+ scopeInstanceId?: string;+}): BuilderPatchChange[] => {+ const patches = Object.entries(values).flatMap(([name, value]) =>+ value === undefined+ ? []+ : [{ op: "replace" as const, path: [resource.id, name], value }]+ );+ const payload: BuilderPatchChange[] = compactBuilderPatchPayload([+ { namespace: "resources", patches },+ ]);+ const dataSource = Array.from(dataSources).find(+ (dataSource) =>+ dataSource.type === "resource" && dataSource.resourceId === resource.id+ );+ const dataSourcePatches = [];+ if (dataSource !== undefined && dataSourceName !== undefined) {+ dataSourcePatches.push({+ op: "replace" as const,+ path: [dataSource.id, "name"],+ value: dataSourceName,+ });+ }+ if (dataSource !== undefined && scopeInstanceId !== undefined) {+ dataSourcePatches.push({+ op: "replace" as const,+ path: [dataSource.id, "scopeInstanceId"],+ value: scopeInstanceId,+ });+ }+ if (dataSourcePatches.length > 0) {+ payload.push({ namespace: "dataSources", patches: dataSourcePatches });+ }+ return payload;+};++export const createResourceDeletePayload = ({+ resource,+ dataSources,+ props,+ force,+}: {+ resource: Resource;+ dataSources: Iterable<DataSource>;+ props: Iterable<Prop>;+ force?: boolean;+}): {+ payload: BuilderPatchChange[];+ dataSourceIds: DataSource["id"][];+ propIds: Prop["id"][];+ isUsed: boolean;+} => {+ const resourceProps = Array.from(props).filter(+ (prop) => prop.type === "resource" && prop.value === resource.id+ );+ if (resourceProps.length > 0 && force !== true) {+ return { payload: [], dataSourceIds: [], propIds: [], isUsed: true };+ }+ const resourceDataSources = Array.from(dataSources).filter(+ (dataSource) =>+ dataSource.type === "resource" && dataSource.resourceId === resource.id+ );+ const payload: BuilderPatchChange[] = [+ {+ namespace: "resources",+ patches: [{ op: "remove", path: [resource.id] }],+ },+ ];+ if (resourceDataSources.length > 0) {+ payload.push({+ namespace: "dataSources",+ patches: resourceDataSources.map((dataSource) => ({+ op: "remove" as const,+ path: [dataSource.id],+ })),+ });+ }+ if (resourceProps.length > 0) {+ payload.push({+ namespace: "props",+ patches: resourceProps.map((prop) => ({+ op: "remove" as const,+ path: [prop.id],+ })),+ });+ }++ return {+ payload,+ dataSourceIds: resourceDataSources.map((dataSource) => dataSource.id),+ propIds: resourceProps.map((prop) => prop.id),+ isUsed: false,+ };+};++export const serializeResources = ({+ resources,+ dataSources,+ scopeInstanceId,+}: {+ resources: Iterable<Resource> | Map<string, Resource>;+ dataSources: Iterable<DataSource> | Map<string, DataSource>;+ scopeInstanceId?: Instance["id"];+}) => {+ const dataSourceList =+ dataSources instanceof Map+ ? Array.from(dataSources.values())+ : Array.from(dataSources);+ return {+ resources: (resources instanceof Map+ ? Array.from(resources.values())+ : Array.from(resources)+ )+ .filter(+ (resource) =>+ scopeInstanceId === undefined ||+ dataSourceList.some(+ (dataSource) =>+ dataSource.type === "resource" &&+ dataSource.resourceId === resource.id &&+ dataSource.scopeInstanceId === scopeInstanceId+ )+ )+ .map((resource) => {+ const dataSource = dataSourceList.find(+ (dataSource) =>+ dataSource.type === "resource" &&+ dataSource.resourceId === resource.id &&+ (scopeInstanceId === undefined ||+ dataSource.scopeInstanceId === scopeInstanceId)+ );+ return {+ id: resource.id,+ name: resource.name,+ method: resource.method,+ url: resource.url,+ scopeInstanceId: dataSource?.scopeInstanceId,+ exposedAsDataSource: dataSource !== undefined,+ dataSourceId: dataSource?.id,+ };+ }),+ };+};++export const listResources = (+ state: Pick<BuilderState, "dataSources" | "resources">,+ input: { scopeInstanceId?: string } = {}+) => {+ return serializeResources({+ resources: getRequiredResources(state),+ dataSources: getRequiredDataSources(state),+ scopeInstanceId: input.scopeInstanceId,+ });+};++export const createResource = (+ state: Pick<+ BuilderState,+ | "pages"+ | "instances"+ | "props"+ | "dataSources"+ | "resources"+ | "breakpoints"+ | "styleSources"+ | "styleSourceSelections"+ | "styles"+ >,+ input: {+ resourceId?: string;+ resource: z.infer<typeof resourceFieldsInput>;+ dataSourceId?: string;+ scopeInstanceId?: string;+ dataSourceName?: string;+ },+ context: BuilderRuntimeContext+) => {+ const expressionErrors = getResourceExpressionErrors(input.resource);+ if (expressionErrors.length > 0) {+ return throwBuilderRuntimeError("BAD_REQUEST", expressionErrors.join("\n"));+ }+ const build = getRequiredBuildData(state);+ const resourceId = input.resourceId ?? context.createId();+ const dataSourceId =+ input.scopeInstanceId === undefined+ ? undefined+ : (input.dataSourceId ?? context.createId());+ const resultPayload = createResourceCreatePayload({+ resourceId,+ resource: input.resource,+ resources: build.resources,+ dataSources: build.dataSources,+ dataSourceId,+ scopeInstanceId: input.scopeInstanceId,+ dataSourceName: input.dataSourceName,+ });+ const error = resultPayload.errors.at(0);+ if (error?.type === "duplicate-resource-id") {+ return throwBuilderRuntimeError("CONFLICT", "Resource id already exists");+ }+ if (error?.type === "duplicate-data-source-id") {+ return throwBuilderRuntimeError(+ "CONFLICT",+ "Data source id already exists"+ );+ }+ const resource = createResourceValue({+ id: resourceId,+ name: input.resource.name,+ control: input.resource.control,+ method: input.resource.method,+ url: input.resource.url,+ searchParams: input.resource.searchParams,+ headers: input.resource.headers,+ body: input.resource.body,+ });+ return createRuntimeMutation({+ payload: createResourceUpsertPatchPayload({+ build,+ resource,+ dataSourceId,+ scopeInstanceId: input.scopeInstanceId,+ dataSourceName: input.dataSourceName,+ }),+ result: { resourceId, dataSourceId },+ invalidatesNamespaces: [+ "pages",+ "instances",+ "props",+ "dataSources",+ "resources",+ "breakpoints",+ "styleSources",+ "styleSourceSelections",+ "styles",+ ],+ });+};++export const updateResource = (+ state: Pick<+ BuilderState,+ | "pages"+ | "instances"+ | "props"+ | "dataSources"+ | "resources"+ | "breakpoints"+ | "styleSources"+ | "styleSourceSelections"+ | "styles"+ >,+ input: {+ resourceId: string;+ values: z.infer<typeof resourceFieldsUpdateInput>;+ dataSourceName?: string;+ scopeInstanceId?: string;+ }+) => {+ const expressionErrors = getResourceExpressionErrors(input.values);+ if (expressionErrors.length > 0) {+ return throwBuilderRuntimeError("BAD_REQUEST", expressionErrors.join("\n"));+ }+ const build = getRequiredBuildData(state);+ const resource = findResource(build.resources, input.resourceId);+ if (resource === undefined) {+ return throwBuilderRuntimeError("NOT_FOUND", "Resource not found");+ }+ const directPayload = createResourceUpdatePayload({+ resource,+ values: input.values,+ dataSources: build.dataSources,+ dataSourceName: input.dataSourceName,+ scopeInstanceId: input.scopeInstanceId,+ });+ if (directPayload.length === 0) {+ return createRuntimeMutation({+ payload: [],+ result: { resourceId: resource.id },+ invalidatesNamespaces: [],+ });+ }+ const nextResource = createResourceValue({+ ...resource,+ ...input.values,+ });+ const dataSource = build.dataSources.find(+ (dataSource) =>+ dataSource.type === "resource" && dataSource.resourceId === resource.id+ );+ return createRuntimeMutation({+ payload: createResourceUpsertPatchPayload({+ build,+ resource: nextResource,+ dataSourceId: dataSource?.id,+ scopeInstanceId: input.scopeInstanceId ?? dataSource?.scopeInstanceId,+ dataSourceName: input.dataSourceName ?? dataSource?.name,+ }),+ result: { resourceId: resource.id },+ invalidatesNamespaces: [+ "pages",+ "instances",+ "props",+ "dataSources",+ "resources",+ "breakpoints",+ "styleSources",+ "styleSourceSelections",+ "styles",+ ],+ });+};++export const deleteResource = (+ state: Pick<BuilderState, "dataSources" | "resources" | "props">,+ input: { resourceId: string; force?: boolean }+) => {+ const resource = findResource(+ getRequiredResources(state).values(),+ input.resourceId+ );+ if (resource === undefined) {+ return throwBuilderRuntimeError("NOT_FOUND", "Resource not found");+ }+ const resultPayload = createResourceDeletePayload({+ resource,+ dataSources: getRequiredDataSources(state).values(),+ props: getRequiredProps(state).values(),+ force: input.force,+ });+ if (resultPayload.isUsed) {+ return throwBuilderRuntimeError(+ "BAD_REQUEST",+ "Resource is used by props. Pass force to remove those prop references."+ );+ }+ return createRuntimeMutation({+ payload: resultPayload.payload,+ result: {+ resourceId: resource.id,+ dataSourceIds: resultPayload.dataSourceIds,+ propIds: resultPayload.propIds,+ },+ invalidatesNamespaces: ["resources", "dataSources", "props"],+ });+};diff --git a/packages/project-build/src/runtime/errors.test.ts b/packages/project-build/src/runtime/errors.test.tsnew file mode 100644index 0000000000..1da1c8c390--- /dev/null+++ b/packages/project-build/src/runtime/errors.test.ts@@ -0,0 +1,20 @@+import { expect, test } from "vitest";+import { BuilderRuntimeError, throwBuilderRuntimeError } from "./errors";++test("creates runtime errors with stable code and name", () => {+ const error = new BuilderRuntimeError("BAD_REQUEST", "Invalid input");++ expect(error).toBeInstanceOf(Error);+ expect(error.name).toBe("BuilderRuntimeError");+ expect(error.code).toBe("BAD_REQUEST");+ expect(error.message).toBe("Invalid input");+});++test("throws runtime errors", () => {+ expect(() => throwBuilderRuntimeError("NOT_FOUND", "Missing")).toThrow(+ BuilderRuntimeError+ );+ expect(() => throwBuilderRuntimeError("CONFLICT", "Changed")).toThrow(+ "Changed"+ );+});diff --git a/packages/project-build/src/runtime/errors.ts b/packages/project-build/src/runtime/errors.tsnew file mode 100644index 0000000000..ecddd04d79--- /dev/null+++ b/packages/project-build/src/runtime/errors.ts@@ -0,0 +1,18 @@+export type BuilderRuntimeErrorCode = "BAD_REQUEST" | "NOT_FOUND" | "CONFLICT";++export class BuilderRuntimeError extends Error {+ code: BuilderRuntimeErrorCode;++ constructor(code: BuilderRuntimeErrorCode, message: string) {+ super(message);+ this.name = "BuilderRuntimeError";+ this.code = code;+ }+}++export const throwBuilderRuntimeError = (+ code: BuilderRuntimeErrorCode,+ message: string+): never => {+ throw new BuilderRuntimeError(code, message);+};diff --git a/apps/builder/app/shared/copy-paste.test.tsx b/packages/project-build/src/runtime/fragment.test.tsxsimilarity index 97%rename from apps/builder/app/shared/copy-paste.test.tsxrename to packages/project-build/src/runtime/fragment.test.tsxindex eed63c817f..fc21636a93 100644--- a/apps/builder/app/shared/copy-paste.test.tsx+++ b/packages/project-build/src/runtime/fragment.test.tsx@@ -1,7 +1,12 @@-import { insertWebstudioFragmentCopy } from "./instance-utils/fragment";+import {+ extractWebstudioFragment,+ insertWebstudioFragmentCopy,+} from "./fragment";import { describe, expect, test } from "vitest";-import stripIndent from "strip-indent";-import { createRegularStyleSheet } from "@webstudio-is/css-engine";+import {+ createRegularStyleSheet,+ type StyleProperty,+} from "@webstudio-is/css-engine";import { createDefaultPages } from "@webstudio-is/project-build";import {encodeDataVariableId,@@ -22,13 +27,22 @@ import {renderTemplate,Parameter,} from "@webstudio-is/template";-import type { Project } from "@webstudio-is/project";-import { extractWebstudioFragment } from "./instance-utils/fragment";-import { $project } from "~/shared/sync/data-stores";-import { findAvailableVariables } from "./data-variables";-import { camelCaseProperty } from "@webstudio-is/css-data";+import { findAvailableVariables } from "./data";++const stripIndent = (value: string) => {+ const lines = value.replace(/^\n|\n\s*$/g, "").split("\n");+ const indent = Math.min(+ ...lines+ .filter((line) => line.trim() !== "")+ .map((line) => line.match(/^\s*/)?.[0].length ?? 0)+ );+ return lines.map((line) => line.slice(indent)).join("\n");+};-$project.set({ id: "current_project" } as Project);+const camelCaseProperty = (property: string): StyleProperty =>+ property.replace(/-([a-z])/g, (_match, char: string) =>+ char.toUpperCase()+ ) as StyleProperty;const createStub = (element: JSX.Element) => {const project = {diff --git a/apps/builder/app/shared/instance-utils/fragment.ts b/packages/project-build/src/runtime/fragment.tssimilarity index 90%rename from apps/builder/app/shared/instance-utils/fragment.tsrename to packages/project-build/src/runtime/fragment.tsindex fe9a6d0d31..0231234e79 100644--- a/apps/builder/app/shared/instance-utils/fragment.ts+++ b/packages/project-build/src/runtime/fragment.ts@@ -13,6 +13,7 @@ import {type Prop,type Resource,type StyleDecl,+ type WsComponentMeta,type WebstudioData,type WebstudioFragment,ROOT_INSTANCE_ID,@@ -22,28 +23,47 @@ import {getHomePage,portalComponent,} from "@webstudio-is/sdk";-import type { Project } from "@webstudio-is/project";-import {- getContentModeCapabilities,- isContentModeCopyableProp,-} from "@webstudio-is/project/content-mode-permissions";-import { buildMergedBreakpointIds, maxBreakpoints } from "../breakpoints-utils";import {replaceDataSourcesInExpression,restoreExpressionVariables,unsetExpressionVariables,-} from "../data-variables";+} from "./data";+import { cloneInstanceWithNewIds } from "./instances";+import { clonePropForInstance } from "./props";+import { buildMergedBreakpointIds, maxBreakpoints } from "./breakpoints";import {collectStyleSourcesFromInstances,detectTokenConflicts,insertLocalStyleSourcesWithNewIds,insertPortalLocalStyleSources,insertTokenStyleSources,-} from "../style-source-utils";-import type { ConflictResolution } from "../token-conflict-dialog";-import { setDifference, setUnion } from "../shim";-import { $registeredComponentMetas } from "../nano-states";-import { getWebstudioData, unwrap } from "./data";+ type ConflictResolution,+} from "./style-copy";+import { unwrap } from "./unwrap";++export type ContentModeCopyableProp = (input: {+ prop: Prop;+ fragment: WebstudioFragment;+ fragmentInstances: Instances;+ styleSources: WebstudioData["styleSources"];+ metas: Map<string, WsComponentMeta>;+}) => boolean;++const setDifference = <Item>(current: Set<Item>, other: Set<Item>) => {+ const result = new Set<Item>(current);+ for (const item of other) {+ result.delete(item);+ }+ return result;+};++const setUnion = <Item>(current: Set<Item>, other: Set<Item>) => {+ const result = new Set<Item>(current);+ for (const item of other) {+ result.add(item);+ }+ return result;+};const traverseStyleValue = (value: StyleValue,@@ -317,7 +337,7 @@ const insertFragmentAssetsMutable = ({assets,}: {fragment: WebstudioFragment;- projectId: Project["id"];+ projectId: string;assets: WebstudioData["assets"];}) => {for (const asset of fragment.assets) {@@ -360,32 +380,10 @@ const insertFragmentBreakpointsMutable = ({return mergedBreakpointIds;};-const getFragmentContentModeCapabilities = ({- fragment,- fragmentInstances,- styleSources,-}: {- fragment: WebstudioFragment;- fragmentInstances: Instances;- styleSources: WebstudioData["styleSources"];-}) =>- getContentModeCapabilities({- instances: fragmentInstances,- metas: $registeredComponentMetas.get(),- props: new Map(fragment.props.map((prop) => [prop.id, prop])),- styleSources,- contentRootIds: new Set(- fragment.children- .filter((child) => child.type === "id")- .map((child) => child.value)- ),- });-export const __testing__ = {getFragmentInstancesData,insertFragmentAssetsMutable,insertFragmentBreakpointsMutable,- getFragmentContentModeCapabilities,};export const insertWebstudioFragmentCopy = ({@@ -395,6 +393,9 @@ export const insertWebstudioFragmentCopy = ({projectId,conflictResolution = "theirs",onBreakpointLimitMerge,+ metas,+ contentModeCopyableProp,+ createId = nanoid,// In content mode, insertion keeps content-editable instance data, creates// local styles for inserted instances, and avoids data/resource records.contentMode = false,@@ -402,9 +403,12 @@ export const insertWebstudioFragmentCopy = ({data: Omit<WebstudioData, "pages">;fragment: WebstudioFragment;availableVariables: DataSource[];- projectId: Project["id"];+ projectId: string;conflictResolution?: ConflictResolution;onBreakpointLimitMerge?: () => void;+ metas?: Map<string, WsComponentMeta>;+ contentModeCopyableProp?: ContentModeCopyableProp;+ createId?: () => string;contentMode?: boolean;}) => {const newInstanceIds = new Map<Instance["id"], Instance["id"]>();@@ -468,6 +472,7 @@ export const insertWebstudioFragmentCopy = ({breakpoints,mergedBreakpointIds,conflictResolution,+ createId,});}@@ -555,7 +560,7 @@ export const insertWebstudioFragmentCopy = ({portalContentIds);for (const instanceId of fragmentInstanceIds) {- newInstanceIds.set(instanceId, nanoid());+ newInstanceIds.set(instanceId, createId());}fragmentInstanceIds.add(ROOT_INSTANCE_ID);newInstanceIds.set(ROOT_INSTANCE_ID, ROOT_INSTANCE_ID);@@ -580,14 +585,14 @@ export const insertWebstudioFragmentCopy = ({}// insert only data sources within portal contentif (fragmentInstanceIds.has(scopeInstanceId)) {- const newDataSourceId = nanoid();+ const newDataSourceId = createId();newDataSourceIds.set(dataSource.id, newDataSourceId);dataSource = structuredClone(unwrap(dataSource));dataSource.id = newDataSourceId;dataSource.scopeInstanceId =newInstanceIds.get(scopeInstanceId) ?? scopeInstanceId;if (dataSource.type === "resource") {- const newResourceId = nanoid();+ const newResourceId = createId();newResourceIds.set(dataSource.resourceId, newResourceId);dataSource.resourceId = newResourceId;}@@ -596,31 +601,28 @@ export const insertWebstudioFragmentCopy = ({}}- const fragmentContentModeCapabilities =- contentMode === false- ? undefined- : getFragmentContentModeCapabilities({- fragment,- fragmentInstances,- styleSources,- });for (let prop of fragment.props) {if (fragmentInstanceIds.has(prop.instanceId) === false) {continue;}if (contentMode &&- (fragmentContentModeCapabilities === undefined ||- isContentModeCopyableProp({- capabilities: fragmentContentModeCapabilities,- prop,- }) === false)+ contentModeCopyableProp !== undefined &&+ contentModeCopyableProp({+ prop,+ fragment,+ fragmentInstances,+ styleSources,+ metas: metas ?? new Map(),+ }) === false) {continue;}- prop = structuredClone(unwrap(prop));- prop.id = nanoid();- prop.instanceId = newInstanceIds.get(prop.instanceId) ?? prop.instanceId;+ prop = clonePropForInstance({+ prop: unwrap(prop),+ propId: createId(),+ instanceId: newInstanceIds.get(prop.instanceId) ?? prop.instanceId,+ });if (prop.type === "expression") {prop.value = restoreExpressionVariables({expression: prop.value,@@ -644,7 +646,7 @@ export const insertWebstudioFragmentCopy = ({prop.value = newDataSourceIds.get(prop.value) ?? prop.value;}if (prop.type === "resource") {- const newResourceId = nanoid();+ const newResourceId = createId();newResourceIds.set(prop.value, newResourceId);prop.value = newResourceId;}@@ -704,12 +706,11 @@ export const insertWebstudioFragmentCopy = ({for (let instance of fragment.instances) {if (fragmentInstanceIds.has(instance.id)) {- instance = structuredClone(unwrap(instance));- instance.id = newInstanceIds.get(instance.id) ?? instance.id;+ instance = cloneInstanceWithNewIds({+ instance: unwrap(instance),+ newInstanceIds,+ });for (const child of instance.children) {- if (child.type === "id") {- child.value = newInstanceIds.get(child.value) ?? child.value;- }if (child.type === "expression") {child.value = restoreExpressionVariables({expression: child.value,@@ -740,6 +741,7 @@ export const insertWebstudioFragmentCopy = ({...localStyleSourceInput,contentMode: true,breakpoints,+ createId,});} else {insertLocalStyleSourcesWithNewIds({@@ -748,6 +750,7 @@ export const insertWebstudioFragmentCopy = ({styleSourceIdMap,mergedBreakpointIds,breakpoints,+ createId,});}@@ -755,23 +758,23 @@ export const insertWebstudioFragmentCopy = ({};export const detectFragmentTokenConflicts = ({fragment,+ targetData,}: {fragment: WebstudioFragment;+ targetData: WebstudioData;}) => {- const data = getWebstudioData();-const mergedBreakpointIds = buildMergedBreakpointIds(fragment.breakpoints,- data.breakpoints,+ targetData.breakpoints,{ maxBreakpointCount: maxBreakpoints });return detectTokenConflicts({fragmentStyleSources: fragment.styleSources,fragmentStyles: fragment.styles,- existingStyleSources: data.styleSources,- existingStyles: data.styles,- breakpoints: data.breakpoints,+ existingStyleSources: targetData.styleSources,+ existingStyles: targetData.styles,+ breakpoints: targetData.breakpoints,mergedBreakpointIds,});};@@ -786,13 +789,13 @@ export const detectFragmentTokenConflicts = ({*/export const detectPageTokenConflicts = ({sourceData,+ targetData,pageId,}: {sourceData: WebstudioData;+ targetData: WebstudioData;pageId: string;}) => {- const data = getWebstudioData();-const page = findPageByIdOrPath(pageId, sourceData.pages);if (page === undefined) {throw new Error("Page not found");@@ -819,16 +822,16 @@ export const detectPageTokenConflicts = ({const mergedBreakpointIds = buildMergedBreakpointIds(combinedBreakpoints,- data.breakpoints,+ targetData.breakpoints,{ maxBreakpointCount: maxBreakpoints });return detectTokenConflicts({fragmentStyleSources: combinedStyleSources,fragmentStyles: combinedStyles,- existingStyleSources: data.styleSources,- existingStyles: data.styles,- breakpoints: data.breakpoints,+ existingStyleSources: targetData.styleSources,+ existingStyles: targetData.styles,+ breakpoints: targetData.breakpoints,mergedBreakpointIds,});};diff --git a/packages/project-build/src/runtime/instances.test.ts b/packages/project-build/src/runtime/instances.test.tsnew file mode 100644index 0000000000..e4c206dbdf--- /dev/null+++ b/packages/project-build/src/runtime/instances.test.ts@@ -0,0 +1,1038 @@+import { describe, expect, test } from "vitest";+import {+ elementComponent,+ type Instance,+ type Prop,+ type StyleDecl,+ type StyleSource,+ type StyleSourceSelection,+} from "@webstudio-is/sdk";+import {+ collectExclusiveInstanceIds,+ cloneInstanceSubtree,+ cloneInstanceWithNewIds,+ createInstanceAppendPayload,+ createInstanceChild,+ createInstanceClonePayload,+ createInstanceCleanupPayload,+ createInstanceDeletePayload,+ createInstanceMovePatches,+ createInstanceMovePayload,+ createTextContentChild,+ createTextContentResetPayload,+ createTextContentUpdatePayload,+ findChildReferenceIndex,+ findLocalStyleSourcesWithinInstances,+ findParentInstanceReference,+ findTextContentChild,+ getInstanceDepths,+ getSameParentAdjustedInsertIndex,+ getTextContentChild,+ getTextContentErrors,+ isTextContentChild,+ serializeTextNodes,+ setTextContentMutable,+} from "./instances";++const createInstance = (+ id: Instance["id"],+ componentOrChildren: string | Instance["children"] = [],+ children?: Instance["children"]+): Instance => ({+ type: "instance",+ id,+ component:+ typeof componentOrChildren === "string"+ ? componentOrChildren+ : elementComponent,+ children:+ typeof componentOrChildren === "string"+ ? (children ?? [])+ : componentOrChildren,+});++const createStyleSource = (+ type: StyleSource["type"],+ id: StyleSource["id"]+): StyleSource => {+ if (type === "token") {+ return {+ type,+ id,+ name: id,+ };+ }+ return {+ type,+ id,+ };+};++const createStyleSourceSelection = (+ instanceId: Instance["id"],+ values: StyleSource["id"][]+): StyleSourceSelection => {+ return {+ instanceId,+ values,+ };+};++test("collects root-owned instance ids without deleting shared child subtrees", () => {+ const instances = new Map<Instance["id"], Instance>([+ [+ "page-root",+ createInstance("page-root", [+ { type: "id", value: "owned-child" },+ { type: "id", value: "shared-child" },+ ]),+ ],+ ["owned-child", createInstance("owned-child")],+ [+ "other-root",+ createInstance("other-root", [{ type: "id", value: "shared-child" }]),+ ],+ [+ "shared-child",+ createInstance("shared-child", [{ type: "id", value: "shared-leaf" }]),+ ],+ ["shared-leaf", createInstance("shared-leaf")],+ ]);++ expect(collectExclusiveInstanceIds(instances, ["page-root"])).toEqual(+ new Set(["page-root", "owned-child"])+ );+});++test("collects multiple requested roots even when one root references another", () => {+ const instances = new Map<Instance["id"], Instance>([+ [+ "first-root",+ createInstance("first-root", [{ type: "id", value: "second-root" }]),+ ],+ [+ "second-root",+ createInstance("second-root", [{ type: "id", value: "child" }]),+ ],+ ["child", createInstance("child")],+ ]);++ expect(+ collectExclusiveInstanceIds(instances, ["first-root", "second-root"])+ ).toEqual(new Set(["first-root", "second-root", "child"]));+});+const createCloneInstance = (+ id: Instance["id"],+ children: Instance["children"] = []+): Instance => ({+ type: "instance",+ id,+ component: elementComponent,+ children,+});++test("creates instance clone payload with child references and props", () => {+ const targetParent = createCloneInstance("parent", []);+ const props: Prop[] = [+ {+ id: "prop",+ instanceId: "source",+ name: "className",+ type: "string",+ value: "card",+ },+ ];+ const ids = ["source-copy", "child-copy", "prop-copy"];++ const result = createInstanceClonePayload({+ instances: new Map([+ [+ "source",+ createCloneInstance("source", [+ { type: "id", value: "child" },+ { type: "text", value: "Text" },+ ]),+ ],+ ["child", createCloneInstance("child")],+ [targetParent.id, targetParent],+ ]),+ sourceInstanceId: "source",+ targetParent,+ insertIndex: 0,+ props,+ styleSourceSelections: [],+ styleSources: [],+ styles: new Map(),+ createId: () => ids.shift() ?? "missing",+ });++ expect(result).toEqual({+ clonedRootId: "source-copy",+ clonedInstanceIds: ["source-copy", "child-copy"],+ payload: [+ {+ namespace: "instances",+ patches: [+ {+ op: "add",+ path: ["source-copy"],+ value: createCloneInstance("source-copy", [+ { type: "id", value: "child-copy" },+ { type: "text", value: "Text" },+ ]),+ },+ {+ op: "add",+ path: ["child-copy"],+ value: createCloneInstance("child-copy"),+ },+ {+ op: "add",+ path: ["parent", "children", 0],+ value: { type: "id", value: "source-copy" },+ },+ ],+ },+ {+ namespace: "props",+ patches: [+ {+ op: "add",+ path: [expect.any(String)],+ value: {+ ...props[0],+ id: expect.any(String),+ instanceId: "source-copy",+ },+ },+ ],+ },+ ],+ });+});+describe("text content utils", () => {+ test("creates text and expression children", () => {+ expect(createTextContentChild({ type: "text", value: "Hello" })).toEqual({+ type: "text",+ value: "Hello",+ });+ expect(+ createTextContentChild({ type: "expression", value: "title" })+ ).toEqual({+ type: "expression",+ value: "title",+ });+ });++ test("validates only expression children", () => {+ expect(+ getTextContentErrors({ type: "text", value: "invalid expression {" })+ ).toEqual([]);+ expect(+ getTextContentErrors({ type: "expression", value: "invalid {" })+ ).not.toEqual([]);+ });++ test("detects text content children", () => {+ expect(isTextContentChild({ type: "text", value: "Hello" })).toBe(true);+ expect(isTextContentChild({ type: "expression", value: "title" })).toBe(+ true+ );+ expect(isTextContentChild({ type: "id", value: "child" })).toBe(false);+ expect(isTextContentChild(undefined)).toBe(false);+ });++ test("gets text content child by index", () => {+ const instance: Instance = {+ type: "instance",+ id: "instance",+ component: "Text",+ children: [+ { type: "id", value: "child" },+ { type: "text", value: "Hello" },+ ],+ };++ expect(getTextContentChild(instance, 0)).toBeUndefined();+ expect(getTextContentChild(instance, 1)).toEqual({+ type: "text",+ value: "Hello",+ });+ });++ test("finds text content children with explicit status", () => {+ const instances: Instance[] = [+ {+ type: "instance",+ id: "instance",+ component: "Text",+ children: [+ { type: "id", value: "child" },+ { type: "text", value: "Hello" },+ ],+ },+ ];++ expect(+ findTextContentChild(instances, {+ instanceId: "instance",+ childIndex: 1,+ mode: "text",+ })+ ).toEqual({+ status: "found",+ child: { type: "text", value: "Hello" },+ });+ expect(+ findTextContentChild(instances, {+ instanceId: "missing",+ childIndex: 1,+ })+ ).toEqual({ status: "instance-not-found" });+ expect(+ findTextContentChild(instances, {+ instanceId: "instance",+ childIndex: 2,+ })+ ).toEqual({ status: "child-not-found" });+ expect(+ findTextContentChild(instances, {+ instanceId: "instance",+ childIndex: 0,+ })+ ).toEqual({ status: "not-text-content" });+ expect(+ findTextContentChild(instances, {+ instanceId: "instance",+ childIndex: 1,+ mode: "expression",+ })+ ).toEqual({ status: "mode-mismatch", actual: "text" });+ });++ test("replaces instance children with a single text content child", () => {+ const instance: Instance = {+ type: "instance",+ id: "instance",+ component: "Text",+ children: [{ type: "text", value: "old" }],+ };++ setTextContentMutable(instance, "expression", "value");++ expect(instance.children).toEqual([{ type: "expression", value: "value" }]);+ });++ test("creates text content update payload", () => {+ expect(+ createTextContentUpdatePayload({+ instanceId: "instance",+ childIndex: 1,+ child: { type: "text", value: "Hello" },+ })+ ).toEqual([+ {+ namespace: "instances",+ patches: [+ {+ op: "replace",+ path: ["instance", "children", 1],+ value: { type: "text", value: "Hello" },+ },+ ],+ },+ ]);+ });++ test("creates text content reset payload", () => {+ expect(createTextContentResetPayload({ instanceId: "instance" })).toEqual([+ {+ namespace: "instances",+ patches: [+ {+ op: "replace",+ path: ["instance", "children"],+ value: [],+ },+ ],+ },+ ]);+ });++ test("serializes text and expression children with filters", () => {+ const instances: Instance[] = [+ {+ type: "instance",+ id: "root",+ component: "Body",+ children: [+ { type: "text", value: "Hello world" },+ { type: "id", value: "child" },+ ],+ },+ {+ type: "instance",+ id: "child",+ component: "Text",+ label: "Label",+ children: [{ type: "expression", value: "greeting" }],+ },+ {+ type: "instance",+ id: "outside",+ component: "Text",+ children: [{ type: "text", value: "Outside" }],+ },+ ];++ expect(+ serializeTextNodes({+ instances,+ rootInstanceIds: new Set(["root", "child"]),+ mode: "all",+ maxValueLength: 5,+ })+ ).toEqual([+ {+ instanceId: "root",+ childIndex: 0,+ component: "Body",+ label: undefined,+ mode: "text",+ value: "Hello",+ },+ {+ instanceId: "child",+ childIndex: 0,+ component: "Text",+ label: "Label",+ mode: "expression",+ value: "greet",+ },+ ]);++ expect(+ serializeTextNodes({+ instances,+ instanceId: "root",+ mode: "text",+ contains: "world",+ })+ ).toEqual([+ {+ instanceId: "root",+ childIndex: 0,+ component: "Body",+ label: undefined,+ mode: "text",+ value: "Hello world",+ },+ ]);+ });+});++test("clone instance with mapped id children", () => {+ expect(+ cloneInstanceWithNewIds({+ instance: {+ type: "instance",+ id: "source",+ component: elementComponent,+ children: [+ { type: "id", value: "child" },+ { type: "text", value: "Text" },+ { type: "expression", value: "value" },+ ],+ },+ newInstanceIds: new Map([+ ["source", "clone"],+ ["child", "child-clone"],+ ]),+ })+ ).toEqual({+ type: "instance",+ id: "clone",+ component: elementComponent,+ children: [+ { type: "id", value: "child-clone" },+ { type: "text", value: "Text" },+ { type: "expression", value: "value" },+ ],+ });+});++test("clones an instance subtree with new ids", () => {+ const instances = new Map([+ [+ "root",+ createInstance("root", elementComponent, [+ { type: "id", value: "child" },+ { type: "text", value: "Text" },+ ]),+ ],+ ["child", createInstance("child", elementComponent)],+ ]);+ const ids = ["root-copy", "child-copy"];++ expect(+ cloneInstanceSubtree({+ instances,+ rootInstanceId: "root",+ createId: () => ids.shift() ?? "missing",+ })+ ).toEqual({+ instanceIds: ["root", "child"],+ nextIdById: new Map([+ ["root", "root-copy"],+ ["child", "child-copy"],+ ]),+ clonedInstances: [+ [+ "root-copy",+ createInstance("root-copy", elementComponent, [+ { type: "id", value: "child-copy" },+ { type: "text", value: "Text" },+ ]),+ ],+ ["child-copy", createInstance("child-copy", elementComponent)],+ ],+ });+});++test("find local style sources within instances", () => {+ const instanceIds = new Set(["instance2", "instance4"]);+ const styleSources = [+ createStyleSource("local", "local1"),+ createStyleSource("local", "local2"),+ createStyleSource("token", "token3"),+ createStyleSource("local", "local4"),+ createStyleSource("token", "token5"),+ createStyleSource("local", "local6"),+ ];+ const styleSourceSelections = [+ createStyleSourceSelection("instance1", ["local1"]),+ createStyleSourceSelection("instance2", ["local2"]),+ createStyleSourceSelection("instance3", ["token3"]),+ createStyleSourceSelection("instance4", ["local4", "token5"]),+ createStyleSourceSelection("instance5", ["local6"]),+ ];+ expect(+ findLocalStyleSourcesWithinInstances(+ styleSources,+ styleSourceSelections,+ instanceIds+ )+ ).toEqual(new Set(["local2", "local4"]));+});++test("gets instance depths from root ids", () => {+ const instances = new Map([+ [+ "root",+ createInstance("root", elementComponent, [+ { type: "id", value: "child" },+ ]),+ ],+ ["child", createInstance("child", elementComponent)],+ ]);++ expect(getInstanceDepths(instances, ["root"])).toEqual(+ new Map([+ ["root", 0],+ ["child", 1],+ ])+ );+});++test("finds child reference index", () => {+ expect(+ findChildReferenceIndex(+ [+ { type: "text", value: "before" },+ { type: "id", value: "child" },+ { type: "text", value: "after" },+ ],+ "child"+ )+ ).toBe(1);+ expect(+ findChildReferenceIndex([{ type: "text", value: "only" }], "child")+ ).toBe(-1);+});++test("creates instance child references", () => {+ expect(createInstanceChild("child")).toEqual({ type: "id", value: "child" });+});++test("adjusts same-parent insert index after removal", () => {+ expect(+ getSameParentAdjustedInsertIndex({+ currentIndex: 1,+ requestedIndex: 3,+ })+ ).toBe(2);+ expect(+ getSameParentAdjustedInsertIndex({+ currentIndex: 3,+ requestedIndex: 1,+ })+ ).toBe(1);+});++test("finds parent instance reference", () => {+ const instances = new Map([+ [+ "parent",+ createInstance("parent", elementComponent, [+ { type: "text", value: "before" },+ { type: "id", value: "child" },+ ]),+ ],+ ["child", createInstance("child", elementComponent)],+ ]);++ expect(findParentInstanceReference(instances, "child")).toEqual({+ instance: instances.get("parent"),+ childIndex: 1,+ });+ expect(findParentInstanceReference(instances, "missing")).toBeUndefined();+});++test("creates instance move patches", () => {+ const instances = new Map([+ [+ "parent",+ createInstance("parent", elementComponent, [+ { type: "id", value: "a" },+ { type: "id", value: "b" },+ ]),+ ],+ ["a", createInstance("a", elementComponent)],+ ["b", createInstance("b", elementComponent)],+ ["target", createInstance("target", elementComponent)],+ ]);++ expect(+ createInstanceMovePatches({+ instances,+ moves: [{ instanceId: "a", parentInstanceId: "target" }],+ })+ ).toEqual({+ errors: [],+ patches: [+ { op: "remove", path: ["parent", "children", 0] },+ {+ op: "add",+ path: ["target", "children", 0],+ value: { type: "id", value: "a" },+ },+ ],+ });+});++test("creates instance move payload", () => {+ const instances = new Map([+ [+ "parent",+ createInstance("parent", elementComponent, [{ type: "id", value: "a" }]),+ ],+ ["a", createInstance("a", elementComponent)],+ ["target", createInstance("target", elementComponent)],+ ]);++ expect(+ createInstanceMovePayload({+ instances,+ moves: [{ instanceId: "a", parentInstanceId: "target" }],+ })+ ).toEqual({+ errors: [],+ payload: [+ {+ namespace: "instances",+ patches: [+ { op: "remove", path: ["parent", "children", 0] },+ {+ op: "add",+ path: ["target", "children", 0],+ value: { type: "id", value: "a" },+ },+ ],+ },+ ],+ });+});++test("adjusts same-parent move insert indexes", () => {+ const instances = new Map([+ [+ "parent",+ createInstance("parent", elementComponent, [+ { type: "id", value: "a" },+ { type: "id", value: "b" },+ { type: "id", value: "c" },+ ]),+ ],+ ["a", createInstance("a", elementComponent)],+ ["b", createInstance("b", elementComponent)],+ ["c", createInstance("c", elementComponent)],+ ]);++ expect(+ createInstanceMovePatches({+ instances,+ moves: [{ instanceId: "a", parentInstanceId: "parent", insertIndex: 3 }],+ }).patches+ ).toEqual([+ { op: "remove", path: ["parent", "children", 0] },+ {+ op: "add",+ path: ["parent", "children", 2],+ value: { type: "id", value: "a" },+ },+ ]);+});++test("reports invalid instance moves", () => {+ const instances = new Map([+ [+ "parent",+ createInstance("parent", elementComponent, [+ { type: "id", value: "child" },+ ]),+ ],+ [+ "child",+ createInstance("child", elementComponent, [+ { type: "id", value: "leaf" },+ ]),+ ],+ ["leaf", createInstance("leaf", elementComponent)],+ ]);++ expect(+ createInstanceMovePatches({+ instances,+ moves: [+ { instanceId: "missing", parentInstanceId: "parent" },+ { instanceId: "child", parentInstanceId: "leaf" },+ { instanceId: "child", parentInstanceId: "parent", insertIndex: 2 },+ ],+ }).errors+ ).toEqual([+ { type: "instance-not-found", instanceId: "missing" },+ { type: "descendant-target", instanceId: "child" },+ { type: "insert-index-outside-parent", parentInstanceId: "parent" },+ ]);+});++test("creates instance delete payload with cleanup", () => {+ const instances = new Map([+ [+ "parent",+ createInstance("parent", elementComponent, [+ { type: "id", value: "child" },+ ]),+ ],+ [+ "child",+ createInstance("child", elementComponent, [+ { type: "id", value: "leaf" },+ ]),+ ],+ ["leaf", createInstance("leaf", elementComponent)],+ ]);+ const result = createInstanceDeletePayload({+ instances,+ instanceIds: ["child"],+ props: [],+ dataSources: [],+ styleSources: [],+ styleSourceSelections: [],+ styles: [],+ });++ expect(result.errors).toEqual([]);+ expect(result.instanceIds).toEqual(["child", "leaf"]);+ expect(result.payload[0]).toEqual({+ namespace: "instances",+ patches: [+ { op: "remove", path: ["parent", "children", 0] },+ { op: "remove", path: ["child"] },+ { op: "remove", path: ["leaf"] },+ ],+ });+ expect(result.payload.every(({ patches }) => patches.length > 0)).toBe(true);+});++test("omits empty instance cleanup namespaces", () => {+ expect(+ createInstanceDeletePayload({+ instances: new Map([+ [+ "root",+ createInstance("root", elementComponent, [+ { type: "id", value: "child" },+ ]),+ ],+ ["child", createInstance("child", elementComponent)],+ ]),+ instanceIds: ["child"],+ props: [],+ dataSources: [],+ styleSources: [],+ styleSourceSelections: [],+ styles: [],+ }).payload+ ).toEqual([+ {+ namespace: "instances",+ patches: [+ { op: "remove", path: ["root", "children", 0] },+ { op: "remove", path: ["child"] },+ ],+ },+ ]);+});++test("creates instance append payload", () => {+ const parent = createInstance("parent", elementComponent);+ const created = createInstance("created", elementComponent);+ const instances = new Map([["parent", parent]]);++ expect(+ createInstanceAppendPayload({+ parent,+ instances,+ createdInstances: [created],+ insertIndex: 0,+ mode: "append",+ props: [],+ dataSources: [],+ styleSources: [],+ styleSourceSelections: [],+ styles: [],+ })+ ).toEqual({+ replacedInstanceIds: [],+ payload: [+ {+ namespace: "instances",+ patches: [+ { op: "add", path: ["created"], value: created },+ {+ op: "add",+ path: ["parent", "children", 0],+ value: { type: "id", value: "created" },+ },+ ],+ },+ ],+ });+});++test("creates instance replace payload with cleanup", () => {+ const parent = createInstance("parent", elementComponent, [+ { type: "id", value: "old" },+ { type: "text", value: "keep text cleanup only removes ids" },+ ]);+ const old = createInstance("old", elementComponent, [+ { type: "id", value: "leaf" },+ ]);+ const leaf = createInstance("leaf", elementComponent);+ const created = createInstance("created", elementComponent);+ const instances = new Map([+ ["parent", parent],+ ["old", old],+ ["leaf", leaf],+ ]);++ expect(+ createInstanceAppendPayload({+ parent,+ instances,+ createdInstances: [created],+ insertIndex: 0,+ mode: "replace",+ props: [],+ dataSources: [],+ styleSources: [],+ styleSourceSelections: [],+ styles: [],+ })+ ).toEqual({+ replacedInstanceIds: ["old", "leaf"],+ payload: [+ {+ namespace: "instances",+ patches: [+ { op: "remove", path: ["parent", "children", 1] },+ { op: "remove", path: ["parent", "children", 0] },+ { op: "add", path: ["created"], value: created },+ {+ op: "add",+ path: ["parent", "children", 0],+ value: { type: "id", value: "created" },+ },+ { op: "remove", path: ["old"] },+ { op: "remove", path: ["leaf"] },+ ],+ },+ ],+ });+});++test("reports invalid instance deletes", () => {+ const instances = new Map([+ ["root", createInstance("root", elementComponent)],+ ]);++ expect(+ createInstanceDeletePayload({+ instances,+ instanceIds: ["root", "missing"],+ pageRootIds: new Set(["root"]),+ props: [],+ dataSources: [],+ styleSources: [],+ styleSourceSelections: [],+ styles: [],+ }).errors+ ).toEqual([+ { type: "page-root", instanceId: "root" },+ { type: "instance-not-found", instanceId: "missing" },+ ]);+});++test("cleans local styles and scoped data when removing instances", () => {+ const styleDecl: StyleDecl = {+ styleSourceId: "local-1",+ breakpointId: "base",+ property: "color",+ value: { type: "keyword", value: "red" },+ };+ const props: Prop[] = [+ {+ id: "prop-1",+ instanceId: "child-1",+ name: "title",+ type: "string",+ value: "Title",+ },+ {+ id: "resource-prop",+ instanceId: "child-1",+ name: "data",+ type: "resource",+ value: "prop-resource",+ },+ ];+ const styles: StyleDecl[] = [+ styleDecl,+ {+ styleSourceId: "token-1",+ breakpointId: "base",+ property: "fontSize",+ value: { type: "unit", value: 16, unit: "px" },+ },+ ];++ expect(+ createInstanceCleanupPayload({+ instanceIds: new Set(["child-1"]),+ props,+ dataSources: [+ {+ id: "variable-1",+ type: "variable",+ scopeInstanceId: "child-1",+ name: "Value",+ value: { type: "string", value: "text" },+ },+ {+ id: "resource-variable",+ type: "resource",+ scopeInstanceId: "child-1",+ name: "Resource",+ resourceId: "variable-resource",+ },+ ],+ styleSources: [+ { type: "local", id: "local-1" },+ { type: "token", id: "token-1", name: "Token" },+ ],+ styleSourceSelections: [+ { instanceId: "child-1", values: ["token-1", "local-1"] },+ ],+ styles,+ })+ ).toEqual([+ {+ namespace: "instances",+ patches: [{ op: "remove", path: ["child-1"] }],+ },+ {+ namespace: "props",+ patches: [+ { op: "remove", path: ["prop-1"] },+ { op: "remove", path: ["resource-prop"] },+ ],+ },+ {+ namespace: "dataSources",+ patches: [+ { op: "remove", path: ["variable-1"] },+ { op: "remove", path: ["resource-variable"] },+ ],+ },+ {+ namespace: "resources",+ patches: [+ { op: "remove", path: ["prop-resource"] },+ { op: "remove", path: ["variable-resource"] },+ ],+ },+ {+ namespace: "styleSourceSelections",+ patches: [{ op: "remove", path: ["child-1"] }],+ },+ {+ namespace: "styleSources",+ patches: [{ op: "remove", path: ["local-1"] }],+ },+ {+ namespace: "styles",+ patches: [{ op: "remove", path: ["local-1:base:color:"] }],+ },+ ]);+});++test("gets instance depths from roots", () => {+ const instances = new Map([+ [+ "root",+ createInstance("root", elementComponent, [+ { type: "id", value: "child" },+ { type: "id", value: "sibling" },+ ]),+ ],+ [+ "child",+ createInstance("child", elementComponent, [+ { type: "id", value: "leaf" },+ ]),+ ],+ ["sibling", createInstance("sibling", elementComponent)],+ ["leaf", createInstance("leaf", elementComponent)],+ ["other-root", createInstance("other-root", elementComponent)],+ ]);++ expect(getInstanceDepths(instances, ["root"])).toEqual(+ new Map([+ ["root", 0],+ ["child", 1],+ ["leaf", 2],+ ["sibling", 1],+ ])+ );+});diff --git a/packages/project-build/src/runtime/instances.ts b/packages/project-build/src/runtime/instances.tsnew file mode 100644index 0000000000..31a70605f2--- /dev/null+++ b/packages/project-build/src/runtime/instances.ts@@ -0,0 +1,1383 @@+import {+ elementComponent,+ getStyleDeclKey,+ lintExpression,+ type DataSource,+ type Instance,+ type Instances,+ type Prop,+ type StyleDecl,+ type StyleSource,+ type StyleSourceSelection,+} from "@webstudio-is/sdk";+import {+ compactBuilderPatchPayload,+ type BuilderPatchChange,+} from "../contracts/patch";+import type { BuilderState } from "../state/builder-state";+import type { BuilderRuntimeContext } from "./context";+import { throwBuilderRuntimeError } from "./errors";+import { createRuntimeMutation } from "./mutation";+import { findSerializedPageByInput, getSerializedPages } from "./pages";+import { createPropClonePatches } from "./props";+import {+ createStyleClonePayload,+ serializeStyleDeclarations,+} from "./style-utils";++export type TextContentChild = Extract<+ Instance["children"][number],+ { type: "text" | "expression" }+>;++const getRequiredInstances = (+ state: Pick<BuilderState, "instances">+): Instances => {+ if (state.instances === undefined) {+ return throwBuilderRuntimeError(+ "BAD_REQUEST",+ "Instances namespace is missing"+ );+ }+ return state.instances;+};++export const findChildReferenceIndex = (+ children: Instance["children"],+ instanceId: Instance["id"]+) =>+ children.findIndex(+ (child) => child.type === "id" && child.value === instanceId+ );++export const createInstanceChild = (instanceId: Instance["id"]) =>+ ({ type: "id", value: instanceId }) as const;++export const getSameParentAdjustedInsertIndex = ({+ currentIndex,+ requestedIndex,+}: {+ currentIndex: number;+ requestedIndex: number;+}) => (requestedIndex > currentIndex ? requestedIndex - 1 : requestedIndex);++export const findParentInstanceReference = (+ instances: Instances,+ instanceId: Instance["id"]+) => {+ for (const instance of instances.values()) {+ const childIndex = findChildReferenceIndex(instance.children, instanceId);+ if (childIndex !== -1) {+ return { instance, childIndex };+ }+ }+};++export const getInstanceDepths = (+ instances: Pick<Instances, "get" | "values">,+ rootInstanceIds?: Instance["id"][]+) => {+ const depths = new Map<Instance["id"], number>();+ const visit = (instanceId: Instance["id"], depth: number) => {+ if (depths.has(instanceId)) {+ return;+ }+ const instance = instances.get(instanceId);+ if (instance === undefined) {+ return;+ }+ depths.set(instanceId, depth);+ for (const child of instance.children) {+ if (child.type === "id") {+ visit(child.value, depth + 1);+ }+ }+ };++ const roots =+ rootInstanceIds ??+ Array.from(instances.values(), (instance) => instance.id);+ for (const root of roots) {+ visit(root, 0);+ }+ return depths;+};++export const getBuildInstanceDepths = (+ state: Pick<BuilderState, "instances" | "pages">,+ rootInstanceIds?: Instance["id"][]+) => {+ const instances = getRequiredInstances(state);+ const roots =+ rootInstanceIds ??+ (state.pages === undefined+ ? undefined+ : Array.from(state.pages.pages.values()).map(+ (page) => page.rootInstanceId+ ));+ return getInstanceDepths(instances, roots);+};++export const collectInstanceIds = (+ instances: Map<Instance["id"], Instance>,+ rootInstanceId: Instance["id"]+) => Array.from(getInstanceDepths(instances, [rootInstanceId]).keys());++export const collectExclusiveInstanceIds = (+ instances: Map<Instance["id"], Instance>,+ rootInstanceIds: Iterable<Instance["id"]>+) => {+ const roots = new Set(rootInstanceIds);+ const referenceCounts = new Map<Instance["id"], number>();+ for (const instance of instances.values()) {+ for (const child of instance.children) {+ if (child.type !== "id") {+ continue;+ }+ referenceCounts.set(+ child.value,+ (referenceCounts.get(child.value) ?? 0) + 1+ );+ }+ }+ const instanceIds = new Set<Instance["id"]>();+ const visit = (instanceId: Instance["id"]) => {+ if (instanceIds.has(instanceId)) {+ return;+ }+ const instance = instances.get(instanceId);+ if (instance === undefined) {+ return;+ }+ instanceIds.add(instanceId);+ for (const child of instance.children) {+ if (child.type !== "id") {+ continue;+ }+ if (+ roots.has(child.value) === false &&+ (referenceCounts.get(child.value) ?? 0) > 1+ ) {+ continue;+ }+ visit(child.value);+ }+ };+ for (const rootInstanceId of roots) {+ visit(rootInstanceId);+ }+ return instanceIds;+};++export const cloneInstanceWithNewIds = ({+ instance,+ newInstanceIds,+}: {+ instance: Instance;+ newInstanceIds: Map<Instance["id"], Instance["id"]>;+}): Instance => ({+ ...instance,+ id: newInstanceIds.get(instance.id) ?? instance.id,+ children: instance.children.map((child) =>+ child.type === "id"+ ? { ...child, value: newInstanceIds.get(child.value) ?? child.value }+ : child+ ),+});++export const cloneInstanceSubtree = ({+ instances,+ rootInstanceId,+ createId,+}: {+ instances: Map<Instance["id"], Instance>;+ rootInstanceId: Instance["id"];+ createId: () => Instance["id"];+}) => {+ const instanceIds = collectInstanceIds(instances, rootInstanceId);+ const nextIdById = new Map(instanceIds.map((id) => [id, createId()]));+ const clonedInstances = instanceIds.flatMap((instanceId) => {+ const instance = instances.get(instanceId);+ const nextId = nextIdById.get(instanceId);+ if (instance === undefined || nextId === undefined) {+ return [];+ }+ return [+ [+ nextId,+ cloneInstanceWithNewIds({ instance, newInstanceIds: nextIdById }),+ ] satisfies [string, Instance],+ ];+ });+ return { clonedInstances, instanceIds, nextIdById };+};++export const findLocalStyleSourcesWithinInstances = (+ styleSources: Iterable<StyleSource>,+ styleSourceSelections: Iterable<StyleSourceSelection>,+ instanceIds: Set<Instance["id"]>+) => {+ const localStyleSourceIds = new Set<StyleSource["id"]>();+ for (const styleSource of styleSources) {+ if (styleSource.type === "local") {+ localStyleSourceIds.add(styleSource.id);+ }+ }++ const subtreeLocalStyleSourceIds = new Set<StyleSource["id"]>();+ for (const { instanceId, values } of styleSourceSelections) {+ if (instanceIds.has(instanceId) === false) {+ continue;+ }+ for (const styleSourceId of values) {+ if (localStyleSourceIds.has(styleSourceId)) {+ subtreeLocalStyleSourceIds.add(styleSourceId);+ }+ }+ }++ return subtreeLocalStyleSourceIds;+};++export const getInstanceDeleteTargets = ({+ instanceIds,+ props,+ dataSources,+ styleSources,+ styleSourceSelections,+}: {+ instanceIds: Set<Instance["id"]>;+ props: Iterable<Prop>;+ dataSources: Iterable<DataSource>;+ styleSources: Iterable<StyleSource>;+ styleSourceSelections: Iterable<StyleSourceSelection>;+}) => {+ const propIds = new Set<Prop["id"]>();+ const dataSourceIds = new Set<DataSource["id"]>();+ const resourceIds = new Set<string>();+ const styleSourceSelectionInstanceIds = new Set<Instance["id"]>();+ const localStyleSourceIds = findLocalStyleSourcesWithinInstances(+ styleSources,+ styleSourceSelections,+ instanceIds+ );++ for (const prop of props) {+ if (instanceIds.has(prop.instanceId) === false) {+ continue;+ }+ propIds.add(prop.id);+ if (prop.type === "resource") {+ resourceIds.add(prop.value);+ }+ }++ for (const dataSource of dataSources) {+ if (instanceIds.has(dataSource.scopeInstanceId ?? "") === false) {+ continue;+ }+ dataSourceIds.add(dataSource.id);+ if (dataSource.type === "resource") {+ resourceIds.add(dataSource.resourceId);+ }+ }++ for (const styleSourceSelection of styleSourceSelections) {+ if (instanceIds.has(styleSourceSelection.instanceId)) {+ styleSourceSelectionInstanceIds.add(styleSourceSelection.instanceId);+ }+ }++ return {+ instanceIds,+ propIds,+ dataSourceIds,+ resourceIds,+ styleSourceSelectionInstanceIds,+ localStyleSourceIds,+ };+};++const createRemovePatches = (ids: Iterable<string>) =>+ Array.from(ids, (id) => ({ op: "remove" as const, path: [id] }));++const sortChildRemovalPatches = <+ Patch extends {+ path: [string, "children", number];+ },+>(+ patches: Patch[]+) =>+ patches.sort((left, right) => {+ const parentOrder = left.path[0].localeCompare(right.path[0]);+ return parentOrder === 0 ? right.path[2] - left.path[2] : parentOrder;+ });++export const createInstanceCleanupPayload = ({+ instanceIds,+ props,+ dataSources,+ styleSources,+ styleSourceSelections,+ styles,+}: {+ instanceIds: Set<Instance["id"]>;+ props: Iterable<Prop>;+ dataSources: Iterable<DataSource>;+ styleSources: Iterable<StyleSource>;+ styleSourceSelections: Iterable<StyleSourceSelection>;+ styles: Iterable<StyleDecl>;+}): BuilderPatchChange[] => {+ const deleteTargets = getInstanceDeleteTargets({+ instanceIds,+ props,+ dataSources,+ styleSources,+ styleSourceSelections,+ });++ return compactBuilderPatchPayload([+ {+ namespace: "instances",+ patches: createRemovePatches(deleteTargets.instanceIds),+ },+ {+ namespace: "props",+ patches: createRemovePatches(deleteTargets.propIds),+ },+ {+ namespace: "dataSources",+ patches: createRemovePatches(deleteTargets.dataSourceIds),+ },+ {+ namespace: "resources",+ patches: createRemovePatches(deleteTargets.resourceIds),+ },+ {+ namespace: "styleSourceSelections",+ patches: createRemovePatches(+ deleteTargets.styleSourceSelectionInstanceIds+ ),+ },+ {+ namespace: "styleSources",+ patches: createRemovePatches(deleteTargets.localStyleSourceIds),+ },+ {+ namespace: "styles",+ patches: Array.from(styles)+ .filter((styleDecl) =>+ deleteTargets.localStyleSourceIds.has(styleDecl.styleSourceId)+ )+ .map((styleDecl) => ({+ op: "remove" as const,+ path: [getStyleDeclKey(styleDecl)],+ })),+ },+ ]);+};++export const createInstanceMovePatches = ({+ instances,+ moves,+}: {+ instances: Instances;+ moves: Array<{+ instanceId: Instance["id"];+ parentInstanceId: Instance["id"];+ insertIndex?: number;+ }>;+}) => {+ const removalPatches = [];+ const addPatches = [];+ const errors: Array<+ | { type: "instance-not-found"; instanceId: Instance["id"] }+ | { type: "parent-not-found"; instanceId: Instance["id"] }+ | { type: "target-parent-not-found"; parentInstanceId: Instance["id"] }+ | { type: "descendant-target"; instanceId: Instance["id"] }+ | { type: "insert-index-outside-parent"; parentInstanceId: Instance["id"] }+ > = [];++ for (const move of moves) {+ const instance = instances.get(move.instanceId);+ if (instance === undefined) {+ errors.push({ type: "instance-not-found", instanceId: move.instanceId });+ continue;+ }+ const parent = findParentInstanceReference(instances, instance.id);+ if (parent === undefined) {+ errors.push({ type: "parent-not-found", instanceId: instance.id });+ continue;+ }+ const nextParent = instances.get(move.parentInstanceId);+ if (nextParent === undefined) {+ errors.push({+ type: "target-parent-not-found",+ parentInstanceId: move.parentInstanceId,+ });+ continue;+ }+ const descendantIds = collectInstanceIds(instances, instance.id);+ if (descendantIds.includes(nextParent.id)) {+ errors.push({ type: "descendant-target", instanceId: instance.id });+ continue;+ }+ const requestedInsertIndex = move.insertIndex ?? nextParent.children.length;+ if (requestedInsertIndex > nextParent.children.length) {+ errors.push({+ type: "insert-index-outside-parent",+ parentInstanceId: nextParent.id,+ });+ continue;+ }+ const insertIndex =+ parent.instance.id === nextParent.id &&+ requestedInsertIndex > parent.childIndex+ ? getSameParentAdjustedInsertIndex({+ currentIndex: parent.childIndex,+ requestedIndex: requestedInsertIndex,+ })+ : requestedInsertIndex;+ removalPatches.push({+ op: "remove" as const,+ path: [parent.instance.id, "children", parent.childIndex] as [+ string,+ "children",+ number,+ ],+ });+ addPatches.push({+ op: "add" as const,+ path: [nextParent.id, "children", insertIndex],+ value: createInstanceChild(instance.id),+ });+ }++ return {+ errors,+ patches: [...sortChildRemovalPatches(removalPatches), ...addPatches],+ };+};++export const createInstanceMovePayload = (+ input: Parameters<typeof createInstanceMovePatches>[0]+) => {+ const { errors, patches } = createInstanceMovePatches(input);+ return {+ errors,+ payload: compactBuilderPatchPayload([{ namespace: "instances", patches }]),+ };+};++export const createInstanceAppendPayload = ({+ parent,+ instances,+ createdInstances,+ insertIndex,+ mode,+ props,+ dataSources,+ styleSources,+ styleSourceSelections,+ styles,+}: {+ parent: Instance;+ instances: Instances;+ createdInstances: Instance[];+ insertIndex: number;+ mode: "append" | "prepend" | "replace";+ props: Iterable<Prop>;+ dataSources: Iterable<DataSource>;+ styleSources: Iterable<StyleSource>;+ styleSourceSelections: Iterable<StyleSourceSelection>;+ styles: Iterable<StyleDecl>;+}) => {+ const replacedInstanceIds =+ mode === "replace"+ ? new Set(+ parent.children.flatMap((child) =>+ child.type === "id"+ ? collectInstanceIds(instances, child.value)+ : []+ )+ )+ : new Set<Instance["id"]>();+ const payload: BuilderPatchChange[] = [+ {+ namespace: "instances",+ patches: [+ ...(mode === "replace"+ ? sortChildRemovalPatches(+ parent.children.map((_child, index) => ({+ op: "remove" as const,+ path: [parent.id, "children", index] as [+ string,+ "children",+ number,+ ],+ }))+ )+ : []),+ ...createdInstances.map((instance) => ({+ op: "add" as const,+ path: [instance.id],+ value: instance,+ })),+ ...createdInstances.map((instance, index) => ({+ op: "add" as const,+ path: [parent.id, "children", insertIndex + index],+ value: createInstanceChild(instance.id),+ })),+ ],+ },+ ];+ if (replacedInstanceIds.size > 0) {+ const [instanceCleanup, ...cleanupPayload] = createInstanceCleanupPayload({+ instanceIds: replacedInstanceIds,+ props,+ dataSources,+ styleSources,+ styleSourceSelections,+ styles,+ });+ payload[0]?.patches.push(...(instanceCleanup?.patches ?? []));+ payload.push(...compactBuilderPatchPayload(cleanupPayload));+ }++ return {+ payload,+ replacedInstanceIds: Array.from(replacedInstanceIds),+ };+};++export const createInstanceDeletePayload = ({+ instances,+ instanceIds,+ pageRootIds = new Set(),+ props,+ dataSources,+ styleSources,+ styleSourceSelections,+ styles,+}: {+ instances: Instances;+ instanceIds: Instance["id"][];+ pageRootIds?: Set<Instance["id"]>;+ props: Iterable<Prop>;+ dataSources: Iterable<DataSource>;+ styleSources: Iterable<StyleSource>;+ styleSourceSelections: Iterable<StyleSourceSelection>;+ styles: Iterable<StyleDecl>;+}) => {+ const parentRemovalPatches = [];+ const deletedInstanceIds = new Set<Instance["id"]>();+ const errors: Array<+ | { type: "page-root"; instanceId: Instance["id"] }+ | { type: "instance-not-found"; instanceId: Instance["id"] }+ | { type: "parent-not-found"; instanceId: Instance["id"] }+ > = [];++ for (const instanceId of instanceIds) {+ if (pageRootIds.has(instanceId)) {+ errors.push({ type: "page-root", instanceId });+ continue;+ }+ if (instances.has(instanceId) === false) {+ errors.push({ type: "instance-not-found", instanceId });+ continue;+ }+ const parent = findParentInstanceReference(instances, instanceId);+ if (parent === undefined) {+ errors.push({ type: "parent-not-found", instanceId });+ continue;+ }+ parentRemovalPatches.push({+ op: "remove" as const,+ path: [parent.instance.id, "children", parent.childIndex] as [+ string,+ "children",+ number,+ ],+ });+ for (const descendantId of collectInstanceIds(instances, instanceId)) {+ deletedInstanceIds.add(descendantId);+ }+ }++ const payload = createInstanceCleanupPayload({+ instanceIds: deletedInstanceIds,+ props,+ dataSources,+ styleSources,+ styleSourceSelections,+ styles,+ });+ if (parentRemovalPatches.length > 0) {+ const sortedParentRemovalPatches =+ sortChildRemovalPatches(parentRemovalPatches);+ if (payload[0]?.namespace === "instances") {+ payload[0].patches.unshift(...sortedParentRemovalPatches);+ } else {+ payload.unshift({+ namespace: "instances",+ patches: sortedParentRemovalPatches,+ });+ }+ }++ return { errors, payload, instanceIds: Array.from(deletedInstanceIds) };+};++export const createInstanceClonePayload = ({+ instances,+ sourceInstanceId,+ targetParent,+ insertIndex,+ props,+ styleSourceSelections,+ styleSources,+ styles,+ createId,+}: {+ instances: Map<Instance["id"], Instance>;+ sourceInstanceId: Instance["id"];+ targetParent: Instance;+ insertIndex: number;+ props: Iterable<Prop>;+ styleSourceSelections: Iterable<StyleSourceSelection>;+ styleSources: Iterable<StyleSource>;+ styles: Map<string, StyleDecl>;+ createId: () => string;+}):+ | {+ clonedRootId: Instance["id"];+ clonedInstanceIds: Instance["id"][];+ payload: BuilderPatchChange[];+ }+ | undefined => {+ const { clonedInstances, nextIdById } = cloneInstanceSubtree({+ instances,+ rootInstanceId: sourceInstanceId,+ createId,+ });+ const clonedRootId = nextIdById.get(sourceInstanceId);+ if (clonedRootId === undefined) {+ return;+ }+ const propPatches = createPropClonePatches({+ nextIdById,+ props,+ createId,+ });+ return {+ clonedRootId,+ clonedInstanceIds: clonedInstances.map(([instanceId]) => instanceId),+ payload: compactBuilderPatchPayload([+ {+ namespace: "instances",+ patches: [+ ...clonedInstances.map(([instanceId, instance]) => ({+ op: "add" as const,+ path: [instanceId],+ value: instance,+ })),+ {+ op: "add" as const,+ path: [targetParent.id, "children", insertIndex],+ value: createInstanceChild(clonedRootId),+ },+ ],+ },+ ...(propPatches.length === 0+ ? []+ : [{ namespace: "props" as const, patches: propPatches }]),+ ...createStyleClonePayload({+ styleSourceSelections,+ styleSources,+ styles,+ nextIdById,+ createId,+ }),+ ]),+ };+};++type TreeMutationState = Pick<+ BuilderState,+ | "instances"+ | "pages"+ | "props"+ | "dataSources"+ | "styleSources"+ | "styleSourceSelections"+ | "styles"+>;++const getRequiredTreeMutationState = (state: TreeMutationState) => {+ const instances = getRequiredInstances(state);+ if (state.props === undefined) {+ return throwBuilderRuntimeError(+ "BAD_REQUEST",+ "Props namespace is missing"+ );+ }+ if (state.dataSources === undefined) {+ return throwBuilderRuntimeError(+ "BAD_REQUEST",+ "Data sources namespace is missing"+ );+ }+ if (state.styleSources === undefined) {+ return throwBuilderRuntimeError(+ "BAD_REQUEST",+ "Style sources namespace is missing"+ );+ }+ if (state.styleSourceSelections === undefined) {+ return throwBuilderRuntimeError(+ "BAD_REQUEST",+ "Style source selections namespace is missing"+ );+ }+ if (state.styles === undefined) {+ return throwBuilderRuntimeError(+ "BAD_REQUEST",+ "Styles namespace is missing"+ );+ }+ return {+ pages: state.pages,+ instances,+ props: state.props,+ dataSources: state.dataSources,+ styleSources: state.styleSources,+ styleSourceSelections: state.styleSourceSelections,+ styles: state.styles,+ };+};++const treeInvalidates = [+ "instances",+ "props",+ "dataSources",+ "resources",+ "styleSourceSelections",+ "styleSources",+ "styles",+] as const;++export const appendInstances = (+ state: TreeMutationState,+ input: {+ parentInstanceId: string;+ mode?: "append" | "prepend" | "replace";+ insertIndex?: number;+ children: Array<{+ instanceId?: string;+ component?: string;+ tag: string;+ label?: string;+ text?: string;+ }>;+ },+ context: BuilderRuntimeContext+) => {+ const mutationState = getRequiredTreeMutationState(state);+ const parent = mutationState.instances.get(input.parentInstanceId);+ if (parent === undefined) {+ return throwBuilderRuntimeError("NOT_FOUND", "Instance not found");+ }+ const mode = input.mode ?? "append";+ const insertIndex =+ mode === "replace"+ ? 0+ : mode === "prepend"+ ? 0+ : (input.insertIndex ?? parent.children.length);+ if (insertIndex > parent.children.length) {+ return throwBuilderRuntimeError(+ "BAD_REQUEST",+ "Insert index is outside parent children"+ );+ }+ const createdInstances = input.children.map((child) => {+ const instanceId = child.instanceId ?? context.createId();+ if (mutationState.instances.has(instanceId)) {+ return throwBuilderRuntimeError("CONFLICT", "Instance id already exists");+ }+ return {+ type: "instance" as const,+ id: instanceId,+ component: child.component ?? elementComponent,+ tag: child.tag,+ label: child.label,+ children:+ child.text === undefined+ ? []+ : [createTextContentChild({ type: "text", value: child.text })],+ };+ });+ const { payload, replacedInstanceIds } = createInstanceAppendPayload({+ parent,+ instances: mutationState.instances,+ createdInstances,+ insertIndex,+ mode,+ props: mutationState.props.values(),+ dataSources: mutationState.dataSources.values(),+ styleSources: mutationState.styleSources.values(),+ styleSourceSelections: mutationState.styleSourceSelections.values(),+ styles: mutationState.styles.values(),+ });+ return createRuntimeMutation({+ payload,+ result: {+ instanceIds: createdInstances.map((instance) => instance.id),+ removedInstanceIds: replacedInstanceIds,+ },+ invalidatesNamespaces: treeInvalidates,+ });+};++export const moveInstances = (+ state: Pick<BuilderState, "instances">,+ input: {+ moves: Array<{+ instanceId: string;+ parentInstanceId: string;+ insertIndex?: number;+ }>;+ }+) => {+ const { errors, payload } = createInstanceMovePayload({+ instances: getRequiredInstances(state),+ moves: input.moves,+ });+ const error = errors.at(0);+ if (error?.type === "instance-not-found") {+ return throwBuilderRuntimeError("NOT_FOUND", "Instance not found");+ }+ if (error?.type === "parent-not-found") {+ return throwBuilderRuntimeError("NOT_FOUND", "Parent instance not found");+ }+ if (error?.type === "target-parent-not-found") {+ return throwBuilderRuntimeError("NOT_FOUND", "Instance not found");+ }+ if (error?.type === "descendant-target") {+ return throwBuilderRuntimeError(+ "BAD_REQUEST",+ "Instance cannot be moved into itself or a descendant"+ );+ }+ if (error?.type === "insert-index-outside-parent") {+ return throwBuilderRuntimeError(+ "BAD_REQUEST",+ "Insert index is outside parent children"+ );+ }+ return createRuntimeMutation({+ payload,+ result: { instanceIds: input.moves.map((move) => move.instanceId) },+ invalidatesNamespaces: ["instances"],+ });+};++export const deleteInstances = (+ state: TreeMutationState,+ input: { instanceIds: string[] }+) => {+ const mutationState = getRequiredTreeMutationState(state);+ const pageRootIds = new Set(+ Array.from(mutationState.pages?.pages.values() ?? []).map(+ (page) => page.rootInstanceId+ )+ );+ const { errors, payload, instanceIds } = createInstanceDeletePayload({+ instances: mutationState.instances,+ instanceIds: input.instanceIds,+ pageRootIds,+ props: mutationState.props.values(),+ dataSources: mutationState.dataSources.values(),+ styleSources: mutationState.styleSources.values(),+ styleSourceSelections: mutationState.styleSourceSelections.values(),+ styles: mutationState.styles.values(),+ });+ const error = errors.at(0);+ if (error?.type === "page-root") {+ return throwBuilderRuntimeError(+ "BAD_REQUEST",+ "Page root instance cannot be deleted"+ );+ }+ if (error?.type === "instance-not-found") {+ return throwBuilderRuntimeError("NOT_FOUND", "Instance not found");+ }+ if (error?.type === "parent-not-found") {+ return throwBuilderRuntimeError("NOT_FOUND", "Parent instance not found");+ }+ return createRuntimeMutation({+ payload,+ result: { instanceIds },+ invalidatesNamespaces: treeInvalidates,+ });+};++export const cloneInstance = (+ state: TreeMutationState,+ input: {+ sourceInstanceId: string;+ targetParentInstanceId?: string;+ insertIndex?: number;+ },+ context: BuilderRuntimeContext+) => {+ const mutationState = getRequiredTreeMutationState(state);+ const source = mutationState.instances.get(input.sourceInstanceId);+ if (source === undefined) {+ return throwBuilderRuntimeError("NOT_FOUND", "Instance not found");+ }+ const targetParent =+ input.targetParentInstanceId === undefined+ ? findParentInstanceReference(mutationState.instances, source.id)+ ?.instance+ : mutationState.instances.get(input.targetParentInstanceId);+ if (targetParent === undefined) {+ return throwBuilderRuntimeError("NOT_FOUND", "Instance not found");+ }+ const insertIndex = input.insertIndex ?? targetParent.children.length;+ if (insertIndex > targetParent.children.length) {+ return throwBuilderRuntimeError(+ "BAD_REQUEST",+ "Insert index is outside parent children"+ );+ }+ const clone = createInstanceClonePayload({+ instances: mutationState.instances,+ sourceInstanceId: source.id,+ targetParent,+ insertIndex,+ props: mutationState.props.values(),+ styleSourceSelections: mutationState.styleSourceSelections.values(),+ styleSources: mutationState.styleSources.values(),+ styles: mutationState.styles,+ createId: context.createId,+ });+ if (clone === undefined) {+ return throwBuilderRuntimeError(+ "BAD_REQUEST",+ "Source instance could not be cloned"+ );+ }+ return createRuntimeMutation({+ payload: clone.payload,+ result: {+ instanceId: clone.clonedRootId,+ instanceIds: clone.clonedInstanceIds,+ },+ invalidatesNamespaces: [+ "instances",+ "props",+ "styleSourceSelections",+ "styleSources",+ "styles",+ ],+ });+};++export const serializeInstanceSummary = (+ instance: Instance,+ depth: number+) => ({+ id: instance.id,+ component: instance.component,+ tag: instance.tag,+ label: instance.label,+ childCount: instance.children.length,+ depth,+});++export const isTextContentChild = (+ child: Instance["children"][number] | undefined+): child is TextContentChild =>+ child?.type === "text" || child?.type === "expression";++export const getTextContentChild = (instance: Instance, childIndex: number) => {+ const child = instance.children[childIndex];+ return isTextContentChild(child) ? child : undefined;+};++export const findTextContentChild = (+ instances: Iterable<Instance>,+ input: {+ instanceId: Instance["id"];+ childIndex: number;+ mode?: TextContentChild["type"];+ }+):+ | { status: "found"; child: TextContentChild }+ | { status: "instance-not-found" }+ | { status: "child-not-found" }+ | { status: "not-text-content" }+ | { status: "mode-mismatch"; actual: TextContentChild["type"] } => {+ let instance: Instance | undefined;+ for (const item of instances) {+ if (item.id === input.instanceId) {+ instance = item;+ break;+ }+ }+ if (instance === undefined) {+ return { status: "instance-not-found" };+ }+ if (instance.children[input.childIndex] === undefined) {+ return { status: "child-not-found" };+ }+ const child = getTextContentChild(instance, input.childIndex);+ if (child === undefined) {+ return { status: "not-text-content" };+ }+ if (input.mode !== undefined && child.type !== input.mode) {+ return { status: "mode-mismatch", actual: child.type };+ }+ return { status: "found", child };+};++export const createTextContentChild = ({+ type,+ value,+}: {+ type: TextContentChild["type"];+ value: string;+}): TextContentChild => ({ type, value });++export const getTextContentErrors = ({+ type,+ value,+}: {+ type: TextContentChild["type"];+ value: string;+}) => {+ if (type === "text") {+ return [];+ }+ return lintExpression({ expression: value })+ .filter((diagnostic) => diagnostic.severity === "error")+ .map((diagnostic) => diagnostic.message);+};++export const setTextContentMutable = (+ instance: Instance,+ type: TextContentChild["type"],+ value: string+) => {+ instance.children = [createTextContentChild({ type, value })];+};++export const createTextContentUpdatePayload = ({+ instanceId,+ childIndex,+ child,+}: {+ instanceId: Instance["id"];+ childIndex: number;+ child: TextContentChild;+}) => [+ {+ namespace: "instances" as const,+ patches: [+ {+ op: "replace" as const,+ path: [instanceId, "children", childIndex],+ value: child,+ },+ ],+ },+];++export const createTextContentResetPayload = ({+ instanceId,+}: {+ instanceId: Instance["id"];+}) => [+ {+ namespace: "instances" as const,+ patches: [+ {+ op: "replace" as const,+ path: [instanceId, "children"],+ value: [],+ },+ ],+ },+];++export const serializeTextNodes = ({+ instances,+ rootInstanceIds,+ instanceId,+ mode = "all",+ contains,+ maxValueLength,+}: {+ instances: Iterable<Instance>;+ rootInstanceIds?: Set<Instance["id"]>;+ instanceId?: Instance["id"];+ mode?: "text" | "expression" | "all";+ contains?: string;+ maxValueLength?: number;+}) => {+ const texts = [];+ for (const instance of instances) {+ if (instanceId !== undefined && instance.id !== instanceId) {+ continue;+ }+ if (+ rootInstanceIds !== undefined &&+ rootInstanceIds.has(instance.id) === false+ ) {+ continue;+ }+ for (const [childIndex, child] of instance.children.entries()) {+ if (isTextContentChild(child) === false) {+ continue;+ }+ if (mode !== "all" && child.type !== mode) {+ continue;+ }+ if (contains !== undefined && child.value.includes(contains) === false) {+ continue;+ }+ texts.push({+ instanceId: instance.id,+ childIndex,+ component: instance.component,+ label: instance.label,+ mode: child.type,+ value:+ maxValueLength === undefined+ ? child.value+ : child.value.slice(0, maxValueLength),+ });+ }+ }+ return texts;+};++const getPageFilteredRootInstanceIds = (+ state: Pick<BuilderState, "pages" | "instances">,+ input: { pageId?: string; pagePath?: string }+) => {+ const pages = getSerializedPages(state);+ const page = findSerializedPageByInput(pages, input);+ if (+ page === undefined &&+ (input.pageId !== undefined || input.pagePath !== undefined)+ ) {+ return throwBuilderRuntimeError("NOT_FOUND", "Page not found");+ }+ return page === undefined ? undefined : [page.rootInstanceId];+};++export const listInstances = (+ state: Pick<BuilderState, "pages" | "instances">,+ input: {+ pageId?: string;+ pagePath?: string;+ rootInstanceId?: string;+ maxDepth?: number;+ topLevelOnly?: boolean;+ component?: string;+ tag?: string;+ labelContains?: string;+ } = {}+) => {+ const instances = getRequiredInstances(state);+ const rootInstanceIds =+ input.rootInstanceId === undefined+ ? getPageFilteredRootInstanceIds(state, input)+ : [input.rootInstanceId];+ const depths = getInstanceDepths(instances, rootInstanceIds);+ const results = [];+ for (const instance of instances.values()) {+ const depth = depths.get(instance.id);+ if (depth === undefined) {+ continue;+ }+ if (input.maxDepth !== undefined && depth > input.maxDepth) {+ continue;+ }+ if (input.topLevelOnly === true && depth > 0) {+ continue;+ }+ if (+ input.component !== undefined &&+ instance.component !== input.component+ ) {+ continue;+ }+ if (input.tag !== undefined && instance.tag !== input.tag) {+ continue;+ }+ if (+ input.labelContains !== undefined &&+ instance.label?.includes(input.labelContains) !== true+ ) {+ continue;+ }+ results.push(serializeInstanceSummary(instance, depth));+ }+ return { instances: results };+};++export const listTextInstances = (+ state: Pick<BuilderState, "pages" | "instances">,+ input: {+ pageId?: string;+ pagePath?: string;+ instanceId?: string;+ mode?: "text" | "expression" | "all";+ contains?: string;+ maxValueLength?: number;+ } = {}+) => {+ const rootInstanceIds = getPageFilteredRootInstanceIds(state, input);+ const pageInstanceIds =+ rootInstanceIds === undefined+ ? undefined+ : new Set(+ getInstanceDepths(getRequiredInstances(state), rootInstanceIds).keys()+ );+ return {+ texts: serializeTextNodes({+ instances: getRequiredInstances(state).values(),+ rootInstanceIds: pageInstanceIds,+ instanceId: input.instanceId,+ mode: input.mode,+ contains: input.contains,+ maxValueLength: input.maxValueLength,+ }),+ };+};++export const inspectInstance = (+ state: Pick<+ BuilderState,+ "instances" | "props" | "styles" | "styleSources" | "styleSourceSelections"+ >,+ input: {+ instanceId: string;+ include?: Array<"props" | "styles" | "children" | "bindings" | "sources">;+ childDepth?: number;+ }+) => {+ const instances = getRequiredInstances(state);+ const instance = instances.get(input.instanceId);+ if (instance === undefined) {+ return throwBuilderRuntimeError("NOT_FOUND", "Instance not found");+ }+ const depths = getInstanceDepths(instances, [input.instanceId]);+ const include = new Set(input.include ?? []);+ const details: Record<string, unknown> = serializeInstanceSummary(+ instance,+ depths.get(instance.id) ?? 0+ );+ if (include.has("props")) {+ details.props = Array.from(state.props?.values() ?? []).filter(+ (prop) => prop.instanceId === instance.id+ );+ }+ if (include.has("styles")) {+ details.styles = serializeStyleDeclarations({+ styles: state.styles?.values() ?? [],+ styleSources: state.styleSources?.values() ?? [],+ styleSourceSelections: state.styleSourceSelections?.values() ?? [],+ instanceIds: new Set([instance.id]),+ });+ }+ if (include.has("children")) {+ const maxDepth = input.childDepth ?? 1;+ details.children = Array.from(instances.values())+ .filter((child) => {+ const depth = depths.get(child.id);+ return depth !== undefined && depth > 0 && depth <= maxDepth;+ })+ .map((child) =>+ serializeInstanceSummary(child, depths.get(child.id) ?? 0)+ );+ }+ if (include.has("bindings")) {+ details.bindings = Array.from(state.props?.values() ?? []).filter(+ (prop) =>+ prop.instanceId === instance.id &&+ (prop.type === "expression" ||+ prop.type === "parameter" ||+ prop.type === "resource" ||+ prop.type === "action")+ );+ }+ if (include.has("sources")) {+ details.sources =+ state.styleSourceSelections?.get(instance.id)?.values ?? [];+ }+ return details;+};++export const updateTextInstance = (+ state: Pick<BuilderState, "instances">,+ input: {+ instanceId: string;+ childIndex: number;+ text: string;+ mode?: "text" | "expression";+ }+) => {+ const result = findTextContentChild(+ getRequiredInstances(state).values(),+ input+ );+ if (result.status === "instance-not-found") {+ return throwBuilderRuntimeError("NOT_FOUND", "Instance not found");+ }+ if (result.status === "child-not-found") {+ return throwBuilderRuntimeError("NOT_FOUND", "Child not found");+ }+ if (result.status === "not-text-content") {+ return throwBuilderRuntimeError(+ "BAD_REQUEST",+ "Child is not text or expression"+ );+ }+ if (result.status === "mode-mismatch") {+ return throwBuilderRuntimeError(+ "BAD_REQUEST",+ `Child is ${result.actual}, not ${input.mode}`+ );+ }++ const mode = input.mode ?? result.child.type;+ const errors = getTextContentErrors({ type: mode, value: input.text });+ if (errors.length > 0) {+ return throwBuilderRuntimeError("BAD_REQUEST", errors.join("\n"));+ }+ const mutationResult = {+ instanceId: input.instanceId,+ childIndex: input.childIndex,+ mode,+ };+ if (result.child.value === input.text) {+ return createRuntimeMutation({+ payload: [],+ result: mutationResult,+ invalidatesNamespaces: ["instances"],+ });+ }+ return createRuntimeMutation({+ payload: createTextContentUpdatePayload({+ instanceId: input.instanceId,+ childIndex: input.childIndex,+ child: createTextContentChild({ type: mode, value: input.text }),+ }),+ result: mutationResult,+ invalidatesNamespaces: ["instances"],+ });+};diff --git a/packages/project-build/src/runtime/mutation.test.ts b/packages/project-build/src/runtime/mutation.test.tsnew file mode 100644index 0000000000..f55e6fe915--- /dev/null+++ b/packages/project-build/src/runtime/mutation.test.ts@@ -0,0 +1,26 @@+import { expect, test } from "vitest";+import { createRuntimeMutation } from "./mutation";++test("creates mutation result and marks noop from payload", () => {+ expect(+ createRuntimeMutation({+ payload: [],+ result: { pageId: "page" },+ invalidatesNamespaces: ["pages"],+ })+ ).toEqual({+ kind: "mutation",+ payload: [],+ result: { pageId: "page" },+ invalidatesNamespaces: ["pages"],+ noop: true,+ });++ expect(+ createRuntimeMutation({+ payload: [{ namespace: "pages", patches: [] }],+ result: {},+ invalidatesNamespaces: [],+ }).noop+ ).toBe(false);+});diff --git a/packages/project-build/src/runtime/mutation.ts b/packages/project-build/src/runtime/mutation.tsnew file mode 100644index 0000000000..be3d534adc--- /dev/null+++ b/packages/project-build/src/runtime/mutation.ts@@ -0,0 +1,30 @@+import type { BuilderNamespace } from "../contracts/namespaces";+import type { BuilderPatchChange } from "../contracts/patch";++export type BuilderRuntimeMutation<+ Result extends Record<string, unknown> = Record<string, unknown>,+> = {+ kind: "mutation";+ payload: BuilderPatchChange[];+ result: Result;+ invalidatesNamespaces: readonly BuilderNamespace[];+ noop: boolean;+};++export const createRuntimeMutation = <+ Result extends Record<string, unknown> = Record<string, unknown>,+>({+ payload,+ result,+ invalidatesNamespaces,+}: {+ payload: BuilderPatchChange[];+ result: Result;+ invalidatesNamespaces: readonly BuilderNamespace[];+}): BuilderRuntimeMutation<Result> => ({+ kind: "mutation",+ payload,+ result,+ invalidatesNamespaces,+ noop: payload.length === 0,+});diff --git a/apps/builder/app/shared/page-utils.test.tsx b/packages/project-build/src/runtime/page-copy.test.tsxsimilarity index 72%rename from apps/builder/app/shared/page-utils.test.tsxrename to packages/project-build/src/runtime/page-copy.test.tsxindex 452b94c87a..bd372ba51f 100644--- a/apps/builder/app/shared/page-utils.test.tsx+++ b/packages/project-build/src/runtime/page-copy.test.tsx@@ -1,12 +1,10 @@import { describe, expect, test } from "vitest";-import type { Project } from "@webstudio-is/project";import {ROOT_FOLDER_ID,ROOT_INSTANCE_ID,encodeDataVariableId,getHomePage,type DataSource,- type Page,type Instance,type WebstudioData,} from "@webstudio-is/sdk";@@ -15,15 +13,17 @@ import {createDefaultPages,createRootFolder,} from "@webstudio-is/project-build";-import { $project } from "./sync/data-stores";import {__testing__,+ createPageFromTemplate,+ createPageDuplicatePayload,+ createTemplateCopyData,+ duplicatePage,insertPageCopyMutable,insertPageFromTemplateMutable,- createTemplateCopyData,insertTemplateCopyFromFragmentsMutable,- copyAndTransformPageMeta,-} from "./page-utils";+ listPageTemplates,+} from "./page-copy";import {$,expression,@@ -125,55 +125,7 @@ describe("page utility helpers", () => {});});-describe("page meta copy helpers", () => {- test("copies and transforms selected page meta fields", () => {- const target: Page["meta"] = {};-- copyAndTransformPageMeta(- {- title: "old",- description: "old",- documentType: "text",- auth: { method: "basic", login: "u", password: "p" },- },- target,- (value) => value.replace("old", "new"),- { fields: new Set(["title", "documentType"]) }- );-- expect(target).toEqual({- title: "new",- documentType: "text",- });- });-- test("copies only caller-selected page meta fields", () => {- const target: Page["meta"] = {};-- copyAndTransformPageMeta(- {- title: "old",- description: "old",- documentType: "text",- auth: { method: "basic", login: "u", password: "p" },- custom: [{ property: "og:type", content: "old" }],- },- target,- (value) => value.replace("old", "new"),- { fields: new Set(["title", "description", "custom"]) }- );-- expect(target).toEqual({- title: "new",- description: "new",- custom: [{ property: "og:type", content: "new" }],- });- });-});-describe("insert page copy", () => {- $project.set({ id: "projectId" } as Project);-test("insert home page copy with new path and ids", () => {const data = getWebstudioDataStub({instances: toMap<Instance>([@@ -196,6 +148,7 @@ describe("insert page copy", () => {insertPageCopyMutable({source: { data, pageId: "pageId" },target: { data, folderId: ROOT_FOLDER_ID },+ projectId: "projectId",});const copiedPages = getCopiedPages(data);expect(copiedPages.length).toEqual(1);@@ -217,6 +170,204 @@ describe("insert page copy", () => {});});+ test("creates duplicate page patch payload from shared copy semantics", () => {+ const data = getWebstudioDataStub({+ instances: toMap<Instance>([+ { type: "instance", id: "bodyId", component: "Body", children: [] },+ ]),+ pages: migratePages({+ meta: {},+ homePage: {+ id: "pageId",+ name: "Name",+ path: "",+ title: `"Title"`,+ meta: {},+ rootInstanceId: "bodyId",+ },+ pages: [],+ folders: [createRootFolder(["pageId"])],+ }),+ });++ const result = createPageDuplicatePayload({+ build: {+ pages: data.pages,+ instances: Array.from(data.instances.values()),+ props: [],+ dataSources: [],+ resources: [],+ breakpoints: [],+ styleSources: [],+ styleSourceSelections: [],+ styles: [],+ },+ projectId: "projectId",+ pageId: "pageId",+ parentFolderId: ROOT_FOLDER_ID,+ name: "Custom",+ path: "/custom",+ });++ expect(result?.pageId).toEqual(expect.any(String));+ expect(result?.pageId).not.toEqual("pageId");+ const pagesPayload = result?.payload.find(+ (item) => item.namespace === "pages"+ );+ expect(pagesPayload?.patches).toEqual([+ {+ op: "add",+ path: ["pages", result?.pageId],+ value: expect.objectContaining({+ id: result?.pageId,+ name: "Custom",+ path: "/custom",+ title: `"Title"`,+ rootInstanceId: expect.not.stringMatching("bodyId"),+ }),+ },+ {+ op: "replace",+ path: ["folders", ROOT_FOLDER_ID],+ value: expect.objectContaining({+ children: ["pageId", result?.pageId],+ }),+ },+ ]);+ expect(result?.payload).toContainEqual({+ namespace: "instances",+ patches: [+ {+ op: "add",+ path: [expect.not.stringMatching("bodyId")],+ value: expect.objectContaining({ component: "Body" }),+ },+ ],+ });+ });++ test("runtime duplicate infers the source page parent folder", () => {+ const data = getWebstudioDataStub({+ instances: toMap<Instance>([+ { type: "instance", id: "bodyId", component: "Body", children: [] },+ ]),+ pages: migratePages({+ meta: {},+ homePage: {+ id: "homePageId",+ name: "Home",+ path: "",+ title: `"Home"`,+ meta: {},+ rootInstanceId: "bodyId",+ },+ pages: [+ {+ id: "pageId",+ name: "Name",+ path: "/nested",+ title: `"Title"`,+ meta: {},+ rootInstanceId: "bodyId",+ },+ ],+ folders: [+ createRootFolder(["homePageId", "folderId"]),+ {+ id: "folderId",+ name: "Folder",+ slug: "folder",+ children: ["pageId"],+ },+ ],+ }),+ });++ const result = duplicatePage(+ data,+ {+ projectId: "projectId",+ pageId: "pageId",+ name: "Copy",+ path: "/copy",+ },+ { createId: nanoid }+ );++ expect(result.result.pageId).toEqual(expect.any(String));+ expect(result.payload).toContainEqual({+ namespace: "pages",+ patches: expect.arrayContaining([+ {+ op: "add",+ path: ["pages", result.result.pageId],+ value: expect.objectContaining({+ id: result.result.pageId,+ name: "Copy",+ path: "/copy",+ }),+ },+ {+ op: "replace",+ path: ["folders", "folderId"],+ value: expect.objectContaining({+ children: ["pageId", result.result.pageId],+ }),+ },+ ]),+ });+ });++ test("runtime duplicate rejects explicit path conflicts", () => {+ const data = getWebstudioDataStub({+ instances: toMap<Instance>([+ { type: "instance", id: "bodyId", component: "Body", children: [] },+ ]),+ pages: migratePages({+ meta: {},+ homePage: {+ id: "homePageId",+ name: "Home",+ path: "",+ title: `"Home"`,+ meta: {},+ rootInstanceId: "bodyId",+ },+ pages: [+ {+ id: "pageId",+ name: "Name",+ path: "/nested",+ title: `"Title"`,+ meta: {},+ rootInstanceId: "bodyId",+ },+ {+ id: "conflictId",+ name: "Conflict",+ path: "/copy",+ title: `"Conflict"`,+ meta: {},+ rootInstanceId: "bodyId",+ },+ ],+ folders: [createRootFolder(["homePageId", "pageId", "conflictId"])],+ }),+ });++ expect(() =>+ duplicatePage(+ data,+ {+ projectId: "projectId",+ pageId: "pageId",+ path: "/copy",+ },+ { createId: nanoid }+ )+ ).toThrow('Page path "/copy" is already in use');+ });+test("preserves slot content ids when duplicating page", () => {const dataWithoutPages = renderData(<$.Body ws:id="bodyId">@@ -247,6 +398,7 @@ describe("insert page copy", () => {insertPageCopyMutable({source: { data, pageId: "pageId" },target: { data, folderId: ROOT_FOLDER_ID },+ projectId: "projectId",});const copiedPage = getCopiedPages(data)[0];@@ -301,6 +453,7 @@ describe("insert page copy", () => {insertPageCopyMutable({source: { data, pageId: "pageId" },target: { data, folderId: ROOT_FOLDER_ID },+ projectId: "projectId",});const copiedPages = getCopiedPages(data);expect(copiedPages.length).toEqual(2);@@ -349,10 +502,12 @@ describe("insert page copy", () => {insertPageCopyMutable({source: { data, pageId: "page1Id" },target: { data, folderId: ROOT_FOLDER_ID },+ projectId: "projectId",});insertPageCopyMutable({source: { data, pageId: "page2Id" },target: { data, folderId: ROOT_FOLDER_ID },+ projectId: "projectId",});const copiedPages = getCopiedPages(data);expect(copiedPages.length).toEqual(4);@@ -401,10 +556,12 @@ describe("insert page copy", () => {insertPageCopyMutable({source: { data, pageId: "pageId" },target: { data, folderId: "folderId" },+ projectId: "projectId",});insertPageCopyMutable({source: { data, pageId: "pageId" },target: { data, folderId: ROOT_FOLDER_ID },+ projectId: "projectId",});const copiedPages = getCopiedPages(data);expect(copiedPages.length).toEqual(3);@@ -453,6 +610,7 @@ describe("insert page copy", () => {insertPageCopyMutable({source: { data, pageId: "pageId" },target: { data, folderId: "folderId" },+ projectId: "projectId",});const copiedPages = getCopiedPages(data);expect(copiedPages.length).toEqual(2);@@ -501,6 +659,7 @@ describe("insert page copy", () => {insertPageCopyMutable({source: { data, pageId: "pageId" },target: { data, folderId: ROOT_FOLDER_ID },+ projectId: "projectId",});const copiedPages = getCopiedPages(data);expect(copiedPages.length).toEqual(1);@@ -561,18 +720,22 @@ describe("insert page copy", () => {insertPageCopyMutable({source: { data, pageId: "pageId" },target: { data, folderId: ROOT_FOLDER_ID },+ projectId: "projectId",});insertPageCopyMutable({source: { data, pageId: "pageId" },target: { data, folderId: ROOT_FOLDER_ID },+ projectId: "projectId",});insertPageCopyMutable({source: { data, pageId: "pageId" },target: { data, folderId: "folderId" },+ projectId: "projectId",});insertPageCopyMutable({source: { data, pageId: "pageId" },target: { data, folderId: "folderId" },+ projectId: "projectId",});const copiedPages = getCopiedPages(data);expect(copiedPages.length).toEqual(4);@@ -602,6 +765,7 @@ describe("insert page copy", () => {insertPageCopyMutable({source: { data, pageId: data.pages.homePageId },target: { data, folderId: ROOT_FOLDER_ID },+ projectId: "projectId",});expect(data.dataSources.size).toEqual(1);const [globalVariableId] = data.dataSources.keys();@@ -650,6 +814,7 @@ describe("insert page copy", () => {insertPageCopyMutable({source: { data: sourceData, pageId: sourceData.pages.homePageId },target: { data: targetData, folderId: ROOT_FOLDER_ID },+ projectId: "projectId",});expect(targetData.dataSources.size).toEqual(1);const [globalVariableId] = targetData.dataSources.keys();@@ -691,6 +856,7 @@ describe("insert page copy", () => {insertPageCopyMutable({source: { data: sourceData, pageId: sourceData.pages.homePageId },target: { data: targetData, folderId: ROOT_FOLDER_ID },+ projectId: "projectId",});expect(targetData.dataSources.size).toEqual(1);const [globalVariableId] = targetData.dataSources.keys();@@ -726,6 +892,7 @@ describe("insert page copy", () => {insertPageCopyMutable({source: { data, pageId: data.pages.homePageId },target: { data, folderId: ROOT_FOLDER_ID },+ projectId: "projectId",});expect(data.dataSources.size).toEqual(1);expect(Array.from(data.instances.values())).toEqual([@@ -794,6 +961,7 @@ describe("insert page copy", () => {source: { data },target: { data, folderId: ROOT_FOLDER_ID },overrides: { name: "Template", path: "/template" },+ projectId: "projectId",});expect(pageId).toBeDefined();@@ -820,6 +988,194 @@ describe("insert page copy", () => {expect(data.pages.folders.get(ROOT_FOLDER_ID)?.children).toContain(pageId);});+ test("lists page templates", () => {+ const pages = migratePages({+ homePage: {+ id: "homePageId",+ name: "Home",+ path: "",+ title: `"Home"`,+ rootInstanceId: "homeBodyId",+ meta: {},+ },+ pages: [],+ folders: [createRootFolder(["homePageId"])],+ });+ pages.pageTemplates = new Map([+ [+ "templateId",+ {+ id: "templateId",+ name: "Template",+ title: `"Template"`,+ rootInstanceId: "templateBodyId",+ meta: { description: `"Description"` },+ },+ ],+ ]);+ const data = getWebstudioDataStub({+ pages,+ });++ expect(listPageTemplates(data)).toEqual({+ templates: [+ {+ id: "templateId",+ name: "Template",+ title: `"Template"`,+ rootInstanceId: "templateBodyId",+ systemDataSourceId: undefined,+ meta: { description: `"Description"` },+ },+ ],+ });+ });++ test("creates page from template patch payload from shared copy semantics", () => {+ const pages = migratePages({+ homePage: {+ id: "homePageId",+ name: "Home",+ path: "",+ title: `"Home"`,+ rootInstanceId: "homeBodyId",+ meta: {},+ },+ pages: [],+ folders: [createRootFolder(["homePageId"])],+ });+ pages.pageTemplates = new Map([+ [+ "templateId",+ {+ id: "templateId",+ name: "Template",+ title: `"Template"`,+ rootInstanceId: "templateBodyId",+ meta: {},+ },+ ],+ ]);+ const data = getWebstudioDataStub({+ pages,+ instances: toMap<Instance>([+ {+ type: "instance",+ id: ROOT_INSTANCE_ID,+ component: "Root",+ children: [{ type: "id", value: "templateBodyId" }],+ },+ {+ type: "instance",+ id: "templateBodyId",+ component: "Body",+ tag: "body",+ children: [],+ },+ ]),+ });+ let index = 0;++ const result = createPageFromTemplate(+ data,+ {+ projectId: "projectId",+ templateId: "templateId",+ name: "Landing",+ path: "/landing",+ },+ { createId: () => `id-${index++}` }+ );+ const { pageId } = result.result;++ expect(pageId).toBeDefined();+ expect(result.payload).toContainEqual({+ namespace: "pages",+ patches: expect.arrayContaining([+ expect.objectContaining({+ op: "add",+ path: ["pages", pageId],+ value: expect.objectContaining({+ id: pageId,+ name: "Landing",+ path: "/landing",+ }),+ }),+ ]),+ });+ expect(result.payload).toContainEqual({+ namespace: "instances",+ patches: expect.arrayContaining([expect.objectContaining({ op: "add" })]),+ });+ });++ test("create page from template rejects path conflicts", () => {+ const pages = migratePages({+ homePage: {+ id: "homePageId",+ name: "Home",+ path: "",+ title: `"Home"`,+ rootInstanceId: "homeBodyId",+ meta: {},+ },+ pages: [+ {+ id: "landingId",+ name: "Landing",+ path: "/landing",+ title: `"Landing"`,+ rootInstanceId: "homeBodyId",+ meta: {},+ },+ ],+ folders: [createRootFolder(["homePageId", "landingId"])],+ });+ pages.pageTemplates = new Map([+ [+ "templateId",+ {+ id: "templateId",+ name: "Template",+ title: `"Template"`,+ rootInstanceId: "templateBodyId",+ meta: {},+ },+ ],+ ]);+ const data = getWebstudioDataStub({+ pages,+ instances: toMap<Instance>([+ {+ type: "instance",+ id: ROOT_INSTANCE_ID,+ component: "Root",+ children: [{ type: "id", value: "templateBodyId" }],+ },+ {+ type: "instance",+ id: "templateBodyId",+ component: "Body",+ tag: "body",+ children: [],+ },+ ]),+ });++ expect(() =>+ createPageFromTemplate(+ data,+ {+ projectId: "projectId",+ templateId: "templateId",+ name: "Landing",+ path: "/landing",+ },+ { createId: nanoid }+ )+ ).toThrow('Page path "/landing" is already in use');+ });+test("insert template copy preserves and remaps system data source", () => {const systemDataSource: DataSource = {id: "templateSystemId",@@ -872,6 +1228,7 @@ describe("insert page copy", () => {const templateId = insertTemplateCopyFromFragmentsMutable({source: createTemplateCopyData({ data, template: template! }),target: { data },+ projectId: "projectId",});const copiedTemplate = data.pages.pageTemplates?.get(templateId ?? "");diff --git a/apps/builder/app/shared/page-utils.ts b/packages/project-build/src/runtime/page-copy.tssimilarity index 68%rename from apps/builder/app/shared/page-utils.tsrename to packages/project-build/src/runtime/page-copy.tsindex b57e997116..6241a7cc80 100644--- a/apps/builder/app/shared/page-utils.ts+++ b/packages/project-build/src/runtime/page-copy.ts@@ -1,29 +1,75 @@-import { insertWebstudioFragmentCopy } from "./instance-utils/fragment";-import { unwrap } from "./instance-utils/data";+import {+ type ContentModeCopyableProp,+ extractWebstudioFragment,+ insertWebstudioFragmentCopy,+} from "./fragment";import { nanoid } from "nanoid";import {+ createWebstudioDataFromBuild,+ createWebstudioDataPatchPayload,+ findAvailableVariables,+ replaceDataSourcesInExpression,+ restoreExpressionVariables,+ unsetExpressionVariables,+} from "./data";+import {+ findParentFolderByChildId,findPageByIdOrPath,getFolderById,getPagePath,+ type Asset,type Folder,type DataSource,type Page,type PageTemplate,type Pages,+ type WsComponentMeta,type WebstudioFragment,type WebstudioData,ROOT_INSTANCE_ID,} from "@webstudio-is/sdk";-import { contentModePageMetaFields } from "@webstudio-is/project/content-mode-permissions";-import { extractWebstudioFragment } from "./instance-utils/fragment";-import {- findAvailableVariables,- replaceDataSourcesInExpression,- restoreExpressionVariables,- unsetExpressionVariables,-} from "./data-variables";-import { $project } from "./sync/data-stores";-import type { ConflictResolution } from "./token-conflict-dialog";+import type { ConflictResolution } from "./style-copy";+import type { BuilderState } from "../state/builder-state";+import { throwBuilderRuntimeError } from "./errors";+import { createRuntimeMutation } from "./mutation";+import { getRequiredPages, isPathAvailable } from "./pages";+import { unwrap } from "./unwrap";++type CreateId = () => string;++const contentModePageMetaFields = new Set([+ "description",+ "title",+ "excludePageFromSearch",+ "language",+ "socialImageAssetId",+ "socialImageUrl",+ "custom",+]);++const getRequiredWebstudioData = (state: BuilderState): WebstudioData => {+ const required = [+ "pages",+ "assets",+ "dataSources",+ "resources",+ "instances",+ "props",+ "breakpoints",+ "styles",+ "styleSources",+ "styleSourceSelections",+ ] as const;+ for (const namespace of required) {+ if (state[namespace] === undefined) {+ return throwBuilderRuntimeError(+ "BAD_REQUEST",+ `${namespace} namespace is missing`+ );+ }+ }+ return state as WebstudioData;+};const parseCopyNumberSuffix = (value: string) => {const { name = value, copyNumber = "0" } =@@ -107,14 +153,22 @@ const copyPageRootAndBodyMutable = ({target,sourceRootInstanceId,systemDataSourceId,+ projectId,+ metas,conflictResolution,+ contentModeCopyableProp,+ createId = nanoid,contentMode = false,}: {source: WebstudioData;target: WebstudioData;sourceRootInstanceId: string;systemDataSourceId: string | undefined;+ projectId?: string;+ metas?: Map<string, WsComponentMeta>;conflictResolution: ConflictResolution | undefined;+ contentModeCopyableProp?: ContentModeCopyableProp;+ createId?: CreateId;contentMode?: boolean;}) => {const unsetVariables = new Set<DataSource["id"]>();@@ -132,8 +186,12 @@ const copyPageRootAndBodyMutable = ({bodyFragment: extractWebstudioFragment(source, sourceRootInstanceId, {unsetVariables,}),+ projectId,+ metas,conflictResolution,systemDataSourceId,+ contentModeCopyableProp,+ createId,contentMode,});};@@ -143,20 +201,27 @@ const copyPageFragmentsMutable = ({rootFragment,bodyFragment,systemDataSourceId,+ projectId,+ metas,conflictResolution,+ contentModeCopyableProp,onBreakpointLimitMerge,+ createId = nanoid,contentMode = false,}: {target: WebstudioData;rootFragment?: WebstudioFragment;bodyFragment: WebstudioFragment;systemDataSourceId: string | undefined;+ projectId?: string;+ metas?: Map<string, WsComponentMeta>;conflictResolution: ConflictResolution | undefined;+ contentModeCopyableProp?: ContentModeCopyableProp;onBreakpointLimitMerge?: () => void;+ createId?: CreateId;contentMode?: boolean;}) => {- const project = $project.get();- if (project === undefined) {+ if (projectId === undefined) {return;}if (contentMode === false && rootFragment !== undefined) {@@ -167,9 +232,12 @@ const copyPageFragmentsMutable = ({...target,startingInstanceId: ROOT_INSTANCE_ID,}),- projectId: project.id,+ projectId,+ metas,conflictResolution,+ contentModeCopyableProp,onBreakpointLimitMerge,+ createId,});}const unsetNameById = new Map<DataSource["id"], DataSource["name"]>();@@ -188,10 +256,13 @@ const copyPageFragmentsMutable = ({data: target,fragment: bodyFragment,availableVariables,- projectId: project.id,+ projectId,+ metas,conflictResolution,+ contentModeCopyableProp,onBreakpointLimitMerge,contentMode,+ createId,});const transformExpression = (expression: string) => {expression = unsetExpressionVariables({ expression, unsetNameById });@@ -206,13 +277,15 @@ const insertCopiedPageMutable = ({page,copied,target,+ createId,}: {page: Page;copied: NonNullable<ReturnType<typeof copyPageFragmentsMutable>>;target: { data: WebstudioData; folderId: Folder["id"] };+ createId: CreateId;}) => {const newPage = structuredClone(unwrap(page));- newPage.id = nanoid();+ newPage.id = createId();delete newPage.systemDataSourceId;newPage.rootInstanceId =copied.newInstanceIds.get(page.rootInstanceId) ?? page.rootInstanceId;@@ -244,13 +317,15 @@ const insertCopiedTemplateMutable = ({template,copied,target,+ createId,}: {template: PageTemplate;copied: NonNullable<ReturnType<typeof copyPageFragmentsMutable>>;target: { data: WebstudioData };+ createId: CreateId;}) => {const newTemplate = structuredClone(unwrap(template));- newTemplate.id = nanoid();+ newTemplate.id = createId();newTemplate.rootInstanceId =copied.newInstanceIds.get(template.rootInstanceId) ??template.rootInstanceId;@@ -271,7 +346,7 @@ const insertCopiedTemplateMutable = ({return newTemplate.id;};-export const copyAndTransformPageMeta = (+const copyAndTransformPageMeta = (source: Page["meta"],target: Page["meta"],transform: (expression: string) => string,@@ -338,14 +413,22 @@ export const insertPageFromTemplateMutable = ({source,target,overrides,+ projectId,+ metas,conflictResolution,+ contentModeCopyableProp,+ createId = nanoid,contentMode = false,}: {templateId: PageTemplate["id"];source: { data: WebstudioData };target: { data: WebstudioData; folderId: Folder["id"] };overrides: { name: string; path: string };+ projectId?: string;+ metas?: Map<string, WsComponentMeta>;conflictResolution?: ConflictResolution;+ contentModeCopyableProp?: ContentModeCopyableProp;+ createId?: CreateId;contentMode?: boolean;}) => {const template = source.data.pages.pageTemplates?.get(templateId);@@ -357,14 +440,18 @@ export const insertPageFromTemplateMutable = ({target: target.data,sourceRootInstanceId: template.rootInstanceId,systemDataSourceId: template.systemDataSourceId,+ projectId,+ metas,conflictResolution,+ contentModeCopyableProp,contentMode,+ createId,});if (copied === undefined) {return;}const newPage: Page = {- id: nanoid(),+ id: createId(),name: deduplicateName(target.data.pages, target.folderId, overrides.name),path: deduplicatePath(target.data.pages, target.folderId, overrides.path),title: copied.transformExpression(template.title),@@ -389,11 +476,15 @@ export const insertPageFromTemplateMutable = ({export const insertPageCopyMutable = ({source,target,+ projectId,conflictResolution,+ createId = nanoid,}: {source: { data: WebstudioData; pageId: Page["id"] };target: { data: WebstudioData; folderId: Folder["id"] };+ projectId?: string;conflictResolution?: ConflictResolution;+ createId?: CreateId;}) => {const page = findPageByIdOrPath(source.pageId, source.data.pages);if (page === undefined) {@@ -404,19 +495,227 @@ export const insertPageCopyMutable = ({target: target.data,sourceRootInstanceId: page.rootInstanceId,systemDataSourceId: page.systemDataSourceId,+ projectId,conflictResolution,+ createId,});if (copied === undefined) {return;}- return insertCopiedPageMutable({ page, copied, target });+ return insertCopiedPageMutable({ page, copied, target, createId });+};++export const createPageDuplicatePayload = ({+ build,+ assets,+ projectId,+ pageId,+ parentFolderId,+ name,+ path,+ createId = nanoid,+}: {+ build: Parameters<typeof createWebstudioDataFromBuild>[0]["build"];+ assets?: Asset[];+ projectId: string;+ pageId: Page["id"];+ parentFolderId: Folder["id"];+ name?: Page["name"];+ path?: Page["path"];+ createId?: CreateId;+}) => {+ const before = createWebstudioDataFromBuild({ build, assets });+ const after = structuredClone(before);+ const duplicatedPageId = insertPageCopyMutable({+ source: { data: after, pageId },+ target: { data: after, folderId: parentFolderId },+ projectId,+ createId,+ });+ if (duplicatedPageId === undefined) {+ return;+ }+ const page = after.pages.pages.get(duplicatedPageId);+ if (page === undefined) {+ return;+ }+ if (name !== undefined) {+ page.name = name;+ }+ if (path !== undefined) {+ page.path = path;+ }+ return {+ pageId: duplicatedPageId,+ payload: createWebstudioDataPatchPayload({ before, after }),+ };+};++export const duplicatePage = (+ state: BuilderState,+ input: {+ projectId: string;+ pageId: Page["id"];+ parentFolderId?: Folder["id"];+ name?: Page["name"];+ path?: Page["path"];+ },+ context: { createId: CreateId }+) => {+ const data = getRequiredWebstudioData(state);+ const parentFolderId =+ input.parentFolderId ??+ findParentFolderByChildId(input.pageId, data.pages.folders)?.id;+ if (parentFolderId === undefined) {+ return throwBuilderRuntimeError(+ "BAD_REQUEST",+ "Page parent folder was not found"+ );+ }+ if (data.pages.folders.has(parentFolderId) === false) {+ return throwBuilderRuntimeError("NOT_FOUND", "Parent folder not found");+ }+ if (+ input.path !== undefined &&+ isPathAvailable({+ pages: data.pages,+ path: input.path,+ parentFolderId,+ }) === false+ ) {+ return throwBuilderRuntimeError(+ "CONFLICT",+ `Page path "${input.path}" is already in use`+ );+ }+ const duplicate = createPageDuplicatePayload({+ build: data,+ assets: Array.from(data.assets.values()),+ projectId: input.projectId,+ pageId: input.pageId,+ parentFolderId,+ name: input.name,+ path: input.path,+ createId: context.createId,+ });+ if (duplicate === undefined) {+ return throwBuilderRuntimeError(+ "BAD_REQUEST",+ "Page could not be duplicated"+ );+ }+ return createRuntimeMutation({+ payload: duplicate.payload,+ result: { pageId: duplicate.pageId },+ invalidatesNamespaces: [+ "pages",+ "assets",+ "dataSources",+ "resources",+ "instances",+ "props",+ "breakpoints",+ "styles",+ "styleSources",+ "styleSourceSelections",+ ],+ });+};++export const listPageTemplates = (state: Pick<BuilderState, "pages">) => {+ const pages = getRequiredPages(state);+ return {+ templates: Array.from(pages.pageTemplates?.values() ?? []).map(+ (template) => ({+ id: template.id,+ name: template.name,+ title: template.title,+ rootInstanceId: template.rootInstanceId,+ systemDataSourceId: template.systemDataSourceId,+ meta: template.meta,+ })+ ),+ };+};++export const createPageFromTemplate = (+ state: BuilderState,+ input: {+ projectId: string;+ templateId: PageTemplate["id"];+ parentFolderId?: Folder["id"];+ name: Page["name"];+ path: Page["path"];+ },+ context: { createId: CreateId }+) => {+ const data = getRequiredWebstudioData(state);+ const template = data.pages.pageTemplates?.get(input.templateId);+ if (template === undefined) {+ return throwBuilderRuntimeError("NOT_FOUND", "Page template not found");+ }+ const parentFolderId = input.parentFolderId ?? data.pages.rootFolderId;+ if (data.pages.folders.has(parentFolderId) === false) {+ return throwBuilderRuntimeError("NOT_FOUND", "Parent folder not found");+ }+ if (+ isPathAvailable({+ pages: data.pages,+ path: input.path,+ parentFolderId,+ }) === false+ ) {+ return throwBuilderRuntimeError(+ "CONFLICT",+ `Page path "${input.path}" is already in use`+ );+ }++ const before = createWebstudioDataFromBuild({+ build: data,+ assets: Array.from(data.assets.values()),+ });+ const after = structuredClone(before);+ const pageId = insertPageFromTemplateMutable({+ templateId: input.templateId,+ source: { data: after },+ target: { data: after, folderId: parentFolderId },+ overrides: { name: input.name, path: input.path },+ projectId: input.projectId,+ createId: context.createId,+ });+ if (pageId === undefined) {+ return throwBuilderRuntimeError(+ "BAD_REQUEST",+ "Page could not be created from template"+ );+ }+ return createRuntimeMutation({+ payload: createWebstudioDataPatchPayload({ before, after }),+ result: { pageId },+ invalidatesNamespaces: [+ "pages",+ "assets",+ "dataSources",+ "resources",+ "instances",+ "props",+ "breakpoints",+ "styles",+ "styleSources",+ "styleSourceSelections",+ ],+ });};export const insertPageCopyFromFragmentsMutable = ({source,target,+ projectId,conflictResolution,+ contentModeCopyableProp,onBreakpointLimitMerge,+ createId = nanoid,}: {source: {page: Page;@@ -424,28 +723,42 @@ export const insertPageCopyFromFragmentsMutable = ({bodyFragment: WebstudioFragment;};target: { data: WebstudioData; folderId: Folder["id"] };+ projectId?: string;conflictResolution?: ConflictResolution;+ contentModeCopyableProp?: ContentModeCopyableProp;onBreakpointLimitMerge?: () => void;+ createId?: CreateId;}) => {const copied = copyPageFragmentsMutable({target: target.data,rootFragment: source.rootFragment,bodyFragment: source.bodyFragment,systemDataSourceId: source.page.systemDataSourceId,+ projectId,conflictResolution,+ contentModeCopyableProp,onBreakpointLimitMerge,+ createId,});if (copied === undefined) {return;}- return insertCopiedPageMutable({ page: source.page, copied, target });+ return insertCopiedPageMutable({+ page: source.page,+ copied,+ target,+ createId,+ });};export const insertTemplateCopyFromFragmentsMutable = ({source,target,+ projectId,conflictResolution,+ contentModeCopyableProp,onBreakpointLimitMerge,+ createId = nanoid,}: {source: {template: PageTemplate;@@ -453,16 +766,22 @@ export const insertTemplateCopyFromFragmentsMutable = ({bodyFragment: WebstudioFragment;};target: { data: WebstudioData };+ projectId?: string;conflictResolution?: ConflictResolution;+ contentModeCopyableProp?: ContentModeCopyableProp;onBreakpointLimitMerge?: () => void;+ createId?: CreateId;}) => {const copied = copyPageFragmentsMutable({target: target.data,rootFragment: source.rootFragment,bodyFragment: source.bodyFragment,systemDataSourceId: undefined,+ projectId,conflictResolution,+ contentModeCopyableProp,onBreakpointLimitMerge,+ createId,});if (copied === undefined) {return;@@ -471,6 +790,7 @@ export const insertTemplateCopyFromFragmentsMutable = ({template: source.template,copied,target,+ createId,});};@@ -613,15 +933,21 @@ const deduplicateFolderSlug = (export const insertFolderCopyFromDataMutable = ({source,target,+ projectId,conflictResolution,+ contentModeCopyableProp,onBreakpointLimitMerge,forceFolderCopySuffix = false,+ createId = nanoid,}: {source: FolderCopyData;target: { data: WebstudioData; parentFolderId: Folder["id"] };+ projectId?: string;conflictResolution?: ConflictResolution;+ contentModeCopyableProp?: ContentModeCopyableProp;onBreakpointLimitMerge?: () => void;forceFolderCopySuffix?: boolean;+ createId?: CreateId;}) => {const copyContext = {didCopyRootFragment: false,@@ -630,9 +956,12 @@ export const insertFolderCopyFromDataMutable = ({return insertFolderCopyFromDataWithContextMutable({source,target,+ projectId,conflictResolution,+ contentModeCopyableProp,onBreakpointLimitMerge,forceFolderCopySuffix,+ createId,copyContext,});};@@ -640,16 +969,22 @@ export const insertFolderCopyFromDataMutable = ({const insertFolderCopyFromDataWithContextMutable = ({source,target,+ projectId,conflictResolution,+ contentModeCopyableProp,onBreakpointLimitMerge,forceFolderCopySuffix,+ createId,copyContext,}: {source: FolderCopyData;target: { data: WebstudioData; parentFolderId: Folder["id"] };+ projectId?: string;conflictResolution?: ConflictResolution;+ contentModeCopyableProp?: ContentModeCopyableProp;onBreakpointLimitMerge?: () => void;forceFolderCopySuffix?: boolean;+ createId: CreateId;copyContext: { didCopyRootFragment: boolean };}) => {const parentFolder = target.data.pages.folders.get(target.parentFolderId);@@ -658,8 +993,8 @@ const insertFolderCopyFromDataWithContextMutable = ({}const newFolder: Folder = {- ...structuredClone(unwrap(source.folder)),- id: nanoid(),+ ...unwrap(source.folder),+ id: createId(),name: deduplicateFolderName(target.data.pages,target.parentFolderId,@@ -682,9 +1017,12 @@ const insertFolderCopyFromDataWithContextMutable = ({insertFolderCopyFromDataWithContextMutable({source: child,target: { data: target.data, parentFolderId: newFolder.id },+ projectId,conflictResolution,+ contentModeCopyableProp,onBreakpointLimitMerge,forceFolderCopySuffix,+ createId,copyContext,});continue;@@ -695,8 +1033,11 @@ const insertFolderCopyFromDataWithContextMutable = ({const pageId = insertPageCopyFromFragmentsMutable({source: { ...child, rootFragment },target: { data: target.data, folderId: newFolder.id },+ projectId,conflictResolution,+ contentModeCopyableProp,onBreakpointLimitMerge,+ createId,});if (rootFragment !== undefined && pageId !== undefined) {copyContext.didCopyRootFragment = true;diff --git a/packages/project-build/src/runtime/pages.test.ts b/packages/project-build/src/runtime/pages.test.tsnew file mode 100644index 0000000000..f97430d825--- /dev/null+++ b/packages/project-build/src/runtime/pages.test.ts@@ -0,0 +1,904 @@+import { describe, expect, test } from "vitest";+import { createDefaultPages } from "@webstudio-is/project-build";+import { migratePages } from "@webstudio-is/project-migrations/pages";+import {+ elementComponent,+ isRootFolder,+ ROOT_FOLDER_ID,+ type Folder,+ type Page,+ type Pages,+} from "@webstudio-is/sdk";+import { createBuilderStateFromSnapshot } from "../state/adapters";+import { createRootFolder } from "../shared/pages-utils";+import {+ createFolderCreatePayload,+ createFolderDeletePayload,+ createFolderUpdatePayload,+ createFolderValue,+ createPageCreatePayload,+ createPageDeletePayload,+ createPageRootInstance,+ createPageUpdatePatches,+ createPageUpdatePayload,+ createPageValue,+ findFolder,+ findPage,+ findParentFolderId,+ findSerializedPageByInput,+ getAllChildrenAndSelf,+ getFolderChildReparentPlan,+ getFolderDeletionTargets,+ getHomePageRootInstanceId,+ getParentFolderId,+ getSerializedPagePath,+ getSerializedPages,+ isPathAvailable,+ isSlugAvailable,+ pageFieldsInput,+ pageMetaInput,+ serializePageDetails,+ serializePageDetailsByInput,+ serializePageSummary,+} from "./pages";++const createPages = () =>+ migratePages({+ meta: {},+ homePage: {+ id: "home",+ name: "Home",+ path: "",+ title: `"Home"`,+ meta: {},+ rootInstanceId: "homeBody",+ },+ pages: [+ {+ id: "page",+ name: "Page",+ path: "/page",+ title: `"Page"`,+ meta: {+ language: "en",+ socialImageAssetId: "asset",+ },+ rootInstanceId: "pageBody",+ },+ ],+ folders: [+ createRootFolder(["home", "page", "folder"]),+ { id: "folder", name: "Folder", slug: "folder", children: [] },+ ],+ });++test("creates the default page root instance", () => {+ expect(createPageRootInstance("root")).toEqual({+ type: "instance",+ id: "root",+ component: "ws:element",+ tag: "body",+ children: [],+ });+});++test("creates a page with title defaulting to name", () => {+ expect(+ createPageValue({+ pageId: "page",+ name: "Page",+ path: "/page",+ rootInstanceId: "root",+ })+ ).toEqual({+ id: "page",+ name: "Page",+ path: "/page",+ title: "Page",+ rootInstanceId: "root",+ meta: {},+ });+});++test("creates page insertion payload", () => {+ const root = createPageRootInstance("root");+ const page = createPageValue({+ pageId: "page",+ name: "Page",+ path: "/page",+ rootInstanceId: root.id,+ });++ expect(+ createPageCreatePayload({+ page,+ parentFolderId: "folder",+ parentChildIndex: 2,+ rootInstance: root,+ })+ ).toEqual([+ {+ namespace: "pages",+ patches: [+ { op: "add", path: ["pages", "page"], value: page },+ {+ op: "add",+ path: ["folders", "folder", "children", 2],+ value: "page",+ },+ ],+ },+ {+ namespace: "instances",+ patches: [{ op: "add", path: ["root"], value: root }],+ },+ ]);+});++describe("serialized page helpers", () => {+ test("serializes page summary and details with parent folder", () => {+ const pages = createDefaultPages({+ rootInstanceId: "root",+ homePageId: "home",+ });+ const page = pages.pages.get("home");+ if (page === undefined) {+ throw new Error("Expected page");+ }+ page.meta = {+ description: "Description",+ excludePageFromSearch: "true",+ status: "200",+ auth: { method: "basic", login: "editor", password: "password123" },+ };+ const serializedPages = getSerializedPages({ pages });+ const serializedPage = serializedPages.pages.find(+ (item) => item.id === page.id+ );+ if (serializedPage === undefined) {+ throw new Error("Expected serialized page");+ }++ expect(findParentFolderId(serializedPages.folders, page.id)).toBe(+ pages.rootFolderId+ );+ expect(findPage(pages, "home")).toBe(page);+ expect(findPage(pages, "missing")).toBeUndefined();+ expect(findFolder(pages, pages.rootFolderId)?.id).toBe(pages.rootFolderId);+ expect(findFolder(pages, "missing")).toBeUndefined();+ expect(serializePageSummary(serializedPages, serializedPage)).toEqual({+ id: "home",+ name: "Home",+ path: "",+ localPath: "",+ title: '"Home"',+ rootInstanceId: "root",+ parentFolderId: pages.rootFolderId,+ isHome: true,+ });+ expect(serializePageDetails(serializedPages, serializedPage).meta).toEqual({+ description: "Description",+ language: undefined,+ redirect: undefined,+ status: "200",+ socialImageUrl: undefined,+ socialImageAssetId: undefined,+ excludePageFromSearch: true,+ documentType: "html",+ content: undefined,+ auth: { method: "basic", login: "editor", password: "password123" },+ custom: undefined,+ });+ expect(getHomePageRootInstanceId(pages)).toBe("root");+ expect(+ findSerializedPageByInput(serializedPages, { pagePath: "" })?.id+ ).toBe("home");+ expect(+ findSerializedPageByInput(serializedPages, { pagePath: "/" })?.id+ ).toBe("home");+ expect(serializePageDetailsByInput({ pages }, { pageId: "home" })).toEqual(+ expect.objectContaining({+ id: "home",+ path: "",+ isHome: true,+ })+ );+ expect(+ serializePageDetailsByInput({ pages }, { pageId: "missing" })+ ).toBeUndefined();+ });++ test("finds serialized pages by full folder-aware path", () => {+ const pages = createDefaultPages({+ rootInstanceId: "root",+ homePageId: "home",+ });+ pages.folders.set("folder", {+ id: "folder",+ name: "Blog",+ slug: "blog",+ children: ["post"],+ });+ pages.pages.set("post", {+ id: "post",+ name: "Post",+ path: "/first-post",+ title: '"Post"',+ rootInstanceId: "post-root",+ meta: {},+ });+ pages.folders.get(pages.rootFolderId)?.children.push("folder");++ const serializedPages = getSerializedPages({ pages });+ const post = serializedPages.pages.find((page) => page.id === "post");+ if (post === undefined) {+ throw new Error("Expected post page");+ }++ expect(getSerializedPagePath(serializedPages, post)).toBe(+ "/blog/first-post"+ );+ expect(+ findSerializedPageByInput(serializedPages, {+ pagePath: "/blog/first-post",+ })?.id+ ).toBe("post");+ expect(+ serializePageDetailsByInput({ pages }, { pagePath: "/blog/first-post" })+ ).toMatchObject({+ id: "post",+ path: "/blog/first-post",+ localPath: "/first-post",+ });+ });+});++describe("createPageDeletePayload", () => {+ test("removes page, folder child reference, and page instances", () => {+ const pages = createDefaultPages({+ rootInstanceId: "body",+ homePageId: "home",+ });+ pages.pages.set("page", {+ id: "page",+ name: "Page",+ path: "/page",+ title: '"Page"',+ rootInstanceId: "page-root",+ meta: {},+ });+ pages.folders.get(pages.rootFolderId)?.children.push("page");++ const state = createBuilderStateFromSnapshot({+ pages,+ instances: [+ [+ "page-root",+ {+ type: "instance",+ id: "page-root",+ component: elementComponent,+ children: [{ type: "id", value: "child" }],+ },+ ],+ [+ "child",+ {+ type: "instance",+ id: "child",+ component: elementComponent,+ children: [],+ },+ ],+ ],+ props: [],+ dataSources: [],+ styleSources: [],+ styleSourceSelections: [],+ styles: [],+ });+ const deleteState = {+ pages: state.pages!,+ instances: state.instances!,+ props: state.props!,+ dataSources: state.dataSources!,+ styleSources: state.styleSources!,+ styleSourceSelections: state.styleSourceSelections!,+ styles: state.styles!,+ };++ expect(+ createPageDeletePayload({+ state: deleteState,+ page: pages.pages.get("page")!,+ parentFolderId: pages.rootFolderId,+ })[0]+ ).toEqual({+ namespace: "pages",+ patches: [+ { op: "remove", path: ["pages", "page"] },+ {+ op: "remove",+ path: ["folders", pages.rootFolderId, "children", 1],+ },+ ],+ });+ });+});++describe("createFolderCreatePayload", () => {+ test("creates folder insertion payload", () => {+ const folder = createFolderValue({+ folderId: "folder",+ name: "Folder",+ slug: "folder",+ });++ expect(+ createFolderCreatePayload({+ folder,+ parentFolderId: "root",+ parentChildIndex: 1,+ })+ ).toEqual([+ {+ namespace: "pages",+ patches: [+ { op: "add", path: ["folders", "folder"], value: folder },+ {+ op: "add",+ path: ["folders", "root", "children", 1],+ value: "folder",+ },+ ],+ },+ ]);+ });+});++describe("createFolderUpdatePayload", () => {+ test("creates field and reparent patches", () => {+ const pages = createDefaultPages({+ rootInstanceId: "body",+ homePageId: "home",+ });+ pages.folders.set("folder", {+ id: "folder",+ name: "Folder",+ slug: "folder",+ children: [],+ });+ pages.folders.set("next", {+ id: "next",+ name: "Next",+ slug: "next",+ children: [],+ });+ pages.folders.get(pages.rootFolderId)?.children.push("folder", "next");++ expect(+ createFolderUpdatePayload({+ folder: pages.folders.get("folder")!,+ pages,+ values: {+ name: "Updated",+ slug: "updated",+ parentFolderId: "next",+ },+ })+ ).toEqual([+ {+ namespace: "pages",+ patches: [+ {+ op: "replace",+ path: ["folders", "folder", "name"],+ value: "Updated",+ },+ {+ op: "replace",+ path: ["folders", "folder", "slug"],+ value: "updated",+ },+ {+ op: "remove",+ path: ["folders", pages.rootFolderId, "children", 1],+ },+ {+ op: "add",+ path: ["folders", "next", "children", 0],+ value: "folder",+ },+ ],+ },+ ]);+ });+});++describe("createFolderDeletePayload", () => {+ test("removes folder subtree, pages, child reference, and page instances", () => {+ const pages = createDefaultPages({+ rootInstanceId: "body",+ homePageId: "home",+ });+ pages.folders.set("folder", {+ id: "folder",+ name: "Folder",+ slug: "folder",+ children: ["page"],+ });+ pages.pages.set("page", {+ id: "page",+ name: "Page",+ path: "/page",+ title: '"Page"',+ rootInstanceId: "page-root",+ meta: {},+ });+ pages.folders.get(pages.rootFolderId)?.children.push("folder");++ const state = createBuilderStateFromSnapshot({+ pages,+ instances: [+ [+ "page-root",+ {+ type: "instance",+ id: "page-root",+ component: elementComponent,+ children: [{ type: "id", value: "child" }],+ },+ ],+ [+ "child",+ {+ type: "instance",+ id: "child",+ component: elementComponent,+ children: [],+ },+ ],+ ],+ props: [],+ dataSources: [],+ styleSources: [],+ styleSourceSelections: [],+ styles: [],+ });+ const deleteState = {+ pages: state.pages!,+ instances: state.instances!,+ props: state.props!,+ dataSources: state.dataSources!,+ styleSources: state.styleSources!,+ styleSourceSelections: state.styleSourceSelections!,+ styles: state.styles!,+ };++ const result = createFolderDeletePayload({+ state: deleteState,+ folder: pages.folders.get("folder")!,+ parentFolderId: pages.rootFolderId,+ });++ expect(result.folderIds).toEqual(["folder"]);+ expect(result.pageIds).toEqual(["page"]);+ expect(result.payload[0]).toEqual({+ namespace: "pages",+ patches: [+ {+ op: "remove",+ path: ["folders", pages.rootFolderId, "children", 1],+ },+ { op: "remove", path: ["pages", "page"] },+ { op: "remove", path: ["folders", "folder"] },+ ],+ });+ expect(result.payload).toContainEqual({+ namespace: "instances",+ patches: [+ { op: "remove", path: ["page-root"] },+ { op: "remove", path: ["child"] },+ ],+ });+ });+});++describe("page input schemas", () => {+ test("parse page fields and metadata used by the API", () => {+ expect(+ pageFieldsInput.parse({+ name: "About",+ path: "/about",+ title: "About",+ parentFolderId: "folder",+ meta: {+ description: "About us",+ excludePageFromSearch: true,+ documentType: "html",+ custom: [{ property: "og:title", content: "About" }],+ },+ })+ ).toEqual({+ name: "About",+ path: "/about",+ title: "About",+ parentFolderId: "folder",+ meta: {+ description: "About us",+ excludePageFromSearch: true,+ documentType: "html",+ custom: [{ property: "og:title", content: "About" }],+ },+ });+ });++ test("reject empty page names and invalid document types", () => {+ expect(() => pageFieldsInput.parse({ name: "" })).toThrow();+ expect(() => pageMetaInput.parse({ documentType: "json" })).toThrow();+ });+});++describe("createPageUpdatePatches", () => {+ test("creates field, meta, and folder patches", () => {+ const pages = createPages();+ const page = pages.pages.get("page");++ expect(+ createPageUpdatePatches({+ input: {+ name: "Updated",+ path: "/updated",+ meta: {+ language: "",+ excludePageFromSearch: true,+ },+ parentFolderId: "folder",+ },+ page: page!,+ pages,+ })+ ).toEqual([+ {+ op: "replace",+ path: ["pages", "page", "name"],+ value: "Updated",+ },+ {+ op: "replace",+ path: ["pages", "page", "path"],+ value: "/updated",+ },+ {+ op: "remove",+ path: ["pages", "page", "meta", "language"],+ },+ {+ op: "add",+ path: ["pages", "page", "meta", "excludePageFromSearch"],+ value: "true",+ },+ {+ op: "remove",+ path: ["folders", pages.rootFolderId, "children", 1],+ },+ {+ op: "add",+ path: ["folders", "folder", "children", 0],+ value: "page",+ },+ ]);+ });++ test("does not remove omitted metadata fields", () => {+ const pages = createPages();+ const page = pages.pages.get("page");++ expect(+ createPageUpdatePatches({+ input: {+ meta: {+ description: "Updated",+ },+ },+ page: page!,+ pages,+ })+ ).toEqual([+ {+ op: "add",+ path: ["pages", "page", "meta", "description"],+ value: "Updated",+ },+ ]);+ });+});++describe("createPageUpdatePayload", () => {+ test("wraps page update patches in a build payload", () => {+ const pages = createPages();+ const page = pages.pages.get("page");++ expect(+ createPageUpdatePayload({+ input: { name: "Updated" },+ page: page!,+ pages,+ })+ ).toEqual([+ {+ namespace: "pages",+ patches: [+ {+ op: "replace",+ path: ["pages", "page", "name"],+ value: "Updated",+ },+ ],+ },+ ]);+ });++ test("returns empty payload for noop updates", () => {+ const pages = createPages();+ const page = pages.pages.get("page");++ expect(+ createPageUpdatePayload({+ input: {},+ page: page!,+ pages,+ })+ ).toEqual([]);+ });+});++const toMap = <T extends { id: string }>(list: T[]) =>+ new Map(list.map((item) => [item.id, item]));++const createRuntimePages = () => {+ const data = createDefaultPages({+ rootInstanceId: "rootInstanceId",+ homePageId: "homePageId",+ });++ const { pages, folders } = data;++ function f(id: string, children?: Array<Page | Folder>): Folder;+ function f(id: string, slug: string, children?: Array<Page | Folder>): Folder;+ function f(id: string, slug?: unknown, children?: unknown) {+ if (Array.isArray(slug)) {+ children = slug;+ slug = id;+ }+ const folder = {+ id,+ name: id,+ slug: slug ?? id,+ children: register((children as Array<Page | Folder>) ?? [], false),+ };++ return folder;+ }++ const p = (id: string, path: string): Page => {+ const page = {+ id,+ meta: {},+ name: id,+ path,+ rootInstanceId: "rootInstanceId",+ title: `"${id}"`,+ };+ return page;+ };++ const register = (children: Array<Page | Folder>, root: boolean = true) => {+ const childIds = [];+ const rootFolder = Array.from(folders.values()).find(isRootFolder);++ for (const child of children) {+ childIds.push(child.id);+ if ("meta" in child) {+ pages.set(child.id, child);+ continue;+ }+ folders.set(child.id, child);++ if (root) {+ rootFolder?.children.push(child.id);+ }+ }++ return childIds;+ };++ return { f, p, register, pages: data };+};++describe("folder child parent helpers", () => {+ test("finds parent folder id for a child", () => {+ const { pages, f, p, register } = createRuntimePages();+ const page = p("page", "/page");+ register([f("folder", [page])]);++ expect(getParentFolderId(pages.folders, page.id)).toBe("folder");+ expect(getParentFolderId(pages.folders, "missing")).toBeUndefined();+ });++ test("plans cross-folder reparent", () => {+ const { pages, f, p, register } = createRuntimePages();+ const page = p("page", "/page");+ register([f("folder", [page]), f("target", [])]);++ expect(+ getFolderChildReparentPlan(pages.folders, page.id, "target")+ ).toEqual({+ currentFolderId: "folder",+ currentIndex: 0,+ nextFolderId: "target",+ nextIndex: 0,+ });+ });++ test("does not plan same-folder reparent", () => {+ const { pages, f, p, register } = createRuntimePages();+ const page = p("page", "/page");+ register([f("folder", [page])]);++ expect(+ getFolderChildReparentPlan(pages.folders, page.id, "folder")+ ).toBeUndefined();+ });+});++describe("isSlugAvailable", () => {+ const {+ pages: { folders },+ register,+ f,+ } = createRuntimePages();++ register([+ f("folder1", [f("folder1-1")]),+ f("folder2-1", ""),+ f("folder2-2", ""),+ ]);++ const rootFolder = Array.from(folders.values()).find(isRootFolder)!;++ test("available in the root", () => {+ expect(isSlugAvailable("folder", folders, rootFolder.id)).toBe(true);+ });++ test("not available in the root", () => {+ expect(isSlugAvailable("folder1", folders, rootFolder.id)).toBe(false);+ });++ test("available in folder1", () => {+ expect(isSlugAvailable("folder", folders, "folder1")).toBe(true);+ });++ test("not available in folder1", () => {+ expect(isSlugAvailable("folder1-1", folders, "folder1")).toBe(false);+ });++ test("existing folder can have a matching slug when its the same id/folder", () => {+ expect(isSlugAvailable("folder1-1", folders, "folder1", "folder1-1")).toBe(+ true+ );+ });++ test("empty folder slug can be defined multiple times", () => {+ expect(isSlugAvailable("", folders, "rootInstanceId")).toBe(true);+ });+});++describe("isPathAvailable", () => {+ const { f, p, register, pages } = createRuntimePages();++ register([+ f("folder1", [p("page1", "/page")]),+ f("folder2", [p("page2", "/page")]),+ f("/", [p("page3", "/page")]),+ ]);++ test("/folder2/page existing page", () => {+ expect(+ isPathAvailable({+ pages,+ path: "/page",+ parentFolderId: "folder2",+ pageId: "page2",+ })+ ).toBe(true);+ });++ test("/folder2/page new page", () => {+ expect(+ isPathAvailable({ pages, path: "/page", parentFolderId: "folder2" })+ ).toBe(false);+ });++ test("/folder2/page1 new page", () => {+ expect(+ isPathAvailable({ pages, path: "/page1", parentFolderId: "folder2" })+ ).toBe(true);+ });++ test("/page new page", () => {+ expect(isPathAvailable({ pages, path: "/page", parentFolderId: "/" })).toBe(+ false+ );+ });+});++describe("getAllChildrenAndSelf", () => {+ const folders = toMap<Folder>([+ { id: "1", name: "1", slug: "1", children: ["2"] },+ { id: "2", name: "2", slug: "2", children: ["3", "page1"] },+ { id: "3", name: "3", slug: "3", children: ["page2"] },+ ]);++ test("get nested folders", () => {+ const result = getAllChildrenAndSelf("1", folders, "folder");+ expect(result).toEqual(["1", "2", "3"]);+ });++ test("get nested pages", () => {+ const result = getAllChildrenAndSelf("1", folders, "page");+ expect(result).toEqual(["page2", "page1"]);+ });+});++describe("getFolderDeletionTargets", () => {+ const pages = (): Pages => ({+ homePageId: "homePageId",+ rootFolderId: ROOT_FOLDER_ID,+ pages: new Map(),+ folders: toMap<Folder>([+ {+ id: ROOT_FOLDER_ID,+ name: "Root",+ slug: "",+ children: ["2"],+ },+ {+ id: "2",+ name: "2",+ slug: "2",+ children: ["3", "page1"],+ },+ {+ id: "3",+ name: "3",+ slug: "3",+ children: [],+ },+ ]),+ });++ test("returns nested folders and pages", () => {+ expect(getFolderDeletionTargets("2", pages())).toEqual({+ folderIds: ["2", "3"],+ pageIds: ["page1"],+ });+ });++ test("returns no targets for root folder", () => {+ expect(getFolderDeletionTargets(ROOT_FOLDER_ID, pages())).toEqual({+ folderIds: [],+ pageIds: [],+ });+ });++ test("returns no targets for folder containing home page", () => {+ const pagesData = pages();+ pagesData.folders.get("2")?.children.push("homePageId");++ expect(getFolderDeletionTargets("2", pagesData)).toEqual({+ folderIds: [],+ pageIds: [],+ });+ });+});diff --git a/packages/project-build/src/runtime/pages.ts b/packages/project-build/src/runtime/pages.tsnew file mode 100644index 0000000000..de289a91a1--- /dev/null+++ b/packages/project-build/src/runtime/pages.ts@@ -0,0 +1,1108 @@+import {+ elementComponent,+ findParentFolderByChildId,+ getAllPages,+ getPagePath,+ type Folder,+ type Page,+ pageAuth,+ type PageAuth,+ type Pages,+} from "@webstudio-is/sdk";+import { serializePages } from "@webstudio-is/project-migrations/pages";+import { z } from "zod";+import {+ compactBuilderPatchPayload,+ type BuilderPatchChange,+} from "../contracts/patch";+import type { BuilderState } from "../state/builder-state";+import type { BuilderRuntimeContext } from "./context";+import { throwBuilderRuntimeError } from "./errors";+import {+ collectExclusiveInstanceIds,+ createInstanceCleanupPayload,+} from "./instances";+import { createRuntimeMutation } from "./mutation";++type SerializedPages = ReturnType<typeof serializePages>;+type SerializedPage = SerializedPages["pages"][number];++export type SerializedPageSummary = {+ id: Page["id"];+ name: Page["name"];+ path: string;+ localPath: Page["path"];+ title: Page["title"];+ rootInstanceId: Page["rootInstanceId"];+ parentFolderId: Folder["id"] | undefined;+ isHome: boolean;+};++export type SerializedPageDetails = SerializedPageSummary & {+ meta: {+ description: Page["meta"]["description"];+ language: Page["meta"]["language"];+ redirect: Page["meta"]["redirect"];+ status: Page["meta"]["status"];+ socialImageUrl: Page["meta"]["socialImageUrl"];+ socialImageAssetId: Page["meta"]["socialImageAssetId"];+ excludePageFromSearch: boolean | undefined;+ documentType: NonNullable<Page["meta"]["documentType"]>;+ content: Page["meta"]["content"];+ auth: Page["meta"]["auth"];+ custom: Page["meta"]["custom"];+ };+};++export const getRequiredPages = (state: Pick<BuilderState, "pages">): Pages => {+ if (state.pages === undefined) {+ return throwBuilderRuntimeError(+ "BAD_REQUEST",+ "Pages namespace is missing"+ );+ }+ return state.pages;+};++export const findPage = (pages: Pick<Pages, "pages">, pageId: Page["id"]) =>+ pages.pages.get(pageId);++export const findFolder = (+ pages: Pick<Pages, "folders">,+ folderId: Folder["id"]+) => pages.folders.get(folderId);++export const getSerializedPages = (+ state: Pick<BuilderState, "pages">+): SerializedPages => serializePages(getRequiredPages(state));++export const findParentFolderId = (+ folders: SerializedPages["folders"],+ childId: Page["id"] | Folder["id"]+) => {+ const map = new Map(folders.map((folder) => [folder.id, folder]));+ for (const folder of map.values()) {+ if (folder.children.includes(childId)) {+ return folder.id;+ }+ }+};++const joinPath = (...parts: string[]) => parts.join("").replace(/\/+/g, "/");++const getSerializedFolderPath = (+ pages: SerializedPages,+ folderId: Folder["id"] | undefined+): string => {+ if (folderId === undefined || folderId === pages.rootFolderId) {+ return "";+ }+ const folder = pages.folders.find((folder) => folder.id === folderId);+ if (folder === undefined) {+ return "";+ }+ return joinPath(+ getSerializedFolderPath(pages, findParentFolderId(pages.folders, folderId)),+ `/${folder.slug}`+ );+};++export const getSerializedPagePath = (+ pages: SerializedPages,+ page: SerializedPage+) =>+ joinPath(+ getSerializedFolderPath(pages, findParentFolderId(pages.folders, page.id)),+ page.path+ );++export const normalizeSerializedPagePath = (path: string) =>+ path === "/" ? "" : path;++export const serializePageSummary = (+ pages: SerializedPages,+ page: SerializedPage+): SerializedPageSummary => ({+ id: page.id,+ name: page.name,+ path: getSerializedPagePath(pages, page),+ localPath: page.path,+ title: page.title,+ rootInstanceId: page.rootInstanceId,+ parentFolderId: findParentFolderId(pages.folders, page.id),+ isHome: page.id === pages.homePageId,+});++export const serializePageDetails = (+ pages: SerializedPages,+ page: SerializedPage+): SerializedPageDetails => ({+ ...serializePageSummary(pages, page),+ meta: {+ description: page.meta.description,+ language: page.meta.language,+ redirect: page.meta.redirect,+ status: page.meta.status,+ socialImageUrl: page.meta.socialImageUrl,+ socialImageAssetId: page.meta.socialImageAssetId,+ excludePageFromSearch:+ page.meta.excludePageFromSearch === undefined+ ? undefined+ : page.meta.excludePageFromSearch === "true",+ documentType: page.meta.documentType ?? "html",+ content: page.meta.content,+ auth: page.meta.auth,+ custom: page.meta.custom,+ },+});++export const findSerializedPageByInput = (+ pages: SerializedPages,+ input: { pageId?: string; pagePath?: string }+) => {+ if (input.pageId !== undefined) {+ return pages.pages.find((page) => page.id === input.pageId);+ }+ if (input.pagePath !== undefined) {+ const pagePath = normalizeSerializedPagePath(input.pagePath);+ return pages.pages.find(+ (page) => getSerializedPagePath(pages, page) === pagePath+ );+ }+};++export const serializePageDetailsByInput = (+ state: Pick<BuilderState, "pages">,+ input: { pageId?: string; pagePath?: string }+) => {+ const pages = getSerializedPages(state);+ const page = findSerializedPageByInput(pages, input);+ return page === undefined ? undefined : serializePageDetails(pages, page);+};++export const getHomePageRootInstanceId = (pages: Pages) =>+ pages.pages.get(pages.homePageId)?.rootInstanceId;++export const listPages = (+ state: Pick<BuilderState, "pages">,+ input: { includeFolders?: boolean } = {}+) => {+ const pages = getSerializedPages(state);+ return {+ pages: pages.pages.map((page) => serializePageSummary(pages, page)),+ folders: input.includeFolders === true ? pages.folders : undefined,+ };+};++export const getPage = (+ state: Pick<BuilderState, "pages">,+ input: { pageId: string }+) => {+ const page = serializePageDetailsByInput(state, input);+ if (page === undefined) {+ return throwBuilderRuntimeError("NOT_FOUND", "Page not found");+ }+ return page;+};++export const getPageByPath = (+ state: Pick<BuilderState, "pages">,+ input: { path: string }+) => {+ const page = serializePageDetailsByInput(state, {+ pagePath: input.path,+ });+ if (page === undefined) {+ return throwBuilderRuntimeError("NOT_FOUND", "Page not found");+ }+ return page;+};++export const listFolders = (+ state: Pick<BuilderState, "pages">,+ input: { includePages?: boolean } = {}+) => {+ const pages = getSerializedPages(state);+ return {+ folders: pages.folders.map((folder) => ({+ id: folder.id,+ name: folder.name,+ slug: folder.slug,+ parentFolderId: findParentFolderId(pages.folders, folder.id),+ children: folder.children,+ })),+ pages:+ input.includePages === true+ ? pages.pages.map((page) => serializePageSummary(pages, page))+ : undefined,+ };+};++export const isSlugAvailable = (+ slug: string,+ folders: Pages["folders"],+ parentFolderId: Folder["id"],+ folderId?: Folder["id"]+) => {+ if (slug === "") {+ return true;+ }+ const parentFolder = folders.get(parentFolderId);+ if (parentFolder === undefined) {+ return false;+ }++ return (+ parentFolder.children.some(+ (id) => folders.get(id)?.slug === slug && id !== folderId+ ) === false+ );+};++export const isPathAvailable = ({+ pages,+ path,+ parentFolderId,+ pageId,+}: {+ pages: Pages;+ path: Page["path"];+ parentFolderId: Folder["id"];+ pageId?: Page["id"];+}) => {+ const map = new Map<Page["path"], Page>();+ for (const page of getAllPages(pages)) {+ map.set(getPagePath(page.id, pages), page);+ }+ const folderPath = getPagePath(parentFolderId, pages);+ const pagePath = folderPath === "/" ? path : `${folderPath}${path}`;+ const existingPage = map.get(pagePath);+ if (pageId && existingPage?.id === pageId) {+ return true;+ }+ return existingPage === undefined;+};++export const getAllChildrenAndSelf = (+ id: Folder["id"] | Page["id"],+ folders: Pages["folders"],+ filter: "folder" | "page"+) => {+ const child = folders.get(id);+ const children: Array<Folder["id"] | Page["id"]> = [];+ const type = child === undefined ? "page" : "folder";++ if (type === filter) {+ children.push(id);+ }++ if (child) {+ for (const childId of child.children) {+ children.push(...getAllChildrenAndSelf(childId, folders, filter));+ }+ }+ return children;+};++export const getFolderDeletionTargets = (+ folderId: Folder["id"],+ pages: Pages+) => {+ const folder = pages.folders.get(folderId);+ if (folder === undefined || folder.id === pages.rootFolderId) {+ return {+ folderIds: [],+ pageIds: [],+ };+ }+ const folderIds = getAllChildrenAndSelf(folderId, pages.folders, "folder");+ const pageIds = getAllChildrenAndSelf(folderId, pages.folders, "page");+ if (pageIds.includes(pages.homePageId)) {+ return {+ folderIds: [],+ pageIds: [],+ };+ }+ return {+ folderIds,+ pageIds,+ };+};++export const getParentFolderId = (+ folders: Pages["folders"],+ childId: Page["id"] | Folder["id"]+) => findParentFolderByChildId(childId, folders)?.id;++export const createFolderValue = ({+ folderId,+ name,+ slug,+}: {+ folderId: Folder["id"];+ name: Folder["name"];+ slug: Folder["slug"];+}): Folder => ({+ id: folderId,+ name,+ slug,+ children: [],+});++export const createFolderCreatePayload = ({+ folder,+ parentFolderId,+ parentChildIndex,+}: {+ folder: Folder;+ parentFolderId: Folder["id"];+ parentChildIndex: number;+}): BuilderPatchChange[] => [+ {+ namespace: "pages",+ patches: [+ {+ op: "add",+ path: ["folders", folder.id],+ value: folder,+ },+ {+ op: "add",+ path: ["folders", parentFolderId, "children", parentChildIndex],+ value: folder.id,+ },+ ],+ },+];++export const getFolderChildReparentPlan = (+ folders: Pages["folders"],+ childId: Page["id"] | Folder["id"],+ nextFolderId: Folder["id"],+ nextPosition?: number+) => {+ const currentFolder = findParentFolderByChildId(childId, folders);+ const nextFolder = folders.get(nextFolderId);+ if (currentFolder === undefined || nextFolder === undefined) {+ return;+ }+ if (currentFolder.id === nextFolder.id) {+ return;+ }+ const currentIndex = currentFolder.children.indexOf(childId);+ if (currentIndex === -1) {+ return;+ }+ return {+ currentFolderId: currentFolder.id,+ currentIndex,+ nextFolderId: nextFolder.id,+ nextIndex: nextPosition ?? nextFolder.children.length,+ };+};++export const createFolderUpdatePayload = ({+ folder,+ pages,+ values,+}: {+ folder: Folder;+ pages: Pages;+ values: Partial<{+ name: Folder["name"];+ slug: Folder["slug"];+ parentFolderId: Folder["id"];+ }>;+}): BuilderPatchChange[] => {+ const patches: BuilderPatchChange["patches"] = [];+ if (values.name !== undefined) {+ patches.push({+ op: "replace",+ path: ["folders", folder.id, "name"],+ value: values.name,+ });+ }+ if (values.slug !== undefined) {+ patches.push({+ op: "replace",+ path: ["folders", folder.id, "slug"],+ value: values.slug,+ });+ }+ if (values.parentFolderId !== undefined) {+ const plan = getFolderChildReparentPlan(+ pages.folders,+ folder.id,+ values.parentFolderId+ );+ if (plan !== undefined) {+ patches.push({+ op: "remove",+ path: ["folders", plan.currentFolderId, "children", plan.currentIndex],+ });+ patches.push({+ op: "add",+ path: ["folders", plan.nextFolderId, "children", plan.nextIndex],+ value: folder.id,+ });+ }+ }+ return compactBuilderPatchPayload([{ namespace: "pages", patches }]);+};++const getFolderOrThrow = (pages: Pages, folderId: string) => {+ const folder = findFolder(pages, folderId);+ if (folder === undefined) {+ return throwBuilderRuntimeError("NOT_FOUND", "Folder not found");+ }+ return folder;+};++const getParentFolderIdOrThrow = (pages: Pages, childId: string) => {+ const parentFolderId = getParentFolderId(pages.folders, childId);+ if (parentFolderId === undefined) {+ return throwBuilderRuntimeError("NOT_FOUND", "Parent folder not found");+ }+ return parentFolderId;+};++export const createFolder = (+ state: Pick<BuilderState, "pages">,+ input: {+ folderId?: string;+ name: string;+ slug: string;+ parentFolderId?: string;+ },+ context: BuilderRuntimeContext+) => {+ const pages = getRequiredPages(state);+ const parentFolderId = input.parentFolderId ?? pages.rootFolderId;+ const parentFolder = getFolderOrThrow(pages, parentFolderId);+ const folderId = input.folderId ?? context.createId();+ if (pages.folders.has(folderId)) {+ return throwBuilderRuntimeError("CONFLICT", "Folder id already exists");+ }+ if (+ isSlugAvailable(input.slug, pages.folders, parentFolderId, folderId) ===+ false+ ) {+ return throwBuilderRuntimeError(+ "CONFLICT",+ `Folder slug "${input.slug}" is already in use`+ );+ }+ const folder = createFolderValue({+ folderId,+ name: input.name,+ slug: input.slug,+ });+ return createRuntimeMutation({+ payload: createFolderCreatePayload({+ folder,+ parentFolderId,+ parentChildIndex: parentFolder.children.length,+ }),+ result: { folderId },+ invalidatesNamespaces: ["pages"],+ });+};++export const createPageRootInstance = (rootInstanceId: string) => ({+ type: "instance" as const,+ id: rootInstanceId,+ component: elementComponent,+ tag: "body",+ children: [],+});++export const createPageValue = ({+ pageId,+ name,+ path,+ title = name,+ rootInstanceId,+ meta = {},+}: {+ pageId: Page["id"];+ name: Page["name"];+ path: Page["path"];+ title?: Page["title"];+ rootInstanceId: string;+ meta?: Page["meta"];+}): Page => ({+ id: pageId,+ name,+ path,+ title,+ rootInstanceId,+ meta,+});++type PageMeta = Page["meta"];++const emptyStringRemovesMetaFields = new Set<keyof PageMeta>([+ "language",+ "redirect",+ "socialImageAssetId",+ "socialImageUrl",+]);++export const normalizePageMetaValue = <Name extends keyof PageMeta>(+ name: Name,+ value: PageMeta[Name]+) => {+ if (value === "" && emptyStringRemovesMetaFields.has(name)) {+ return undefined;+ }+ return value;+};++type PageMetaPatchInput = Partial<{+ description: Page["meta"]["description"];+ language: Page["meta"]["language"];+ redirect: Page["meta"]["redirect"];+ socialImageUrl: Page["meta"]["socialImageUrl"];+ socialImageAssetId: Page["meta"]["socialImageAssetId"];+ excludePageFromSearch: boolean;+ documentType: Page["meta"]["documentType"];+ content: Page["meta"]["content"];+ status: Page["meta"]["status"];+ auth: PageAuth;+ custom: Page["meta"]["custom"];+}>;++type PageFieldsPatchInput = Partial<{+ name: Page["name"];+ path: Page["path"];+ title: Page["title"];+ parentFolderId: string;+ meta: PageMetaPatchInput;+}>;++export const pageMetaInput = z.object({+ description: z.string().optional(),+ language: z.string().optional(),+ redirect: z.string().optional(),+ socialImageUrl: z.string().optional(),+ socialImageAssetId: z.string().optional(),+ excludePageFromSearch: z.boolean().optional(),+ documentType: z.enum(["html", "xml", "text"]).optional(),+ content: z.string().optional(),+ status: z.string().optional(),+ auth: pageAuth.optional(),+ custom: z+ .array(z.object({ property: z.string(), content: z.string() }))+ .optional(),+});++export const pageFieldsInput = z.object({+ name: z.string().min(1).optional(),+ path: z.string().optional(),+ title: z.string().optional(),+ parentFolderId: z.string().optional(),+ meta: pageMetaInput.optional(),+});++export const pageMetaToPatchValue = (meta: PageMetaPatchInput) => {+ const result: Record<string, unknown> = {};+ for (const [name, value] of Object.entries(meta)) {+ result[name] =+ name === "excludePageFromSearch"+ ? String(value)+ : normalizePageMetaValue(name as keyof PageMeta, value as never);+ }+ return result;+};++export const createPageCreatePayload = ({+ page,+ parentFolderId,+ parentChildIndex,+ rootInstance,+}: {+ page: Page;+ parentFolderId: string;+ parentChildIndex: number;+ rootInstance: ReturnType<typeof createPageRootInstance>;+}): BuilderPatchChange[] => [+ {+ namespace: "pages",+ patches: [+ { op: "add", path: ["pages", page.id], value: page },+ {+ op: "add",+ path: ["folders", parentFolderId, "children", parentChildIndex],+ value: page.id,+ },+ ],+ },+ {+ namespace: "instances",+ patches: [+ {+ op: "add",+ path: [rootInstance.id],+ value: rootInstance,+ },+ ],+ },+];++export const createPageUpdatePatches = ({+ input,+ page,+ pages,+}: {+ input: PageFieldsPatchInput;+ page: Page;+ pages: Pages;+}) => {+ const patches: BuilderPatchChange["patches"] = [];+ const replace = (path: Array<string | number>, value: unknown) => {+ patches.push({ op: "replace", path, value });+ };++ if (input.name !== undefined) {+ replace(["pages", page.id, "name"], input.name);+ }+ if (input.path !== undefined) {+ replace(+ ["pages", page.id, "path"],+ page.id === pages.homePageId ? "" : input.path+ );+ }+ if (input.title !== undefined) {+ replace(["pages", page.id, "title"], input.title);+ }+ if (input.meta !== undefined) {+ for (const [name, value] of Object.entries(+ pageMetaToPatchValue(input.meta)+ )) {+ if (value === undefined) {+ if (Object.hasOwn(page.meta, name)) {+ patches.push({+ op: "remove",+ path: ["pages", page.id, "meta", name],+ });+ }+ continue;+ }+ patches.push({+ op: Object.hasOwn(page.meta, name) ? "replace" : "add",+ path: ["pages", page.id, "meta", name],+ value,+ });+ }+ }+ if (input.parentFolderId !== undefined) {+ const plan = getFolderChildReparentPlan(+ pages.folders,+ page.id,+ input.parentFolderId+ );+ if (plan !== undefined) {+ patches.push({+ op: "remove",+ path: ["folders", plan.currentFolderId, "children", plan.currentIndex],+ });+ patches.push({+ op: "add",+ path: ["folders", plan.nextFolderId, "children", plan.nextIndex],+ value: page.id,+ });+ }+ }+ return patches;+};++export const createPageUpdatePayload = (+ input: Parameters<typeof createPageUpdatePatches>[0]+): BuilderPatchChange[] => {+ const patches = createPageUpdatePatches(input);+ return compactBuilderPatchPayload([{ namespace: "pages", patches }]);+};++export const createPage = (+ state: Pick<BuilderState, "pages">,+ input: {+ pageId?: string;+ name: string;+ path: string;+ title?: string;+ parentFolderId?: string;+ meta?: z.infer<typeof pageMetaInput>;+ },+ context: BuilderRuntimeContext+) => {+ const pages = getRequiredPages(state);+ const parentFolderId = input.parentFolderId ?? pages.rootFolderId;+ const parentFolder = getFolderOrThrow(pages, parentFolderId);+ const pageId = input.pageId ?? context.createId();+ if (pages.pages.has(pageId)) {+ return throwBuilderRuntimeError("CONFLICT", "Page id already exists");+ }+ if (+ isPathAvailable({+ pages,+ path: input.path,+ parentFolderId,+ pageId,+ }) === false+ ) {+ return throwBuilderRuntimeError(+ "CONFLICT",+ `Page path "${input.path}" is already in use`+ );+ }+ const rootInstanceId = context.createId();+ const page = createPageValue({+ pageId,+ name: input.name,+ path: input.path,+ title: input.title,+ rootInstanceId,+ meta:+ input.meta === undefined+ ? {}+ : (pageMetaToPatchValue(input.meta) as Page["meta"]),+ });+ const rootInstance = createPageRootInstance(rootInstanceId);+ return createRuntimeMutation({+ payload: createPageCreatePayload({+ page,+ parentFolderId,+ parentChildIndex: parentFolder.children.length,+ rootInstance,+ }),+ result: { pageId },+ invalidatesNamespaces: ["pages", "instances"],+ });+};++export const updatePage = (+ state: Pick<BuilderState, "pages">,+ input: { pageId: string; values: z.infer<typeof pageFieldsInput> }+) => {+ const pages = getRequiredPages(state);+ const page = findPage(pages, input.pageId);+ if (page === undefined) {+ return throwBuilderRuntimeError("NOT_FOUND", "Page not found");+ }+ if (+ (input.values.path !== undefined ||+ input.values.parentFolderId !== undefined) &&+ isPathAvailable({+ pages,+ path: input.values.path ?? page.path,+ parentFolderId:+ input.values.parentFolderId ?? getParentFolderIdOrThrow(pages, page.id),+ pageId: page.id,+ }) === false+ ) {+ return throwBuilderRuntimeError(+ "CONFLICT",+ `Page path "${input.values.path ?? page.path}" is already in use`+ );+ }+ if (input.values.parentFolderId !== undefined) {+ getFolderOrThrow(pages, input.values.parentFolderId);+ getParentFolderIdOrThrow(pages, page.id);+ }+ return createRuntimeMutation({+ payload: createPageUpdatePayload({+ input: input.values,+ page,+ pages,+ }),+ result: { pageId: input.pageId },+ invalidatesNamespaces: ["pages"],+ });+};++type DeletePayloadState = Pick<+ BuilderState,+ | "pages"+ | "instances"+ | "props"+ | "dataSources"+ | "styleSources"+ | "styleSourceSelections"+ | "styles"+>;++const getRequiredDeleteState = (state: DeletePayloadState) => {+ const pages = getRequiredPages(state);+ if (+ state.instances === undefined ||+ state.props === undefined ||+ state.dataSources === undefined ||+ state.styleSources === undefined ||+ state.styleSourceSelections === undefined ||+ state.styles === undefined+ ) {+ return throwBuilderRuntimeError(+ "BAD_REQUEST",+ "Delete namespaces are missing"+ );+ }+ return {+ pages,+ instances: state.instances,+ props: state.props,+ dataSources: state.dataSources,+ styleSources: state.styleSources,+ styleSourceSelections: state.styleSourceSelections,+ styles: state.styles,+ };+};++const createDeletedInstanceCleanupPayload = (+ state: ReturnType<typeof getRequiredDeleteState>,+ rootInstanceIds: Iterable<string>+) => {+ const instanceIds = collectExclusiveInstanceIds(+ state.instances,+ rootInstanceIds+ );+ return createInstanceCleanupPayload({+ instanceIds,+ props: state.props.values(),+ dataSources: state.dataSources.values(),+ styleSources: state.styleSources.values(),+ styleSourceSelections: state.styleSourceSelections.values(),+ styles: state.styles.values(),+ });+};++export const createPageDeletePayload = ({+ state,+ page,+ parentFolderId,+}: {+ state: ReturnType<typeof getRequiredDeleteState>;+ page: Page;+ parentFolderId: Folder["id"];+}): BuilderPatchChange[] => {+ const parentFolder = state.pages.folders.get(parentFolderId);+ const pageIndex = parentFolder?.children.indexOf(page.id) ?? -1;+ return [+ {+ namespace: "pages",+ patches: [+ { op: "remove", path: ["pages", page.id] },+ ...(pageIndex === -1+ ? []+ : [+ {+ op: "remove" as const,+ path: ["folders", parentFolderId, "children", pageIndex],+ },+ ]),+ ],+ },+ ...createDeletedInstanceCleanupPayload(state, [page.rootInstanceId]),+ ];+};++export const deletePage = (+ state: DeletePayloadState,+ input: { pageId: string }+) => {+ const deleteState = getRequiredDeleteState(state);+ const page = findPage(deleteState.pages, input.pageId);+ if (page === undefined) {+ return throwBuilderRuntimeError("NOT_FOUND", "Page not found");+ }+ if (page.id === deleteState.pages.homePageId) {+ return throwBuilderRuntimeError(+ "BAD_REQUEST",+ "Home page cannot be deleted"+ );+ }+ const parentFolderId = getParentFolderIdOrThrow(deleteState.pages, page.id);+ return createRuntimeMutation({+ payload: createPageDeletePayload({+ state: deleteState,+ page,+ parentFolderId,+ }),+ result: { pageId: input.pageId },+ invalidatesNamespaces: [+ "pages",+ "instances",+ "props",+ "dataSources",+ "resources",+ "styleSourceSelections",+ "styleSources",+ "styles",+ ],+ });+};++export const createFolderDeletePayload = ({+ state,+ folder,+ parentFolderId,+}: {+ state: ReturnType<typeof getRequiredDeleteState>;+ folder: Folder;+ parentFolderId: Folder["id"];+}) => {+ const { folderIds, pageIds } = getFolderDeletionTargets(+ folder.id,+ state.pages+ );+ const parentFolder = state.pages.folders.get(parentFolderId);+ const folderIndex = parentFolder?.children.indexOf(folder.id) ?? -1;+ return {+ folderIds,+ pageIds,+ payload: [+ {+ namespace: "pages" as const,+ patches: [+ ...(folderIndex === -1+ ? []+ : [+ {+ op: "remove" as const,+ path: ["folders", parentFolderId, "children", folderIndex],+ },+ ]),+ ...pageIds.map((pageId) => ({+ op: "remove" as const,+ path: ["pages", pageId],+ })),+ ...folderIds.map((folderId) => ({+ op: "remove" as const,+ path: ["folders", folderId],+ })),+ ],+ },+ ...createDeletedInstanceCleanupPayload(+ state,+ pageIds.flatMap((pageId) => {+ const page = state.pages.pages.get(pageId);+ return page === undefined ? [] : [page.rootInstanceId];+ })+ ),+ ],+ };+};++export const deleteFolder = (+ state: DeletePayloadState,+ input: { folderId: string }+) => {+ const deleteState = getRequiredDeleteState(state);+ const folder = getFolderOrThrow(deleteState.pages, input.folderId);+ if (folder.id === deleteState.pages.rootFolderId) {+ return throwBuilderRuntimeError(+ "BAD_REQUEST",+ "Root folder cannot be deleted"+ );+ }+ const parentFolderId = getParentFolderIdOrThrow(deleteState.pages, folder.id);+ const { folderIds, pageIds, payload } = createFolderDeletePayload({+ state: deleteState,+ folder,+ parentFolderId,+ });+ if (folderIds.length === 0) {+ return throwBuilderRuntimeError(+ "BAD_REQUEST",+ "Folder containing home page cannot be deleted"+ );+ }+ return createRuntimeMutation({+ payload,+ result: { folderId: input.folderId, pageIds, folderIds },+ invalidatesNamespaces: [+ "pages",+ "instances",+ "props",+ "dataSources",+ "resources",+ "styleSourceSelections",+ "styleSources",+ "styles",+ ],+ });+};++export const updateFolder = (+ state: Pick<BuilderState, "pages">,+ input: {+ folderId: string;+ values: {+ name?: string;+ slug?: string;+ parentFolderId?: string;+ };+ }+) => {+ const pages = getRequiredPages(state);+ const folder = getFolderOrThrow(pages, input.folderId);+ if (folder.id === pages.rootFolderId) {+ return throwBuilderRuntimeError(+ "BAD_REQUEST",+ "Root folder cannot be updated"+ );+ }+ if (input.values.slug !== undefined) {+ if (+ isSlugAvailable(+ input.values.slug,+ pages.folders,+ input.values.parentFolderId ??+ getParentFolderIdOrThrow(pages, folder.id),+ folder.id+ ) === false+ ) {+ return throwBuilderRuntimeError(+ "CONFLICT",+ `Folder slug "${input.values.slug}" is already in use`+ );+ }+ }+ if (input.values.parentFolderId !== undefined) {+ const descendantFolderIds = getAllChildrenAndSelf(+ folder.id,+ pages.folders,+ "folder"+ );+ if (descendantFolderIds.includes(input.values.parentFolderId)) {+ return throwBuilderRuntimeError(+ "BAD_REQUEST",+ "Folder cannot be moved into itself or a descendant"+ );+ }+ const slug = input.values.slug ?? folder.slug;+ if (+ isSlugAvailable(+ slug,+ pages.folders,+ input.values.parentFolderId,+ folder.id+ ) === false+ ) {+ return throwBuilderRuntimeError(+ "CONFLICT",+ `Folder slug "${slug}" is already in use`+ );+ }+ getFolderOrThrow(pages, input.values.parentFolderId);+ getParentFolderIdOrThrow(pages, folder.id);+ }+ return createRuntimeMutation({+ payload: createFolderUpdatePayload({+ folder,+ pages,+ values: input.values,+ }),+ result: { folderId: input.folderId },+ invalidatesNamespaces: ["pages"],+ });+};diff --git a/packages/project-build/src/runtime/project-settings.test.ts b/packages/project-build/src/runtime/project-settings.test.tsnew file mode 100644index 0000000000..d8769b5c7b--- /dev/null+++ b/packages/project-build/src/runtime/project-settings.test.ts@@ -0,0 +1,402 @@+import { describe, expect, test } from "vitest";+import type { BuilderState } from "../state/builder-state";+import {+ breakpointFieldsInput,+ breakpointUpdateFieldsInput,+ createBreakpoint,+ createRedirect,+ deleteBreakpoint,+ deleteRedirect,+ getProjectSettings,+ listBreakpoints,+ listRedirects,+ projectSettingsUpdateInput,+ redirectFieldsInput,+ redirectUpdateFieldsInput,+ updateBreakpoint,+ updateProjectSettings,+ updateRedirect,+} from "./project-settings";++const createState = (): BuilderState =>+ ({+ pages: {+ meta: { siteName: "Existing site", faviconAssetId: "old-asset" },+ compiler: { atomicStyles: true },+ redirects: [{ old: "/old", new: "/new", status: "301" }],+ },+ breakpoints: new Map([+ ["base", { id: "base", label: "Base" }],+ ["desktop", { id: "desktop", label: "Desktop", minWidth: 1024 }],+ ]),+ styles: new Map([+ [+ "local:desktop:color",+ {+ breakpointId: "desktop",+ styleSourceId: "local",+ state: undefined,+ property: "color",+ value: { type: "keyword", value: "red" },+ },+ ],+ [+ "local:base:color",+ {+ breakpointId: "base",+ styleSourceId: "local",+ state: undefined,+ property: "color",+ value: { type: "keyword", value: "blue" },+ },+ ],+ ]),+ }) as BuilderState;++describe("project settings runtime", () => {+ test("exports reusable input contracts for router adapters", () => {+ expect(+ projectSettingsUpdateInput.parse({+ meta: { siteName: "Site", faviconAssetId: null },+ compiler: { atomicStyles: false },+ })+ ).toEqual({+ meta: { siteName: "Site", faviconAssetId: null },+ compiler: { atomicStyles: false },+ });+ expect(+ redirectFieldsInput.safeParse({+ old: "/old",+ new: "/new",+ status: "308",+ }).success+ ).toBe(false);+ expect(redirectUpdateFieldsInput.parse({ status: null })).toMatchObject({+ status: null,+ });+ expect(+ breakpointFieldsInput.parse({ id: "tablet", label: "Tablet" })+ ).toEqual({ id: "tablet", label: "Tablet" });+ expect(breakpointUpdateFieldsInput.parse({ condition: null })).toEqual({+ condition: null,+ });+ });++ test("reads project settings from pages namespace", () => {+ expect(getProjectSettings(createState())).toEqual({+ meta: { siteName: "Existing site", faviconAssetId: "old-asset" },+ compiler: { atomicStyles: true },+ redirects: [{ old: "/old", new: "/new", status: "301" }],+ });+ });++ test("updates project meta and compiler settings", () => {+ expect(+ updateProjectSettings(createState(), {+ meta: { siteName: "New site", faviconAssetId: null },+ compiler: { atomicStyles: false },+ })+ ).toEqual({+ kind: "mutation",+ invalidatesNamespaces: ["pages"],+ noop: false,+ result: { updated: true },+ payload: [+ {+ namespace: "pages",+ patches: [+ { op: "replace", path: ["meta", "siteName"], value: "New site" },+ { op: "remove", path: ["meta", "faviconAssetId"] },+ {+ op: "replace",+ path: ["compiler", "atomicStyles"],+ value: false,+ },+ ],+ },+ ],+ });+ });++ test("creates project meta and compiler settings when missing", () => {+ const state = createState();+ if (state.pages === undefined) {+ throw new Error("Expected pages");+ }+ state.pages.meta = undefined;+ state.pages.compiler = undefined;++ expect(+ updateProjectSettings(state, {+ meta: { siteName: "New site", faviconAssetId: null },+ compiler: { atomicStyles: true },+ })+ ).toEqual({+ kind: "mutation",+ invalidatesNamespaces: ["pages"],+ noop: false,+ result: { updated: true },+ payload: [+ {+ namespace: "pages",+ patches: [+ { op: "add", path: ["meta"], value: { siteName: "New site" } },+ { op: "add", path: ["compiler"], value: { atomicStyles: true } },+ ],+ },+ ],+ });+ });++ test("ignores unknown project settings fields after validation", () => {+ expect(+ updateProjectSettings(createState(), {+ meta: { unknown: "value" } as never,+ compiler: { unknown: true } as never,+ })+ ).toEqual({+ kind: "mutation",+ invalidatesNamespaces: ["pages"],+ noop: true,+ result: { updated: true },+ payload: [],+ });+ });+});++describe("redirect runtime", () => {+ test("lists redirects", () => {+ expect(listRedirects(createState())).toEqual({+ redirects: [{ old: "/old", new: "/new", status: "301" }],+ });+ });++ test("creates redirect", () => {+ expect(+ createRedirect(createState(), { old: "/from", new: "/to", status: "302" })+ ).toEqual({+ kind: "mutation",+ invalidatesNamespaces: ["pages"],+ noop: false,+ result: { old: "/from" },+ payload: [+ {+ namespace: "pages",+ patches: [+ {+ op: "add",+ path: ["redirects", 1],+ value: { old: "/from", new: "/to", status: "302" },+ },+ ],+ },+ ],+ });+ });++ test("updates redirect and can remove status", () => {+ expect(+ updateRedirect(createState(), {+ old: "/old",+ values: { old: "/older", new: "/newer", status: null },+ })+ ).toEqual({+ kind: "mutation",+ invalidatesNamespaces: ["pages"],+ noop: false,+ result: { old: "/older" },+ payload: [+ {+ namespace: "pages",+ patches: [+ { op: "replace", path: ["redirects", 0, "old"], value: "/older" },+ { op: "replace", path: ["redirects", 0, "new"], value: "/newer" },+ { op: "remove", path: ["redirects", 0, "status"] },+ ],+ },+ ],+ });+ });++ test("deletes redirect", () => {+ expect(deleteRedirect(createState(), { old: "/old" })).toEqual({+ kind: "mutation",+ invalidatesNamespaces: ["pages"],+ noop: false,+ result: { old: "/old" },+ payload: [+ {+ namespace: "pages",+ patches: [{ op: "remove", path: ["redirects", 0] }],+ },+ ],+ });+ });+});++describe("breakpoint runtime", () => {+ test("lists breakpoints", () => {+ expect(listBreakpoints(createState())).toEqual({+ breakpoints: [+ { id: "base", label: "Base" },+ { id: "desktop", label: "Desktop", minWidth: 1024 },+ ],+ });+ });++ test("creates breakpoint", () => {+ expect(+ createBreakpoint(createState(), {+ id: "tablet",+ label: "Tablet",+ maxWidth: 991,+ })+ ).toEqual({+ kind: "mutation",+ invalidatesNamespaces: ["breakpoints"],+ noop: false,+ result: { breakpointId: "tablet" },+ payload: [+ {+ namespace: "breakpoints",+ patches: [+ {+ op: "add",+ path: ["tablet"],+ value: { id: "tablet", label: "Tablet", maxWidth: 991 },+ },+ ],+ },+ ],+ });+ });++ test("rejects creating more editable breakpoints than Builder allows", () => {+ const state = createState();+ const breakpoints = state.breakpoints;+ if (breakpoints === undefined) {+ throw new Error("Expected breakpoints");+ }+ for (let index = 0; index < 7; index += 1) {+ breakpoints.set(`extra-${index}`, {+ id: `extra-${index}`,+ label: `Extra ${index}`,+ minWidth: index + 1,+ });+ }++ expect(() =>+ createBreakpoint(state, {+ id: "overflow",+ label: "Overflow",+ minWidth: 1200,+ })+ ).toThrow("Breakpoint limit reached");+ });++ test("rejects creating a second base breakpoint", () => {+ expect(() =>+ createBreakpoint(createState(), {+ id: "second-base",+ label: "Second base",+ })+ ).toThrow("Base breakpoint already exists");+ });++ test("updates breakpoint", () => {+ expect(+ updateBreakpoint(createState(), {+ breakpointId: "desktop",+ values: { label: "Large", minWidth: 1200 },+ })+ ).toEqual({+ kind: "mutation",+ invalidatesNamespaces: ["breakpoints"],+ noop: false,+ result: { breakpointId: "desktop" },+ payload: [+ {+ namespace: "breakpoints",+ patches: [+ {+ op: "replace",+ path: ["desktop"],+ value: { id: "desktop", label: "Large", minWidth: 1200 },+ },+ ],+ },+ ],+ });+ });++ test("updates breakpoint and can clear width or condition fields", () => {+ const state = createState();+ const breakpoints = state.breakpoints;+ if (breakpoints === undefined) {+ throw new Error("Expected breakpoints");+ }+ breakpoints.set("custom", {+ id: "custom",+ label: "Custom",+ condition: "(hover: hover)",+ });++ expect(+ updateBreakpoint(state, {+ breakpointId: "custom",+ values: { condition: null, maxWidth: 767 },+ })+ ).toEqual({+ kind: "mutation",+ invalidatesNamespaces: ["breakpoints"],+ noop: false,+ result: { breakpointId: "custom" },+ payload: [+ {+ namespace: "breakpoints",+ patches: [+ {+ op: "replace",+ path: ["custom"],+ value: { id: "custom", label: "Custom", maxWidth: 767 },+ },+ ],+ },+ ],+ });+ });++ test("rejects updating or deleting the base breakpoint", () => {+ expect(() =>+ updateBreakpoint(createState(), {+ breakpointId: "base",+ values: { label: "New base" },+ })+ ).toThrow("Base breakpoint cannot be updated");++ expect(() =>+ deleteBreakpoint(createState(), { breakpointId: "base" })+ ).toThrow("Base breakpoint cannot be deleted");+ });++ test("deletes breakpoint and its style declarations", () => {+ expect(+ deleteBreakpoint(createState(), { breakpointId: "desktop" })+ ).toEqual({+ kind: "mutation",+ invalidatesNamespaces: ["breakpoints", "styles"],+ noop: false,+ result: { breakpointId: "desktop" },+ payload: [+ {+ namespace: "breakpoints",+ patches: [{ op: "remove", path: ["desktop"] }],+ },+ {+ namespace: "styles",+ patches: [{ op: "remove", path: ["local:desktop:color"] }],+ },+ ],+ });+ });+});diff --git a/packages/project-build/src/runtime/project-settings.ts b/packages/project-build/src/runtime/project-settings.tsnew file mode 100644index 0000000000..1aa70c0976--- /dev/null+++ b/packages/project-build/src/runtime/project-settings.ts@@ -0,0 +1,457 @@+import type {+ Breakpoint,+ CompilerSettings,+ PageRedirect,+ ProjectMeta,+} from "@webstudio-is/sdk";+import {+ breakpoint,+ compilerSettings,+ pageRedirect,+ projectMeta,+} from "@webstudio-is/sdk";+import { z } from "zod";+import {+ compactBuilderPatchPayload,+ type BuilderPatchChange,+} from "../contracts/patch";+import type { BuilderState } from "../state/builder-state";+import { hasReachedBreakpointLimit, isBaseBreakpoint } from "./breakpoints";+import { throwBuilderRuntimeError } from "./errors";+import { createRuntimeMutation } from "./mutation";+import { getRequiredPages } from "./pages";++const getRequiredBreakpoints = (state: Pick<BuilderState, "breakpoints">) => {+ if (state.breakpoints === undefined) {+ return throwBuilderRuntimeError(+ "BAD_REQUEST",+ "Breakpoints namespace is missing"+ );+ }+ return state.breakpoints;+};++type Settable<T> = {+ [Property in keyof T]?: T[Property] | null;+};++type ProjectMetaValues = Settable<+ NonNullable<ReturnType<typeof getRequiredPages>["meta"]>+>;++type CompilerValues = Settable<+ NonNullable<ReturnType<typeof getRequiredPages>["compiler"]>+>;++export const projectSettingsUpdateInput = z.object({+ meta: z.record(z.unknown()).optional(),+ compiler: z.record(z.unknown()).optional(),+});++const projectMetaKeys: ReadonlySet<string> = new Set(+ projectMeta.keyof().options+);+const compilerSettingKeys: ReadonlySet<string> = new Set(+ compilerSettings.keyof().options+);++const omitNullValues = (input: Record<string, unknown>) =>+ Object.fromEntries(+ Object.entries(input).filter(([, value]) => value !== null)+ );++const parseProjectMeta = (input: Record<string, unknown>) => {+ const result = projectMeta.partial().safeParse(omitNullValues(input));+ if (result.success === false) {+ return throwBuilderRuntimeError("BAD_REQUEST", result.error.message);+ }+ const values: Settable<ProjectMeta> = { ...result.data };+ for (const [name, value] of Object.entries(input)) {+ if (value === null && projectMetaKeys.has(name)) {+ values[name as keyof ProjectMeta] = null;+ }+ }+ return values;+};++const parseCompilerSettings = (input: Record<string, unknown>) => {+ const result = compilerSettings.partial().safeParse(omitNullValues(input));+ if (result.success === false) {+ return throwBuilderRuntimeError("BAD_REQUEST", result.error.message);+ }+ const values: Settable<CompilerSettings> = { ...result.data };+ for (const [name, value] of Object.entries(input)) {+ if (value === null && compilerSettingKeys.has(name)) {+ values[name as keyof CompilerSettings] = null;+ }+ }+ return values;+};++export const getProjectSettings = (state: Pick<BuilderState, "pages">) => {+ const pages = getRequiredPages(state);+ return {+ meta: pages.meta ?? {},+ compiler: pages.compiler ?? {},+ redirects: pages.redirects ?? [],+ };+};++const pushObjectFieldPatches = ({+ patches,+ basePath,+ current,+ values,+}: {+ patches: BuilderPatchChange["patches"];+ basePath: string[];+ current: Record<string, unknown> | undefined;+ values: Record<string, unknown>;+}) => {+ if (current === undefined) {+ const next = omitNullValues(values);+ if (Object.keys(next).length > 0) {+ patches.push({ op: "add", path: basePath, value: next });+ }+ return;+ }+ for (const [name, value] of Object.entries(values)) {+ const exists = Object.hasOwn(current, name);+ if (value === null) {+ if (exists) {+ patches.push({ op: "remove", path: [...basePath, name] });+ }+ continue;+ }+ patches.push({+ op: exists ? "replace" : "add",+ path: [...basePath, name],+ value,+ });+ }+};++export const updateProjectSettings = (+ state: Pick<BuilderState, "pages">,+ input: {+ meta?: ProjectMetaValues;+ compiler?: CompilerValues;+ }+) => {+ const pages = getRequiredPages(state);+ const patches: BuilderPatchChange["patches"] = [];+ if (input.meta !== undefined) {+ const values = parseProjectMeta(input.meta);+ pushObjectFieldPatches({+ patches,+ basePath: ["meta"],+ current: pages.meta,+ values,+ });+ }+ if (input.compiler !== undefined) {+ const values = parseCompilerSettings(input.compiler);+ pushObjectFieldPatches({+ patches,+ basePath: ["compiler"],+ current: pages.compiler,+ values,+ });+ }+ return createRuntimeMutation({+ payload: compactBuilderPatchPayload([{ namespace: "pages", patches }]),+ result: { updated: true },+ invalidatesNamespaces: ["pages"],+ });+};++export const listRedirects = (state: Pick<BuilderState, "pages">) => ({+ redirects: getRequiredPages(state).redirects ?? [],+});++export const redirectStatusInput = z.enum(["301", "302"]);++export const redirectFieldsInput = z.object({+ old: z.string(),+ new: z.string(),+ status: redirectStatusInput.optional(),+});++export const redirectUpdateFieldsInput = z.object({+ old: z.string().optional(),+ new: z.string().optional(),+ status: redirectStatusInput.nullable().optional(),+});++const findRedirectIndex = (+ redirects: NonNullable<ReturnType<typeof getRequiredPages>["redirects"]>,+ oldPath: string+) => redirects.findIndex((redirect) => redirect.old === oldPath);++const parseRedirect = (input: PageRedirect) => {+ const result = pageRedirect.safeParse(input);+ if (result.success === false) {+ return throwBuilderRuntimeError("BAD_REQUEST", result.error.message);+ }+ return result.data;+};++export const createRedirect = (+ state: Pick<BuilderState, "pages">,+ input: PageRedirect+) => {+ const pages = getRequiredPages(state);+ const value = parseRedirect(input);+ const redirects = pages.redirects ?? [];+ if (findRedirectIndex(redirects, value.old) !== -1) {+ return throwBuilderRuntimeError("CONFLICT", "Redirect already exists");+ }+ const patches: BuilderPatchChange["patches"] = [];+ if (pages.redirects === undefined) {+ patches.push({ op: "add", path: ["redirects"], value: [] });+ }+ patches.push({+ op: "add",+ path: ["redirects", redirects.length],+ value,+ });+ return createRuntimeMutation({+ payload: [{ namespace: "pages", patches }],+ result: { old: value.old },+ invalidatesNamespaces: ["pages"],+ });+};++export const updateRedirect = (+ state: Pick<BuilderState, "pages">,+ input: {+ old: string;+ values: { old?: string; new?: string; status?: "301" | "302" | null };+ }+) => {+ const pages = getRequiredPages(state);+ const redirects = pages.redirects ?? [];+ const index = findRedirectIndex(redirects, input.old);+ if (index === -1) {+ return throwBuilderRuntimeError("NOT_FOUND", "Redirect not found");+ }+ if (+ input.values.old !== undefined &&+ input.values.old !== input.old &&+ findRedirectIndex(redirects, input.values.old) !== -1+ ) {+ return throwBuilderRuntimeError("CONFLICT", "Redirect already exists");+ }+ const nextRedirect: Record<string, unknown> = { ...redirects[index] };+ for (const [name, value] of Object.entries(input.values)) {+ if (value === null) {+ delete nextRedirect[name];+ } else if (value !== undefined) {+ nextRedirect[name] = value;+ }+ }+ parseRedirect(nextRedirect as PageRedirect);+ const patches: BuilderPatchChange["patches"] = [];+ for (const [name, value] of Object.entries(input.values)) {+ if (value === null) {+ if (Object.hasOwn(redirects[index], name)) {+ patches.push({ op: "remove", path: ["redirects", index, name] });+ }+ continue;+ }+ if (value !== undefined) {+ patches.push({+ op: Object.hasOwn(redirects[index], name) ? "replace" : "add",+ path: ["redirects", index, name],+ value,+ });+ }+ }+ return createRuntimeMutation({+ payload: compactBuilderPatchPayload([{ namespace: "pages", patches }]),+ result: { old: input.values.old ?? input.old },+ invalidatesNamespaces: ["pages"],+ });+};++export const deleteRedirect = (+ state: Pick<BuilderState, "pages">,+ input: { old: string }+) => {+ const redirects = getRequiredPages(state).redirects ?? [];+ const index = findRedirectIndex(redirects, input.old);+ if (index === -1) {+ return throwBuilderRuntimeError("NOT_FOUND", "Redirect not found");+ }+ return createRuntimeMutation({+ payload: [+ {+ namespace: "pages",+ patches: [{ op: "remove", path: ["redirects", index] }],+ },+ ],+ result: { old: input.old },+ invalidatesNamespaces: ["pages"],+ });+};++export const listBreakpoints = (state: Pick<BuilderState, "breakpoints">) => ({+ breakpoints: Array.from(getRequiredBreakpoints(state).values()),+});++export const breakpointFieldsInput = z.object({+ id: z.string(),+ label: z.string(),+ minWidth: z.number().optional(),+ maxWidth: z.number().optional(),+ condition: z.string().optional(),+});++export const breakpointUpdateFieldsInput = z.object({+ label: z.string().optional(),+ minWidth: z.number().nullable().optional(),+ maxWidth: z.number().nullable().optional(),+ condition: z.string().nullable().optional(),+});++const parseBreakpoint = (input: Breakpoint) => {+ const result = breakpoint.safeParse(input);+ if (result.success === false) {+ return throwBuilderRuntimeError("BAD_REQUEST", result.error.message);+ }+ return result.data;+};++export const createBreakpoint = (+ state: Pick<BuilderState, "breakpoints">,+ input: Breakpoint+) => {+ const breakpoints = getRequiredBreakpoints(state);+ if (breakpoints.has(input.id)) {+ return throwBuilderRuntimeError("CONFLICT", "Breakpoint already exists");+ }+ const value = parseBreakpoint(input);+ const canHaveOnlyOneBaseBreakpoint =+ value.condition === undefined && isBaseBreakpoint(value);+ if (+ canHaveOnlyOneBaseBreakpoint &&+ Array.from(breakpoints.values()).some(+ (breakpoint) =>+ breakpoint.condition === undefined && isBaseBreakpoint(breakpoint)+ )+ ) {+ return throwBuilderRuntimeError(+ "CONFLICT",+ "Base breakpoint already exists"+ );+ }+ const editableBreakpointCount = Array.from(breakpoints.values()).filter(+ (breakpoint) =>+ breakpoint.condition !== undefined ||+ isBaseBreakpoint(breakpoint) === false+ ).length;+ if (hasReachedBreakpointLimit(editableBreakpointCount)) {+ return throwBuilderRuntimeError("BAD_REQUEST", "Breakpoint limit reached");+ }+ return createRuntimeMutation({+ payload: [+ {+ namespace: "breakpoints",+ patches: [{ op: "add", path: [value.id], value }],+ },+ ],+ result: { breakpointId: value.id },+ invalidatesNamespaces: ["breakpoints"],+ });+};++export const updateBreakpoint = (+ state: Pick<BuilderState, "breakpoints">,+ input: {+ breakpointId: string;+ values: Settable<Omit<Breakpoint, "id">>;+ }+) => {+ const breakpoints = getRequiredBreakpoints(state);+ const current = breakpoints.get(input.breakpointId);+ if (current === undefined) {+ return throwBuilderRuntimeError("NOT_FOUND", "Breakpoint not found");+ }+ if (current.condition === undefined && isBaseBreakpoint(current)) {+ return throwBuilderRuntimeError(+ "BAD_REQUEST",+ "Base breakpoint cannot be updated"+ );+ }+ const nextBreakpoint: Record<string, unknown> = { ...current };+ for (const [name, value] of Object.entries(input.values)) {+ if (value === null) {+ delete nextBreakpoint[name];+ continue;+ }+ if (value !== undefined) {+ nextBreakpoint[name] = value;+ }+ }+ const value = parseBreakpoint(nextBreakpoint as Breakpoint);+ if (value.condition === undefined && isBaseBreakpoint(value)) {+ return throwBuilderRuntimeError(+ "BAD_REQUEST",+ "Breakpoint cannot be changed into the base breakpoint"+ );+ }+ return createRuntimeMutation({+ payload: [+ {+ namespace: "breakpoints",+ patches: [{ op: "replace", path: [input.breakpointId], value }],+ },+ ],+ result: { breakpointId: input.breakpointId },+ invalidatesNamespaces: ["breakpoints"],+ });+};++export const deleteBreakpoint = (+ state: Pick<BuilderState, "breakpoints" | "styles">,+ input: { breakpointId: string }+) => {+ const breakpoints = getRequiredBreakpoints(state);+ if (state.styles === undefined) {+ return throwBuilderRuntimeError(+ "BAD_REQUEST",+ "Styles namespace is missing"+ );+ }+ if (breakpoints.has(input.breakpointId) === false) {+ return throwBuilderRuntimeError("NOT_FOUND", "Breakpoint not found");+ }+ const breakpoint = breakpoints.get(input.breakpointId);+ if (+ breakpoint !== undefined &&+ breakpoint.condition === undefined &&+ isBaseBreakpoint(breakpoint)+ ) {+ return throwBuilderRuntimeError(+ "BAD_REQUEST",+ "Base breakpoint cannot be deleted"+ );+ }+ const stylePatches: BuilderPatchChange["patches"] = [];+ for (const [key, style] of state.styles) {+ if (style.breakpointId === input.breakpointId) {+ stylePatches.push({ op: "remove", path: [key] });+ }+ }+ return createRuntimeMutation({+ payload: compactBuilderPatchPayload([+ {+ namespace: "breakpoints",+ patches: [{ op: "remove", path: [input.breakpointId] }],+ },+ { namespace: "styles", patches: stylePatches },+ ]),+ result: { breakpointId: input.breakpointId },+ invalidatesNamespaces: ["breakpoints", "styles"],+ });+};diff --git a/packages/project-build/src/runtime/props.test.ts b/packages/project-build/src/runtime/props.test.tsnew file mode 100644index 0000000000..b135464c08--- /dev/null+++ b/packages/project-build/src/runtime/props.test.ts@@ -0,0 +1,469 @@+import { describe, expect, test } from "vitest";+import type { Instance, Prop } from "@webstudio-is/sdk";+import {+ clonePropForInstance,+ createPropDeletePayload,+ createPropBindingFromInput,+ createPropClonePatches,+ createPropRenamePayload,+ createPropUpsertPayload,+ createValidatedPropBindingFromInput,+ createValidatedPropValueFromInput,+ createPropValue,+ findProp,+ getPropDeletePlan,+ getPropIdsToDelete,+ getPropValueErrors,+ propBindingInput,+ propValueInput,+} from "./props";++const image: Instance = {+ type: "instance",+ id: "image-id",+ component: "Image",+ children: [],+};++const prop = (name: string, overrides: Partial<Prop> = {}): Prop =>+ ({+ id: `${name}-id`,+ instanceId: image.id,+ name,+ type: "string",+ value: "",+ ...overrides,+ }) as Prop;++describe("findProp", () => {+ test("finds a prop by instance id and name", () => {+ expect(findProp([prop("src")], image.id, "src")?.id).toBe("src-id");+ expect(findProp([prop("src")], "other-id", "src")).toBeUndefined();+ });+});++describe("createPropValue", () => {+ test("creates props through the sdk schema", () => {+ expect(+ createPropValue({+ id: "prop-id",+ instanceId: "instance-id",+ name: "label",+ type: "string",+ value: "Label",+ })+ ).toEqual({+ id: "prop-id",+ instanceId: "instance-id",+ name: "label",+ type: "string",+ value: "Label",+ });+ });++ test("rejects invalid prop values", () => {+ expect(() =>+ createPropValue({+ id: "prop-id",+ instanceId: "instance-id",+ name: "visible",+ type: "boolean",+ value: "not boolean",+ })+ ).toThrow();+ });+});++describe("prop input creators", () => {+ test("parse prop value and binding inputs used by the API", () => {+ expect(+ propValueInput.parse({+ instanceId: "instance-id",+ name: "label",+ type: "string",+ value: "Label",+ })+ ).toEqual({+ instanceId: "instance-id",+ name: "label",+ type: "string",+ value: "Label",+ });++ expect(+ propBindingInput.parse({+ instanceId: "instance-id",+ name: "value",+ binding: { type: "expression", value: "system.search.value" },+ })+ ).toEqual({+ instanceId: "instance-id",+ name: "value",+ binding: { type: "expression", value: "system.search.value" },+ });+ });++ test("reject invalid prop input types", () => {+ expect(() =>+ propValueInput.parse({+ instanceId: "instance-id",+ name: "label",+ type: "invalid",+ value: "Label",+ })+ ).toThrow();++ expect(() =>+ propBindingInput.parse({+ instanceId: "instance-id",+ name: "value",+ binding: { type: "string", value: "Label" },+ })+ ).toThrow();+ });++ test("creates prop values and bindings from input", () => {+ expect(+ createPropBindingFromInput({+ id: "prop-id",+ instanceId: "instance-id",+ name: "value",+ binding: { type: "expression", value: "value" },+ })+ ).toEqual({+ id: "prop-id",+ instanceId: "instance-id",+ name: "value",+ type: "expression",+ value: "value",+ });+ });+});++describe("validated prop input creators", () => {+ test("create valid prop values and bindings", () => {+ expect(+ createValidatedPropValueFromInput(+ {+ instanceId: "instance-id",+ name: "label",+ type: "string",+ value: "Label",+ },+ () => "prop-id"+ )+ ).toEqual({+ success: true,+ prop: {+ id: "prop-id",+ instanceId: "instance-id",+ name: "label",+ type: "string",+ value: "Label",+ },+ });++ expect(+ createValidatedPropBindingFromInput(+ {+ instanceId: "instance-id",+ name: "value",+ binding: { type: "parameter", value: "param" },+ },+ () => "prop-id"+ )+ ).toEqual({+ success: true,+ prop: {+ id: "prop-id",+ instanceId: "instance-id",+ name: "value",+ type: "parameter",+ value: "param",+ },+ });+ });++ test("return expression errors without creating props", () => {+ expect(+ createValidatedPropValueFromInput({+ instanceId: "instance-id",+ name: "value",+ type: "expression",+ value: "invalid {",+ })+ ).toEqual({+ success: false,+ errors: expect.arrayContaining([expect.any(String)]),+ });++ expect(+ createValidatedPropBindingFromInput({+ instanceId: "instance-id",+ name: "value",+ binding: { type: "expression", value: "invalid {" },+ })+ ).toEqual({+ success: false,+ errors: expect.arrayContaining([expect.any(String)]),+ });+ });+});++describe("clonePropForInstance", () => {+ test("clones prop with new prop and instance ids", () => {+ expect(+ clonePropForInstance({+ prop: prop("title", { value: "Title" }),+ propId: "new-prop",+ instanceId: "new-instance",+ })+ ).toEqual({+ id: "new-prop",+ instanceId: "new-instance",+ name: "title",+ type: "string",+ value: "Title",+ });+ });+});++describe("createPropClonePatches", () => {+ test("clones props for copied instances", () => {+ expect(+ createPropClonePatches({+ nextIdById: new Map([[image.id, "new-instance"]]),+ props: [+ prop("title", { value: "Title" }),+ prop("ignored", { instanceId: "other-instance" }),+ ],+ createId: () => "new-prop",+ })+ ).toEqual([+ {+ op: "add",+ path: ["new-prop"],+ value: {+ id: "new-prop",+ instanceId: "new-instance",+ name: "title",+ type: "string",+ value: "Title",+ },+ },+ ]);+ });+});++describe("createPropUpsertPayload", () => {+ test("creates add and replace patches", () => {+ const nextExisting = prop("src", { id: "incoming-src-id", value: "next" });+ const nextNew = prop("alt", { id: "alt-id", value: "Alt" });++ expect(+ createPropUpsertPayload({+ props: [prop("src", { value: "prev" })],+ nextProps: [nextExisting, nextNew],+ })+ ).toEqual({+ propIds: ["src-id", "alt-id"],+ payload: [+ {+ namespace: "props",+ patches: [+ {+ op: "replace",+ path: ["src-id"],+ value: { ...nextExisting, id: "src-id" },+ },+ { op: "add", path: ["alt-id"], value: nextNew },+ ],+ },+ ],+ });+ });++ test("removes duplicate props with the same instance and name", () => {+ const nextProp = prop("src", { id: "src-id", value: "next" });++ expect(+ createPropUpsertPayload({+ props: [+ prop("src", { id: "src-id", value: "prev" }),+ prop("src", { id: "duplicate-src-id", value: "duplicate" }),+ ],+ nextProps: [nextProp],+ })+ ).toEqual({+ propIds: ["src-id"],+ payload: [+ {+ namespace: "props",+ patches: [+ { op: "remove", path: ["duplicate-src-id"] },+ { op: "replace", path: ["src-id"], value: nextProp },+ ],+ },+ ],+ });+ });+});++describe("createPropRenamePayload", () => {+ test("creates remove and add patches for renamed props", () => {+ const classNameProp = prop("className", {+ id: "box:className",+ instanceId: "box",+ });++ expect(+ createPropRenamePayload({+ props: [classNameProp],+ renames: [+ {+ propId: "box:className",+ name: "class",+ propIdPrefix: "box",+ },+ ],+ })+ ).toEqual({+ propIds: ["box:class"],+ payload: [+ {+ namespace: "props",+ patches: [+ { op: "remove", path: ["box:className"] },+ {+ op: "add",+ path: ["box:class"],+ value: {+ ...classNameProp,+ id: "box:class",+ name: "class",+ },+ },+ ],+ },+ ],+ });+ });+});++describe("getPropValueErrors", () => {+ test("skips non-expression props", () => {+ expect(+ getPropValueErrors({ type: "string", value: "invalid expression {" })+ ).toEqual([]);+ });++ test("validates expression props", () => {+ expect(getPropValueErrors({ type: "expression", value: "value" })).toEqual(+ []+ );+ expect(+ getPropValueErrors({ type: "expression", value: "invalid {" })+ ).not.toEqual([]);+ });+});++describe("getPropIdsToDelete", () => {+ const imageProps = new Map<Prop["name"], Prop>([+ ["src", prop("src")],+ ["width", prop("width")],+ ["height", prop("height")],+ ]);++ test("deletes related image dimensions with src", () => {+ expect(+ getPropIdsToDelete({+ instanceComponent: "Image",+ instanceProps: imageProps,+ propName: "src",+ })+ ).toEqual(new Set(["src-id", "width-id", "height-id"]));+ });++ test("deletes only the requested prop for non-image components", () => {+ expect(+ getPropIdsToDelete({+ instanceComponent: "Box",+ instanceProps: imageProps,+ propName: "src",+ })+ ).toEqual(new Set(["src-id"]));+ });+});++describe("getPropDeletePlan", () => {+ test("includes resource ids owned by deleted props", () => {+ expect(+ getPropDeletePlan({+ instance: image,+ props: [+ prop("src", {+ type: "resource",+ value: "resource-id",+ }),+ prop("width"),+ prop("height"),+ ],+ propName: "src",+ })+ ).toEqual({+ propIds: new Set(["src-id", "width-id", "height-id"]),+ resourceIds: new Set(["resource-id"]),+ });+ });+});++describe("createPropDeletePayload", () => {+ test("creates prop and resource removal payload", () => {+ expect(+ createPropDeletePayload({+ deletions: [{ instanceId: image.id, name: "src" }],+ instances: new Map([[image.id, image]]),+ props: [+ prop("src", {+ type: "resource",+ value: "resource-id",+ }),+ prop("width"),+ prop("height"),+ ],+ })+ ).toEqual({+ propIds: ["src-id", "width-id", "height-id"],+ resourceIds: ["resource-id"],+ payload: [+ {+ namespace: "props",+ patches: [+ { op: "remove", path: ["src-id"] },+ { op: "remove", path: ["width-id"] },+ { op: "remove", path: ["height-id"] },+ ],+ },+ {+ namespace: "resources",+ patches: [{ op: "remove", path: ["resource-id"] }],+ },+ ],+ });+ });++ test("reports the first missing instance", () => {+ expect(+ createPropDeletePayload({+ deletions: [{ instanceId: "missing", name: "src" }],+ instances: new Map([[image.id, image]]),+ props: [],+ })+ ).toEqual({+ missingInstanceId: "missing",+ propIds: [],+ resourceIds: [],+ payload: [],+ });+ });+});diff --git a/packages/project-build/src/runtime/props.ts b/packages/project-build/src/runtime/props.tsnew file mode 100644index 0000000000..71b2411737--- /dev/null+++ b/packages/project-build/src/runtime/props.ts@@ -0,0 +1,522 @@+import { z } from "zod";+import {+ lintExpression,+ prop as propSchema,+ type Instance,+ type Prop,+} from "@webstudio-is/sdk";+import type { BuilderState } from "../state/builder-state";+import { throwBuilderRuntimeError } from "./errors";+import { createRuntimeMutation } from "./mutation";++export const findProp = (+ props: Iterable<Prop>,+ instanceId: Instance["id"],+ name: Prop["name"]+) => {+ for (const prop of props) {+ if (prop.instanceId === instanceId && prop.name === name) {+ return prop;+ }+ }+};++export const createPropValue = ({+ id,+ instanceId,+ name,+ type,+ value,+ required,+}: {+ id: Prop["id"];+ instanceId: Instance["id"];+ name: Prop["name"];+ type: Prop["type"];+ value: unknown;+ required?: boolean;+}): Prop =>+ propSchema.parse({+ id,+ instanceId,+ name,+ type,+ value,+ required,+ });++export const createPropBindingFromInput = ({+ id,+ instanceId,+ name,+ binding,+}: {+ id: Prop["id"];+ instanceId: Instance["id"];+ name: Prop["name"];+ binding: Pick<Prop, "type" | "value">;+}): Prop =>+ createPropValue({+ id,+ instanceId,+ name,+ type: binding.type,+ value: binding.value,+ });++export const propValueInput = z.object({+ propId: z.string().optional(),+ instanceId: z.string(),+ name: z.string(),+ type: z.enum([+ "number",+ "string",+ "boolean",+ "json",+ "asset",+ "page",+ "string[]",+ "parameter",+ "resource",+ "expression",+ "action",+ "animationAction",+ ]),+ value: z.unknown(),+ required: z.boolean().optional(),+});++export const propBindingInput = z.object({+ propId: z.string().optional(),+ instanceId: z.string(),+ name: z.string(),+ binding: z.discriminatedUnion("type", [+ z.object({ type: z.literal("expression"), value: z.string() }),+ z.object({ type: z.literal("parameter"), value: z.string() }),+ z.object({ type: z.literal("resource"), value: z.string() }),+ z.object({+ type: z.literal("action"),+ value: z.array(+ z.object({+ type: z.literal("execute"),+ args: z.array(z.string()),+ code: z.string(),+ })+ ),+ }),+ ]),+});++export const getPropValueErrors = ({+ type,+ value,+}: {+ type: Prop["type"];+ value?: unknown;+}) => {+ if (type !== "expression") {+ return [];+ }+ return lintExpression({ expression: String(value) })+ .filter((diagnostic) => diagnostic.severity === "error")+ .map((diagnostic) => diagnostic.message);+};++type ValidatedPropInputResult =+ | { success: true; prop: Prop }+ | { success: false; errors: string[] };++const createMissingId = (): Prop["id"] => {+ throw new Error("createId is required when propId is not provided.");+};++export const createValidatedPropValueFromInput = (+ value: z.infer<typeof propValueInput>,+ createId: () => Prop["id"] = createMissingId+): ValidatedPropInputResult => {+ const errors = getPropValueErrors(value);+ if (errors.length > 0) {+ return { success: false, errors };+ }+ return {+ success: true,+ prop: createPropValue({+ id: value.propId ?? createId(),+ instanceId: value.instanceId,+ name: value.name,+ type: value.type,+ value: value.value,+ required: value.required,+ }),+ };+};++export const createValidatedPropBindingFromInput = (+ binding: z.infer<typeof propBindingInput>,+ createId: () => Prop["id"] = createMissingId+): ValidatedPropInputResult => {+ const errors = getPropValueErrors({+ type: binding.binding.type,+ value: binding.binding.value,+ });+ if (errors.length > 0) {+ return { success: false, errors };+ }+ return {+ success: true,+ prop: createPropBindingFromInput({+ id: binding.propId ?? createId(),+ instanceId: binding.instanceId,+ name: binding.name,+ binding: binding.binding,+ }),+ };+};++export const clonePropForInstance = ({+ prop,+ propId,+ instanceId,+}: {+ prop: Prop;+ propId: Prop["id"];+ instanceId: Instance["id"];+}): Prop => ({+ ...prop,+ id: propId,+ instanceId,+});++export const createPropClonePatches = ({+ nextIdById,+ props,+ createId,+}: {+ nextIdById: Map<Instance["id"], Instance["id"]>;+ props: Iterable<Prop>;+ createId: () => Prop["id"];+}) =>+ Array.from(props).flatMap((prop) => {+ const nextInstanceId = nextIdById.get(prop.instanceId);+ if (nextInstanceId === undefined) {+ return [];+ }+ const nextProp = clonePropForInstance({+ prop,+ propId: createId(),+ instanceId: nextInstanceId,+ });+ return [{ op: "add" as const, path: [nextProp.id], value: nextProp }];+ });++export const createPropUpsertPayload = ({+ props,+ nextProps,+}: {+ props: Iterable<Prop>;+ nextProps: Prop[];+}) => {+ const existingProps = Array.from(props);+ const removedPropIds = new Set<Prop["id"]>();+ const patches = nextProps.flatMap((nextProp) => {+ const existing =+ existingProps.find((prop) => prop.id === nextProp.id) ??+ findProp(existingProps, nextProp.instanceId, nextProp.name);+ const prop =+ existing === undefined ? nextProp : { ...nextProp, id: existing.id };+ const duplicateRemovals = existingProps+ .filter((existingProp) => existingProp.id !== prop.id)+ .filter((existingProp) => existingProp.instanceId === prop.instanceId)+ .filter((existingProp) => existingProp.name === prop.name)+ .flatMap((existingProp) => {+ if (removedPropIds.has(existingProp.id)) {+ return [];+ }+ removedPropIds.add(existingProp.id);+ return [+ {+ op: "remove" as const,+ path: [existingProp.id],+ },+ ];+ });+ return [+ ...duplicateRemovals,+ {+ op: existing === undefined ? ("add" as const) : ("replace" as const),+ path: [prop.id],+ value: prop,+ },+ ];+ });+ return {+ propIds: patches.flatMap((patch) =>+ patch.op === "remove" ? [] : [String(patch.path[0])]+ ),+ payload:+ patches.length === 0 ? [] : [{ namespace: "props" as const, patches }],+ };+};++export const getPropIdsToDelete = ({+ instanceComponent,+ instanceProps,+ propName,+}: {+ instanceComponent: string | undefined;+ instanceProps: Map<Prop["name"], Prop>;+ propName: Prop["name"];+}) => {+ const propIds = new Set<Prop["id"]>();+ const prop = instanceProps.get(propName);+ if (prop) {+ propIds.add(prop.id);+ }+ if (instanceComponent === "Image" && propName === "src") {+ const widthProp = instanceProps.get("width");+ if (widthProp) {+ propIds.add(widthProp.id);+ }+ const heightProp = instanceProps.get("height");+ if (heightProp) {+ propIds.add(heightProp.id);+ }+ }+ return propIds;+};++export const getPropDeletePlan = ({+ instance,+ props,+ propName,+}: {+ instance: Instance;+ props: Iterable<Prop>;+ propName: Prop["name"];+}) => {+ const instanceProps = new Map<Prop["name"], Prop>();+ for (const prop of props) {+ if (prop.instanceId === instance.id) {+ instanceProps.set(prop.name, prop);+ }+ }+ const propIds = getPropIdsToDelete({+ instanceComponent: instance.component,+ instanceProps,+ propName,+ });+ const propById = new Map(+ Array.from(instanceProps.values(), (prop) => [prop.id, prop])+ );+ const resourceIds = new Set<string>();+ for (const propId of propIds) {+ const prop = propById.get(propId);+ if (prop?.type === "resource") {+ resourceIds.add(prop.value);+ }+ }+ return { propIds, resourceIds };+};++export const createPropDeletePayload = ({+ deletions,+ instances,+ props,+}: {+ deletions: Array<{ instanceId: Instance["id"]; name: Prop["name"] }>;+ instances: Map<Instance["id"], Instance>;+ props: Iterable<Prop>;+}) => {+ const propIds = new Set<string>();+ const resourceIds = new Set<string>();+ for (const deletion of deletions) {+ const instance = instances.get(deletion.instanceId);+ if (instance === undefined) {+ return {+ missingInstanceId: deletion.instanceId,+ propIds: [],+ resourceIds: [],+ payload: [],+ };+ }+ const plan = getPropDeletePlan({+ instance,+ props,+ propName: deletion.name,+ });+ for (const propId of plan.propIds) {+ propIds.add(propId);+ }+ for (const resourceId of plan.resourceIds) {+ resourceIds.add(resourceId);+ }+ }+ const propIdList = Array.from(propIds);+ const resourceIdList = Array.from(resourceIds);+ return {+ propIds: propIdList,+ resourceIds: resourceIdList,+ payload: [+ ...(propIdList.length === 0+ ? []+ : [+ {+ namespace: "props" as const,+ patches: propIdList.map((propId) => ({+ op: "remove" as const,+ path: [propId],+ })),+ },+ ]),+ ...(resourceIdList.length === 0+ ? []+ : [+ {+ namespace: "resources" as const,+ patches: resourceIdList.map((resourceId) => ({+ op: "remove" as const,+ path: [resourceId],+ })),+ },+ ]),+ ],+ };+};++export const createPropRenamePayload = ({+ props,+ renames,+}: {+ props: Iterable<Prop>;+ renames: Array<{+ propId: Prop["id"];+ name: Prop["name"];+ propIdPrefix?: string;+ }>;+}) => {+ const propById = new Map(Array.from(props, (prop) => [prop.id, prop]));+ const patches = renames.flatMap(({ propId, name, propIdPrefix }) => {+ const prop = propById.get(propId);+ if (prop === undefined) {+ return [];+ }+ const nextProp = {+ ...prop,+ id: propIdPrefix === undefined ? prop.id : `${propIdPrefix}:${name}`,+ name,+ };+ return [+ { op: "remove" as const, path: [prop.id] },+ { op: "add" as const, path: [nextProp.id], value: nextProp },+ ];+ });+ return {+ propIds: patches.flatMap((patch) =>+ patch.op === "remove" ? [] : [String(patch.path[0])]+ ),+ payload:+ patches.length === 0 ? [] : [{ namespace: "props" as const, patches }],+ };+};++const getRequiredPropState = (+ state: Pick<BuilderState, "instances" | "props">+) => {+ if (state.instances === undefined || state.props === undefined) {+ return throwBuilderRuntimeError(+ "BAD_REQUEST",+ "Instance or props namespace is missing"+ );+ }+ return { instances: state.instances, props: state.props };+};++const assertRuntimeInstance = (+ instances: Map<Instance["id"], Instance>,+ instanceId: Instance["id"]+) => {+ if (instances.has(instanceId) === false) {+ return throwBuilderRuntimeError("NOT_FOUND", "Instance not found");+ }+};++const throwPropErrors = (errors: string[]) =>+ throwBuilderRuntimeError("BAD_REQUEST", errors.join("\n"));++export const updateProps = (+ state: Pick<BuilderState, "instances" | "props">,+ input: { updates: Array<z.infer<typeof propValueInput>> },+ context: { createId: () => string }+) => {+ const { instances, props } = getRequiredPropState(state);+ const nextProps = input.updates.map((update) => {+ assertRuntimeInstance(instances, update.instanceId);+ const existing = findProp(props.values(), update.instanceId, update.name);+ const nextProp = createValidatedPropValueFromInput(+ { ...update, propId: update.propId ?? existing?.id },+ context.createId+ );+ if (nextProp.success === false) {+ return throwPropErrors(nextProp.errors);+ }+ return nextProp.prop;+ });+ const { payload, propIds } = createPropUpsertPayload({+ props: props.values(),+ nextProps,+ });+ return createRuntimeMutation({+ payload,+ result: { propIds },+ invalidatesNamespaces: ["props"],+ });+};++export const bindProps = (+ state: Pick<BuilderState, "instances" | "props">,+ input: { bindings: Array<z.infer<typeof propBindingInput>> },+ context: { createId: () => string }+) => {+ const { instances, props } = getRequiredPropState(state);+ const nextProps = input.bindings.map((binding) => {+ assertRuntimeInstance(instances, binding.instanceId);+ const existing = findProp(props.values(), binding.instanceId, binding.name);+ const nextProp = createValidatedPropBindingFromInput(+ { ...binding, propId: binding.propId ?? existing?.id },+ context.createId+ );+ if (nextProp.success === false) {+ return throwPropErrors(nextProp.errors);+ }+ return nextProp.prop;+ });+ const { payload, propIds } = createPropUpsertPayload({+ props: props.values(),+ nextProps,+ });+ return createRuntimeMutation({+ payload,+ result: { propIds },+ invalidatesNamespaces: ["props"],+ });+};++export const deleteProps = (+ state: Pick<BuilderState, "instances" | "props">,+ input: { deletions: Array<{ instanceId: string; name: string }> }+) => {+ const { instances, props } = getRequiredPropState(state);+ const { missingInstanceId, payload, propIds } = createPropDeletePayload({+ instances,+ props: props.values(),+ deletions: input.deletions,+ });+ if (missingInstanceId !== undefined) {+ return throwBuilderRuntimeError("NOT_FOUND", "Instance not found");+ }+ return createRuntimeMutation({+ payload,+ result: { propIds },+ invalidatesNamespaces: ["props", "resources"],+ });+};diff --git a/packages/project-build/src/runtime/registry.test.ts b/packages/project-build/src/runtime/registry.test.tsnew file mode 100644index 0000000000..1d028e4540--- /dev/null+++ b/packages/project-build/src/runtime/registry.test.ts@@ -0,0 +1,417 @@+import { describe, expect, test } from "vitest";+import { runtimeOperationContracts } from "../contracts/builder-runtime";+import { builderRuntimeCutoverManifests } from "./cutover";+import {+ builderRuntimeOperations,+ executeBuilderRuntimeOperation,+ getBuilderRuntimeOperation,+} from "./registry";+import { getPage, listFolders, listPages } from "./pages";+import { getStyleDeclarations, listDesignTokens } from "./styles";+import {+ inspectInstance,+ listTextInstances,+ updateTextInstance,+} from "./instances";+import { listDataVariables, listResources } from "./data";+import { bindProps, deleteProps, updateProps } from "./props";+import type { BuilderRuntimeContext } from "./context";+import type { BuilderState } from "../state/builder-state";++const context: BuilderRuntimeContext = {+ createId: () => "id",+ now: () => new Date("2026-01-01T00:00:00.000Z"),+};++const state = {+ pages: {+ homePageId: "home",+ rootFolderId: "root",+ pages: new Map([+ [+ "home",+ {+ id: "home",+ name: "Home",+ title: "Home",+ path: "",+ rootInstanceId: "body",+ meta: {},+ },+ ],+ [+ "post",+ {+ id: "post",+ name: "Post",+ title: "Post",+ path: "/post",+ rootInstanceId: "post-body",+ meta: {+ description: "Post description",+ excludePageFromSearch: "true",+ },+ },+ ],+ ]),+ folders: new Map([+ [+ "root",+ {+ id: "root",+ name: "Root",+ slug: "",+ children: ["home", "blog"],+ },+ ],+ [+ "blog",+ {+ id: "blog",+ name: "Blog",+ slug: "blog",+ children: ["post"],+ },+ ],+ ]),+ },+ instances: new Map([+ [+ "body",+ {+ type: "instance",+ id: "body",+ component: "Body",+ tag: "body",+ children: [{ type: "id", value: "heading" }],+ },+ ],+ [+ "heading",+ {+ type: "instance",+ id: "heading",+ component: "Text",+ tag: "h1",+ label: "Hero",+ children: [{ type: "text", value: "Hello" }],+ },+ ],+ ]),+ props: new Map([+ [+ "prop",+ {+ id: "prop",+ instanceId: "heading",+ name: "title",+ type: "string",+ value: "Heading",+ },+ ],+ [+ "resourceProp",+ {+ id: "resourceProp",+ instanceId: "heading",+ name: "src",+ type: "resource",+ value: "resource",+ },+ ],+ ]),+ styleSources: new Map([+ ["local", { type: "local", id: "local" }],+ ["token", { type: "token", id: "token", name: "Brand" }],+ ]),+ styleSourceSelections: new Map([+ ["heading", { instanceId: "heading", values: ["token", "local"] }],+ ]),+ styles: new Map([+ [+ "local:base::color",+ {+ styleSourceId: "local",+ breakpointId: "base",+ state: undefined,+ property: "color",+ value: { type: "keyword", value: "red" },+ },+ ],+ [+ "token:base::color",+ {+ styleSourceId: "token",+ breakpointId: "base",+ state: undefined,+ property: "color",+ value: { type: "keyword", value: "blue" },+ },+ ],+ ]),+ dataSources: new Map([+ [+ "variable",+ {+ id: "variable",+ type: "variable",+ name: "Title",+ scopeInstanceId: "heading",+ value: { type: "string", value: "Hello" },+ },+ ],+ [+ "resourceDataSource",+ {+ id: "resourceDataSource",+ type: "resource",+ name: "Posts",+ scopeInstanceId: "heading",+ resourceId: "resource",+ },+ ],+ ]),+ resources: new Map([+ [+ "resource",+ {+ id: "resource",+ name: "Posts",+ method: "get",+ url: `"/posts"`,+ headers: [],+ searchParams: [],+ },+ ],+ ]),+ assets: new Map(),+ breakpoints: new Map(),+} satisfies BuilderState;++test("runtime operation registry implements every runtime contract", () => {+ const contractIds = runtimeOperationContracts.map((contract) => contract.id);+ const operationIds = builderRuntimeOperations.map(+ (operation) => operation.id+ );++ expect(operationIds).toEqual(contractIds);+});++describe("builder runtime pages", () => {+ test("lists pages and folders from shared state", () => {+ expect(listPages(state, { includeFolders: true })).toMatchObject({+ pages: [+ { id: "home", path: "", isHome: true, parentFolderId: "root" },+ { id: "post", path: "/blog/post", parentFolderId: "blog" },+ ],+ folders: [+ { id: "root", children: ["home", "blog"] },+ { id: "blog", children: ["post"] },+ ],+ });++ expect(listFolders(state, { includePages: true })).toMatchObject({+ folders: [+ { id: "root", parentFolderId: undefined },+ { id: "blog", parentFolderId: "root" },+ ],+ pages: [{ id: "home" }, { id: "post" }],+ });+ });++ test("gets page details by id and path", () => {+ expect(getPage(state, { pageId: "post" })).toMatchObject({+ id: "post",+ path: "/blog/post",+ meta: {+ description: "Post description",+ excludePageFromSearch: true,+ documentType: "html",+ },+ });++ expect(+ executeBuilderRuntimeOperation({+ id: "pages.getByPath",+ state,+ input: { path: "/blog/post" },+ context,+ })+ ).toMatchObject({ id: "post" });+ });+});++describe("builder runtime read families", () => {+ test("reads instances and text nodes", () => {+ expect(+ executeBuilderRuntimeOperation({+ id: "instances.list",+ state,+ input: { pageId: "home" },+ context,+ })+ ).toMatchObject({+ instances: [+ { id: "body", depth: 0 },+ { id: "heading", depth: 1, label: "Hero" },+ ],+ });++ const inspectedInstance = inspectInstance(state, {+ instanceId: "heading",+ include: ["props", "styles", "sources"],+ });+ expect(inspectedInstance).toMatchObject({+ id: "heading",+ styles: [{ instanceId: "heading", property: "color" }],+ sources: ["token", "local"],+ });+ expect(inspectedInstance.props).toEqual(+ expect.arrayContaining([expect.objectContaining({ id: "prop" })])+ );++ expect(listTextInstances(state, { contains: "Hello" })).toMatchObject({+ texts: [{ instanceId: "heading", childIndex: 0, value: "Hello" }],+ });+ });++ test("builds text update mutations", () => {+ expect(+ updateTextInstance(state, {+ instanceId: "heading",+ childIndex: 0,+ text: "Updated",+ })+ ).toMatchObject({+ kind: "mutation",+ noop: false,+ payload: [+ {+ namespace: "instances",+ patches: [+ {+ op: "replace",+ path: ["heading", "children", 0],+ value: { type: "text", value: "Updated" },+ },+ ],+ },+ ],+ result: { instanceId: "heading", childIndex: 0, mode: "text" },+ });++ expect(+ updateTextInstance(state, {+ instanceId: "heading",+ childIndex: 0,+ text: "Hello",+ })+ ).toMatchObject({+ noop: true,+ payload: [],+ result: { instanceId: "heading", childIndex: 0, mode: "text" },+ });+ });++ test("builds prop mutations", () => {+ expect(+ updateProps(+ state,+ {+ updates: [+ {+ instanceId: "heading",+ name: "title",+ type: "string",+ value: "Updated",+ },+ ],+ },+ context+ )+ ).toMatchObject({+ kind: "mutation",+ noop: false,+ result: { propIds: ["prop"] },+ payload: [{ namespace: "props" }],+ });++ expect(+ bindProps(+ state,+ {+ bindings: [+ {+ instanceId: "heading",+ name: "title",+ binding: { type: "expression", value: "title" },+ },+ ],+ },+ context+ )+ ).toMatchObject({+ result: { propIds: ["prop"] },+ payload: [{ namespace: "props" }],+ });++ expect(+ deleteProps(state, {+ deletions: [{ instanceId: "heading", name: "src" }],+ })+ ).toMatchObject({+ result: { propIds: ["resourceProp"] },+ payload: [{ namespace: "props" }, { namespace: "resources" }],+ });+ });++ test("reads styles, tokens, variables, and resources", () => {+ expect(+ getStyleDeclarations(state, { instanceIds: ["heading"] })+ ).toMatchObject({+ declarations: [{ instanceId: "heading", property: "color" }],+ });+ expect(listDesignTokens(state, { withUsage: true })).toMatchObject({+ tokens: [{ id: "token", usageCount: 1 }],+ });+ expect(listDataVariables(state)).toMatchObject({+ variables: [{ id: "variable", scopeInstanceId: "heading" }],+ });+ expect(listResources(state)).toMatchObject({+ resources: [{ id: "resource", dataSourceId: "resourceDataSource" }],+ });+ });+});++describe("builder runtime registry", () => {+ test("implements every cutover operation", () => {+ for (const manifest of builderRuntimeCutoverManifests) {+ for (const operationId of manifest.operationIds) {+ expect(getBuilderRuntimeOperation(operationId).id).toBe(operationId);+ }+ }+ });++ test("uses runtime context for ids in migrated mutations", () => {+ const duplicateWithDeterministicIds = () => {+ let nextId = 0;+ return executeBuilderRuntimeOperation({+ id: "pages.duplicate",+ state,+ input: {+ projectId: "project-1",+ pageId: "home",+ parentFolderId: "root",+ },+ context: {+ ...context,+ createId: () => `runtime-id-${++nextId}`,+ },+ });+ };++ expect(duplicateWithDeterministicIds()).toEqual(+ duplicateWithDeterministicIds()+ );+ });+});diff --git a/packages/project-build/src/runtime/registry.ts b/packages/project-build/src/runtime/registry.tsnew file mode 100644index 0000000000..efb8e84dfa--- /dev/null+++ b/packages/project-build/src/runtime/registry.ts@@ -0,0 +1,399 @@+import type { RuntimeOperationId } from "../contracts/builder-runtime";+import type { BuilderState } from "../state/builder-state";+import type { BuilderRuntimeContext } from "./context";+import * as assets from "./assets";+import * as data from "./data";+import * as instances from "./instances";+import * as pageCopy from "./page-copy";+import * as pages from "./pages";+import * as projectSettings from "./project-settings";+import * as props from "./props";+import * as styles from "./styles";++export type BuilderRuntimeOperation<Input = unknown, Result = unknown> = {+ id: RuntimeOperationId;+ execute: (args: {+ state: BuilderState;+ input: Input;+ context: BuilderRuntimeContext;+ }) => Result;+};++const runtimeOperation = <Input, Result>(+ id: RuntimeOperationId,+ execute: BuilderRuntimeOperation<Input, Result>["execute"]+): BuilderRuntimeOperation<Input, Result> => ({ id, execute });++export const builderRuntimeOperations = [+ runtimeOperation("pages.list", ({ state, input }) =>+ pages.listPages(state, input as Parameters<typeof pages.listPages>[1])+ ),+ runtimeOperation("pages.get", ({ state, input }) =>+ pages.getPage(state, input as Parameters<typeof pages.getPage>[1])+ ),+ runtimeOperation("pages.getByPath", ({ state, input }) =>+ pages.getPageByPath(+ state,+ input as Parameters<typeof pages.getPageByPath>[1]+ )+ ),+ runtimeOperation("pages.create", ({ state, input, context }) =>+ pages.createPage(+ state,+ input as Parameters<typeof pages.createPage>[1],+ context+ )+ ),+ runtimeOperation("pages.update", ({ state, input }) =>+ pages.updatePage(state, input as Parameters<typeof pages.updatePage>[1])+ ),+ runtimeOperation("projectSettings.get", ({ state }) =>+ projectSettings.getProjectSettings(state)+ ),+ runtimeOperation("projectSettings.update", ({ state, input }) =>+ projectSettings.updateProjectSettings(+ state,+ input as Parameters<typeof projectSettings.updateProjectSettings>[1]+ )+ ),+ runtimeOperation("redirects.list", ({ state }) =>+ projectSettings.listRedirects(state)+ ),+ runtimeOperation("redirects.create", ({ state, input }) =>+ projectSettings.createRedirect(+ state,+ input as Parameters<typeof projectSettings.createRedirect>[1]+ )+ ),+ runtimeOperation("redirects.update", ({ state, input }) =>+ projectSettings.updateRedirect(+ state,+ input as Parameters<typeof projectSettings.updateRedirect>[1]+ )+ ),+ runtimeOperation("redirects.delete", ({ state, input }) =>+ projectSettings.deleteRedirect(+ state,+ input as Parameters<typeof projectSettings.deleteRedirect>[1]+ )+ ),+ runtimeOperation("breakpoints.list", ({ state }) =>+ projectSettings.listBreakpoints(state)+ ),+ runtimeOperation("breakpoints.create", ({ state, input }) =>+ projectSettings.createBreakpoint(+ state,+ input as Parameters<typeof projectSettings.createBreakpoint>[1]+ )+ ),+ runtimeOperation("breakpoints.update", ({ state, input }) =>+ projectSettings.updateBreakpoint(+ state,+ input as Parameters<typeof projectSettings.updateBreakpoint>[1]+ )+ ),+ runtimeOperation("breakpoints.delete", ({ state, input }) =>+ projectSettings.deleteBreakpoint(+ state,+ input as Parameters<typeof projectSettings.deleteBreakpoint>[1]+ )+ ),+ runtimeOperation("pages.delete", ({ state, input }) =>+ pages.deletePage(state, input as Parameters<typeof pages.deletePage>[1])+ ),+ runtimeOperation("pages.duplicate", ({ state, input, context }) =>+ pageCopy.duplicatePage(+ state,+ input as Parameters<typeof pageCopy.duplicatePage>[1],+ context+ )+ ),+ runtimeOperation("pageTemplates.list", ({ state }) =>+ pageCopy.listPageTemplates(state)+ ),+ runtimeOperation("pageTemplates.createPage", ({ state, input, context }) =>+ pageCopy.createPageFromTemplate(+ state,+ input as Parameters<typeof pageCopy.createPageFromTemplate>[1],+ context+ )+ ),+ runtimeOperation("folders.list", ({ state, input }) =>+ pages.listFolders(state, input as Parameters<typeof pages.listFolders>[1])+ ),+ runtimeOperation("folders.create", ({ state, input, context }) =>+ pages.createFolder(+ state,+ input as Parameters<typeof pages.createFolder>[1],+ context+ )+ ),+ runtimeOperation("folders.update", ({ state, input }) =>+ pages.updateFolder(state, input as Parameters<typeof pages.updateFolder>[1])+ ),+ runtimeOperation("folders.delete", ({ state, input }) =>+ pages.deleteFolder(state, input as Parameters<typeof pages.deleteFolder>[1])+ ),+ runtimeOperation("instances.list", ({ state, input }) =>+ instances.listInstances(+ state,+ input as Parameters<typeof instances.listInstances>[1]+ )+ ),+ runtimeOperation("instances.inspect", ({ state, input }) =>+ instances.inspectInstance(+ state,+ input as Parameters<typeof instances.inspectInstance>[1]+ )+ ),+ runtimeOperation("instances.append", ({ state, input, context }) =>+ instances.appendInstances(+ state,+ input as Parameters<typeof instances.appendInstances>[1],+ context+ )+ ),+ runtimeOperation("instances.move", ({ state, input }) =>+ instances.moveInstances(+ state,+ input as Parameters<typeof instances.moveInstances>[1]+ )+ ),+ runtimeOperation("instances.clone", ({ state, input, context }) =>+ instances.cloneInstance(+ state,+ input as Parameters<typeof instances.cloneInstance>[1],+ context+ )+ ),+ runtimeOperation("instances.delete", ({ state, input }) =>+ instances.deleteInstances(+ state,+ input as Parameters<typeof instances.deleteInstances>[1]+ )+ ),+ runtimeOperation("instances.updateProps", ({ state, input, context }) =>+ props.updateProps(+ state,+ input as Parameters<typeof props.updateProps>[1],+ context+ )+ ),+ runtimeOperation("instances.deleteProps", ({ state, input }) =>+ props.deleteProps(state, input as Parameters<typeof props.deleteProps>[1])+ ),+ runtimeOperation("instances.bindProps", ({ state, input, context }) =>+ props.bindProps(+ state,+ input as Parameters<typeof props.bindProps>[1],+ context+ )+ ),+ runtimeOperation("instances.listTexts", ({ state, input }) =>+ instances.listTextInstances(+ state,+ input as Parameters<typeof instances.listTextInstances>[1]+ )+ ),+ runtimeOperation("instances.updateText", ({ state, input }) =>+ instances.updateTextInstance(+ state,+ input as Parameters<typeof instances.updateTextInstance>[1]+ )+ ),+ runtimeOperation("styles.getDeclarations", ({ state, input }) =>+ styles.getStyleDeclarations(+ state,+ input as Parameters<typeof styles.getStyleDeclarations>[1]+ )+ ),+ runtimeOperation("styles.updateDeclarations", ({ state, input, context }) =>+ styles.updateStyleDeclarations(+ state,+ input as Parameters<typeof styles.updateStyleDeclarations>[1],+ context+ )+ ),+ runtimeOperation("styles.deleteDeclarations", ({ state, input }) =>+ styles.deleteStyleDeclarations(+ state,+ input as Parameters<typeof styles.deleteStyleDeclarations>[1]+ )+ ),+ runtimeOperation("styles.replaceValues", ({ state, input }) =>+ styles.replaceStyleValues(+ state,+ input as Parameters<typeof styles.replaceStyleValues>[1]+ )+ ),+ runtimeOperation("designTokens.list", ({ state, input }) =>+ styles.listDesignTokens(+ state,+ input as Parameters<typeof styles.listDesignTokens>[1]+ )+ ),+ runtimeOperation("designTokens.create", ({ state, input, context }) =>+ styles.createDesignTokens(+ state,+ input as Parameters<typeof styles.createDesignTokens>[1],+ context+ )+ ),+ runtimeOperation("designTokens.updateStyles", ({ state, input }) =>+ styles.updateDesignTokenStyles(+ state,+ input as Parameters<typeof styles.updateDesignTokenStyles>[1]+ )+ ),+ runtimeOperation("designTokens.deleteStyles", ({ state, input }) =>+ styles.deleteDesignTokenStyles(+ state,+ input as Parameters<typeof styles.deleteDesignTokenStyles>[1]+ )+ ),+ runtimeOperation("designTokens.attach", ({ state, input }) =>+ styles.attachDesignToken(+ state,+ input as Parameters<typeof styles.attachDesignToken>[1]+ )+ ),+ runtimeOperation("designTokens.detach", ({ state, input }) =>+ styles.detachDesignToken(+ state,+ input as Parameters<typeof styles.detachDesignToken>[1]+ )+ ),+ runtimeOperation("designTokens.extract", ({ state, input, context }) =>+ styles.extractDesignToken(+ state,+ input as Parameters<typeof styles.extractDesignToken>[1],+ context+ )+ ),+ runtimeOperation("cssVariables.list", ({ state, input }) =>+ styles.listCssVariables(+ state,+ input as Parameters<typeof styles.listCssVariables>[1]+ )+ ),+ runtimeOperation("cssVariables.define", ({ state, input, context }) =>+ styles.defineCssVariables(+ state,+ input as Parameters<typeof styles.defineCssVariables>[1],+ context+ )+ ),+ runtimeOperation("cssVariables.delete", ({ state, input }) =>+ styles.deleteCssVariables(+ state,+ input as Parameters<typeof styles.deleteCssVariables>[1]+ )+ ),+ runtimeOperation("cssVariables.rewriteRefs", ({ state, input }) =>+ styles.rewriteCssVariableRefs(+ state,+ input as Parameters<typeof styles.rewriteCssVariableRefs>[1]+ )+ ),+ runtimeOperation("variables.list", ({ state, input }) =>+ data.listDataVariables(+ state,+ input as Parameters<typeof data.listDataVariables>[1]+ )+ ),+ runtimeOperation("variables.create", ({ state, input, context }) =>+ data.createDataVariable(+ state,+ input as Parameters<typeof data.createDataVariable>[1],+ context+ )+ ),+ runtimeOperation("variables.update", ({ state, input }) =>+ data.updateDataVariable(+ state,+ input as Parameters<typeof data.updateDataVariable>[1]+ )+ ),+ runtimeOperation("variables.delete", ({ state, input }) =>+ data.deleteDataVariable(+ state,+ input as Parameters<typeof data.deleteDataVariable>[1]+ )+ ),+ runtimeOperation("resources.list", ({ state, input }) =>+ data.listResources(state, input as Parameters<typeof data.listResources>[1])+ ),+ runtimeOperation("resources.create", ({ state, input, context }) =>+ data.createResource(+ state,+ input as Parameters<typeof data.createResource>[1],+ context+ )+ ),+ runtimeOperation("resources.update", ({ state, input }) =>+ data.updateResource(+ state,+ input as Parameters<typeof data.updateResource>[1]+ )+ ),+ runtimeOperation("resources.delete", ({ state, input }) =>+ data.deleteResource(+ state,+ input as Parameters<typeof data.deleteResource>[1]+ )+ ),+ runtimeOperation("assets.list", ({ state, input }) =>+ assets.listAssets(state, input as Parameters<typeof assets.listAssets>[1])+ ),+ runtimeOperation("assets.findUsage", ({ state, input }) =>+ assets.findAssetUsage(+ state,+ input as Parameters<typeof assets.findAssetUsage>[1]+ )+ ),+ runtimeOperation("assets.replace", ({ state, input }) =>+ assets.replaceAsset(+ state,+ input as Parameters<typeof assets.replaceAsset>[1]+ )+ ),+ runtimeOperation("assets.delete", ({ state, input }) =>+ assets.deleteAssets(+ state,+ input as Parameters<typeof assets.deleteAssets>[1]+ )+ ),+] as const satisfies readonly BuilderRuntimeOperation[];++const builderRuntimeOperationById: ReadonlyMap<+ string,+ BuilderRuntimeOperation+> = new Map(+ builderRuntimeOperations.map((operation) => [operation.id, operation])+);++export const getBuilderRuntimeOperation = (id: string) => {+ const operation = builderRuntimeOperationById.get(id);+ if (operation === undefined) {+ throw new Error(`Unknown builder runtime operation "${id}".`);+ }+ return operation;+};++export const executeBuilderRuntimeOperation = <Result = unknown>({+ id,+ state,+ input,+ context,+}: {+ id: string;+ state: BuilderState;+ input: unknown;+ context: BuilderRuntimeContext;+}): Result => {+ return getBuilderRuntimeOperation(id).execute({+ state,+ input,+ context,+ }) as Result;+};diff --git a/packages/project-build/src/runtime/style-copy.test.ts b/packages/project-build/src/runtime/style-copy.test.tsnew file mode 100644index 0000000000..a6956409d8--- /dev/null+++ b/packages/project-build/src/runtime/style-copy.test.ts@@ -0,0 +1,279 @@+import { describe, expect, test } from "vitest";+import type { StyleProperty, StyleValue } from "@webstudio-is/css-engine";+import {+ getStyleDeclKey,+ ROOT_INSTANCE_ID,+ type Breakpoint,+ type StyleDecl,+ type StyleSource,+ type StyleSourceSelection,+ type StyleSourceSelections,+ type StyleSources,+ type Styles,+} from "@webstudio-is/sdk";+import {+ collectStyleSourcesFromInstances,+ detectTokenConflicts,+ findTokenWithMatchingStyles,+ getStyleSourceStylesSignature,+ insertLocalStyleSourcesWithNewIds,+ insertPortalLocalStyleSources,+ insertStyleSources,+ insertTokenStyleSources,+} from "./style-copy";++const toMap = <T extends { id: string }>(items: T[]) =>+ new Map(items.map((item) => [item.id, item] as const));++const style = (+ styleSourceId: string,+ breakpointId: string,+ property: StyleProperty,+ value: StyleValue+): StyleDecl => ({+ styleSourceId,+ breakpointId,+ property,+ value,+});++const styleMap = (styles: StyleDecl[]) =>+ new Map(styles.map((item) => [getStyleDeclKey(item), item]));++const token = (id: string, name: string): StyleSource => ({+ type: "token",+ id,+ name,+});++const local = (id: string): StyleSource => ({ type: "local", id });++const baseBreakpoints = toMap<Breakpoint>([{ id: "base", label: "Base" }]);+const red = { type: "keyword", value: "red" } satisfies StyleValue;+const blue = { type: "keyword", value: "blue" } satisfies StyleValue;++describe("token conflict helpers", () => {+ test("creates stable style signatures independent of declaration order", () => {+ const first = [+ style("token", "base", "color", red),+ style("token", "base", "backgroundColor", blue),+ ];+ const second = [...first].reverse();++ expect(+ getStyleSourceStylesSignature("token", first, baseBreakpoints, new Map())+ ).toBe(+ getStyleSourceStylesSignature("token", second, baseBreakpoints, new Map())+ );+ });++ test("finds matching tokens and detects conflicting tokens", () => {+ const existingStyles = [style("existing", "base", "color", red)];++ expect(+ findTokenWithMatchingStyles({+ tokenName: "Primary",+ tokenStyles: [style("incoming", "base", "color", red)],+ existingTokens: [token("existing", "Primary")],+ existingStyles,+ breakpoints: baseBreakpoints,+ mergedBreakpointIds: new Map(),+ })+ ).toMatchObject({+ hasConflict: false,+ matchingToken: token("existing", "Primary"),+ });++ expect(+ findTokenWithMatchingStyles({+ tokenName: "Primary",+ tokenStyles: [style("incoming", "base", "color", blue)],+ existingTokens: [token("existing", "Primary")],+ existingStyles,+ breakpoints: baseBreakpoints,+ mergedBreakpointIds: new Map(),+ }).hasConflict+ ).toBe(true);+ });++ test("detects token conflicts by name and different styles", () => {+ expect(+ detectTokenConflicts({+ fragmentStyleSources: [token("incoming", "Primary")],+ fragmentStyles: [style("incoming", "base", "color", blue)],+ existingStyleSources: toMap([token("existing", "Primary")]),+ existingStyles: styleMap([style("existing", "base", "color", red)]),+ breakpoints: baseBreakpoints,+ mergedBreakpointIds: new Map(),+ })+ ).toEqual([+ {+ tokenName: "Primary",+ fragmentTokenId: "incoming",+ fragmentToken: token("incoming", "Primary"),+ existingToken: token("existing", "Primary"),+ },+ ]);+ });+});++describe("style source insertion", () => {+ test("reuses matching tokens and suffixes conflicting incoming tokens", () => {+ const reused = insertStyleSources({+ fragmentStyleSources: [token("incoming", "Primary")],+ fragmentStyles: [style("incoming", "base", "color", red)],+ existingStyleSources: toMap([token("existing", "Primary")]),+ existingStyles: styleMap([style("existing", "base", "color", red)]),+ breakpoints: baseBreakpoints,+ mergedBreakpointIds: new Map(),+ });++ expect(reused.styleSourceIdMap.get("incoming")).toBe("existing");+ expect(reused.styleSourceIds.size).toBe(0);++ const conflicting = insertStyleSources({+ fragmentStyleSources: [token("incoming", "Primary")],+ fragmentStyles: [style("incoming", "base", "color", blue)],+ existingStyleSources: toMap([token("existing", "Primary")]),+ existingStyles: styleMap([style("existing", "base", "color", red)]),+ breakpoints: baseBreakpoints,+ mergedBreakpointIds: new Map(),+ });+ const insertedId = conflicting.styleSourceIdMap.get("incoming");++ expect(insertedId).toBeDefined();+ expect(conflicting.updatedStyleSources.get(insertedId ?? "")).toMatchObject(+ {+ type: "token",+ name: "Primary-1",+ }+ );+ });++ test("inserts token style sources and remaps declarations", () => {+ const styleSources: StyleSources = new Map();+ const styles: Styles = new Map();+ const styleSourceIdMap = insertTokenStyleSources({+ fragmentStyleSources: [token("incoming", "Primary")],+ fragmentStyles: [style("incoming", "old-base", "color", red)],+ styleSources,+ styles,+ breakpoints: baseBreakpoints,+ mergedBreakpointIds: new Map([["old-base", "base"]]),+ });+ const insertedId = styleSourceIdMap.get("incoming");++ expect(styleSources.get(insertedId ?? "")).toMatchObject({+ type: "token",+ name: "Primary",+ });+ expect(Array.from(styles.values())).toEqual([+ {+ ...style("incoming", "old-base", "color", red),+ breakpointId: "base",+ styleSourceId: insertedId,+ },+ ]);+ });++ test("inserts portal local style sources preserving ids", () => {+ const styleSources: StyleSources = new Map();+ const styleSourceSelections: StyleSourceSelections = new Map();+ const styles: Styles = new Map();++ insertPortalLocalStyleSources({+ fragmentStyleSources: [local("local"), token("token", "Primary")],+ fragmentStyleSourceSelections: [+ { instanceId: "portal", values: ["local", "token"] },+ ],+ fragmentStyles: [style("local", "old-base", "color", red)],+ instanceIds: new Set(["portal"]),+ styleSources,+ styleSourceSelections,+ styles,+ mergedBreakpointIds: new Map([["old-base", "base"]]),+ });++ expect(styleSources.get("local")).toEqual(local("local"));+ expect(styleSourceSelections.get("portal")).toEqual({+ instanceId: "portal",+ values: ["local", "token"],+ });+ expect(Array.from(styles.values())).toEqual([+ style("local", "base", "color", red),+ ]);+ });++ test("copies local style sources with new ids and maps selections", () => {+ const styleSources: StyleSources = new Map([+ ["existing-token", token("existing-token", "Primary")],+ ]);+ const styleSourceSelections: StyleSourceSelections = new Map([+ [+ ROOT_INSTANCE_ID,+ { instanceId: ROOT_INSTANCE_ID, values: ["existing-local"] },+ ],+ ]);+ const styles: Styles = new Map();++ insertLocalStyleSourcesWithNewIds({+ fragmentStyleSources: [local("local"), token("old-token", "Primary")],+ fragmentStyleSourceSelections: [+ { instanceId: "old-instance", values: ["local", "old-token"] },+ { instanceId: ROOT_INSTANCE_ID, values: ["local"] },+ ],+ fragmentStyles: [style("local", "old-base", "color", red)],+ fragmentInstanceIds: new Set(["old-instance", ROOT_INSTANCE_ID]),+ newInstanceIds: new Map([["old-instance", "new-instance"]]),+ styleSources,+ styleSourceSelections,+ styles,+ styleSourceIdMap: new Map([["old-token", "existing-token"]]),+ mergedBreakpointIds: new Map([["old-base", "base"]]),+ });++ const newSelection = styleSourceSelections.get("new-instance");+ expect(newSelection?.instanceId).toBe("new-instance");+ expect(newSelection?.values).toContain("existing-token");+ expect(newSelection?.values[0]).not.toBe("local");+ expect(Array.from(styles.values())[0]).toMatchObject({+ breakpointId: "base",+ property: "color",+ });+ });+});++test("collects selected style sources and styles from instances", () => {+ const styleSourceSelections: StyleSourceSelections = new Map([+ ["box", { instanceId: "box", values: ["local", "token"] }],+ ["other", { instanceId: "other", values: ["other-local"] }],+ ]);+ const styleSources: StyleSources = toMap([+ local("local"),+ token("token", "Primary"),+ local("other-local"),+ ]);+ const styles = styleMap([+ style("local", "base", "color", red),+ style("token", "base", "backgroundColor", blue),+ style("other-local", "base", "color", blue),+ ]);++ expect(+ collectStyleSourcesFromInstances({+ instanceIds: new Set(["box"]),+ styleSourceSelections,+ styleSources,+ styles,+ })+ ).toEqual({+ styleSourceSelectionsArray: [+ { instanceId: "box", values: ["local", "token"] },+ ] satisfies StyleSourceSelection[],+ styleSourcesMap: toMap([local("local"), token("token", "Primary")]),+ stylesArray: [+ style("local", "base", "color", red),+ style("token", "base", "backgroundColor", blue),+ ],+ });+});diff --git a/apps/builder/app/shared/style-source-utils.ts b/packages/project-build/src/runtime/style-copy.tssimilarity index 71%rename from apps/builder/app/shared/style-source-utils.tsrename to packages/project-build/src/runtime/style-copy.tsindex abb77c1707..1b8215d412 100644--- a/apps/builder/app/shared/style-source-utils.ts+++ b/packages/project-build/src/runtime/style-copy.ts@@ -1,27 +1,20 @@import { nanoid } from "nanoid";-import type {- Breakpoint,- Instance,- StyleDecl,- StyleSource,- StyleSourceSelection,- Styles,- StyleSources,- StyleSourceSelections,-} from "@webstudio-is/sdk";-import { getStyleDeclKey, ROOT_INSTANCE_ID } from "@webstudio-is/sdk";import { toValue } from "@webstudio-is/css-engine";-import type { ConflictResolution } from "./token-conflict-dialog";-import { removeByMutable } from "./array-utils";+import {+ getStyleDeclKey,+ ROOT_INSTANCE_ID,+ type Breakpoint,+ type Instance,+ type StyleDecl,+ type StyleSource,+ type StyleSourceSelection,+ type StyleSourceSelections,+ type StyleSources,+ type Styles,+} from "@webstudio-is/sdk";-export const isStyleSourceLocked = (styleSource: StyleSource | undefined) =>- styleSource?.type === "token" && styleSource.locked === true;+export type ConflictResolution = "ours" | "theirs" | "merge";-/**- * Generates a normalized CSS string for comparing style source styles.- * This creates a deterministic signature based on breakpoint, state, property, and value.- * The signature is normalized by sorting to ensure order-independent comparison.- */export const getStyleSourceStylesSignature = (styleSourceId: StyleSource["id"],styles: StyleDecl[],@@ -200,6 +193,7 @@ export const insertStyleSources = ({breakpoints,mergedBreakpointIds,conflictResolution = "theirs",+ createId = nanoid,}: {fragmentStyleSources: StyleSource[];fragmentStyles: StyleDecl[];@@ -209,6 +203,7 @@ export const insertStyleSources = ({mergedBreakpointIds: Map<Breakpoint["id"], Breakpoint["id"]>;/** How to handle conflicts: "theirs" = add suffix (keep incoming), "ours" = use existing token, "merge" = merge styles (theirs overrides ours) */conflictResolution?: ConflictResolution;+ createId?: () => string;}): {styleSourceIds: Set<StyleSource["id"]>;styleSourceIdMap: Map<StyleSource["id"], StyleSource["id"]>;@@ -237,7 +232,7 @@ export const insertStyleSources = ({styleSource.type satisfies "token";const originalFragmentTokenId = styleSource.id;- const newTokenId = nanoid();+ const newTokenId = createId();// Check if there's an existing token with the same nameconst tokensWithSameName = existingTokensByName.get(styleSource.name);@@ -347,6 +342,7 @@ export const insertTokenStyleSources = ({breakpoints,mergedBreakpointIds,conflictResolution = "theirs",+ createId,}: {fragmentStyleSources: StyleSource[];fragmentStyles: StyleDecl[];@@ -355,6 +351,7 @@ export const insertTokenStyleSources = ({breakpoints: Map<Breakpoint["id"], Breakpoint>;mergedBreakpointIds: Map<Breakpoint["id"], Breakpoint["id"]>;conflictResolution?: ConflictResolution;+ createId?: () => string;}) => {const { styleSourceIds, styleSourceIdMap, updatedStyleSources } =insertStyleSources({@@ -365,6 +362,7 @@ export const insertTokenStyleSources = ({breakpoints,mergedBreakpointIds,conflictResolution,+ createId,});for (const [id, styleSource] of updatedStyleSources) {@@ -455,6 +453,7 @@ type InsertLocalStyleSourcesWithNewIdsOptions = {styleSources: StyleSources;styleSourceSelections: StyleSourceSelections;styles: Styles;+ createId?: () => string;} & (| {contentMode: true;@@ -485,6 +484,7 @@ export const insertLocalStyleSourcesWithNewIds = ({styleSources,styleSourceSelections,styles,+ createId = nanoid,contentMode = false,breakpoints,styleSourceIdMap = new Map(),@@ -560,7 +560,7 @@ export const insertLocalStyleSourcesWithNewIds = ({styleSourceId = existingLocalStyleSource.id;} else {// create new local styles- const newId = nanoid();+ const newId = createId();styleSources.set(newId, { ...newLocalStyleSource, id: newId });styleSourceId = newId;}@@ -611,185 +611,6 @@ export const insertLocalStyleSourcesWithNewIds = ({}};-/**- * Delete a style source and all its associated styles and selections.- * This is a mutable operation designed to be used within a transaction.- */-export const deleteStyleSourceMutable = ({- styleSourceId,- styleSources,- styleSourceSelections,- styles,-}: {- styleSourceId: StyleSource["id"];- styleSources: StyleSources;- styleSourceSelections: StyleSourceSelections;- styles: Styles;-}): void => {- styleSources.delete(styleSourceId);- for (const styleSourceSelection of styleSourceSelections.values()) {- if (styleSourceSelection.values.includes(styleSourceId)) {- removeByMutable(- styleSourceSelection.values,- (item) => item === styleSourceId- );- }- }- for (const [styleDeclKey, styleDecl] of styles) {- if (styleDecl.styleSourceId === styleSourceId) {- styles.delete(styleDeclKey);- }- }-};--/**- * Find all unused tokens in the style sources.- * A token is considered unused if it has no usages in any instance.- */-export const findUnusedTokens = ({- styleSources,- styleSourceUsages,-}: {- styleSources: StyleSources;- styleSourceUsages: Map<StyleSource["id"], Set<Instance["id"]>>;-}): StyleSource["id"][] => {- const unusedTokenIds: StyleSource["id"][] = [];- for (const styleSource of styleSources.values()) {- if (styleSource.type === "token") {- const usages = styleSourceUsages.get(styleSource.id);- if (usages === undefined || usages.size === 0) {- unusedTokenIds.push(styleSource.id);- }- }- }- return unusedTokenIds;-};--/**- * Delete multiple style sources (used for bulk unused token deletion).- * This is a mutable operation designed to be used within a transaction.- */-export const deleteStyleSourcesMutable = ({- styleSourceIds,- styleSources,- styleSourceSelections,- styles,-}: {- styleSourceIds: StyleSource["id"][];- styleSources: StyleSources;- styleSourceSelections: StyleSourceSelections;- styles: Styles;-}): void => {- for (const styleSourceId of styleSourceIds) {- deleteStyleSourceMutable({- styleSourceId,- styleSources,- styleSourceSelections,- styles,- });- }-};--export type RenameStyleSourceError =- | { type: "minlength"; id: StyleSource["id"] }- | { type: "duplicate"; id: StyleSource["id"] };--/**- * Validate and perform a style source rename.- * Returns an error if validation fails, undefined on success.- */-export const validateAndRenameStyleSource = ({- id,- name,- styleSources,-}: {- id: StyleSource["id"];- name: string;- styleSources: StyleSources;-}): RenameStyleSourceError | undefined => {- if (name.trim().length === 0) {- return { type: "minlength", id };- }- for (const styleSource of styleSources.values()) {- if (- styleSource.type === "token" &&- styleSource.name === name &&- styleSource.id !== id- ) {- return { type: "duplicate", id };- }- }- return;-};--/**- * Rename a style source (token).- * This is a mutable operation designed to be used within a transaction.- */-export const renameStyleSourceMutable = ({- id,- name,- styleSources,-}: {- id: StyleSource["id"];- name: string;- styleSources: StyleSources;-}): void => {- const styleSource = styleSources.get(id);- if (styleSource?.type === "token") {- styleSource.name = name;- }-};--export const toggleStyleSourceLockMutable = ({- id,- locked,- styleSources,-}: {- id: StyleSource["id"];- locked: boolean;- styleSources: StyleSources;-}): void => {- const styleSource = styleSources.get(id);- if (styleSource?.type !== "token") {- return;- }- if (locked) {- styleSource.locked = true;- return;- }- delete styleSource.locked;-};--/**- * Delete local style sources and their associated styles for a set of instances.- * This is typically used when deleting instances to clean up their local styles.- * This is a mutable operation designed to be used within a transaction.- */-export const deleteLocalStyleSourcesMutable = ({- localStyleSourceIds,- styleSources,- styles,-}: {- localStyleSourceIds: Set<StyleSource["id"]>;- styleSources: StyleSources;- styles: Styles;-}): void => {- for (const styleSourceId of localStyleSourceIds) {- styleSources.delete(styleSourceId);- }- for (const [styleDeclKey, styleDecl] of styles) {- if (localStyleSourceIds.has(styleDecl.styleSourceId)) {- styles.delete(styleDeclKey);- }- }-};--/**- * Collect all style sources and their selections from a set of instances.- * Returns the style sources, their selections, and the styles associated with them.- * This is typically used when extracting a fragment of instances.- */export const collectStyleSourcesFromInstances = ({instanceIds,styleSourceSelections,@@ -808,25 +629,23 @@ export const collectStyleSourcesFromInstances = ({const styleSourceSelectionsArray: StyleSourceSelection[] = [];const styleSourcesMap: StyleSources = new Map();- // Collect all style sources bound to these instancesfor (const instanceId of instanceIds) {const styleSourceSelection = styleSourceSelections.get(instanceId);- if (styleSourceSelection) {- styleSourceSelectionsArray.push(styleSourceSelection);- for (const styleSourceId of styleSourceSelection.values) {- if (styleSourcesMap.has(styleSourceId)) {- continue;- }- const styleSource = styleSources.get(styleSourceId);- if (styleSource === undefined) {- continue;- }+ if (styleSourceSelection === undefined) {+ continue;+ }+ styleSourceSelectionsArray.push(styleSourceSelection);+ for (const styleSourceId of styleSourceSelection.values) {+ if (styleSourcesMap.has(styleSourceId)) {+ continue;+ }+ const styleSource = styleSources.get(styleSourceId);+ if (styleSource !== undefined) {styleSourcesMap.set(styleSourceId, styleSource);}}}- // Collect styles bound to these style sourcesconst stylesArray: StyleDecl[] = [];for (const styleDecl of styles.values()) {if (styleSourcesMap.has(styleDecl.styleSourceId)) {@@ -840,89 +659,3 @@ export const collectStyleSourcesFromInstances = ({stylesArray,};};--/**- * Find tokens that have duplicates based on:- * 1. Identical styles (same CSS signature)- * 2. Same token name- *- * Returns a map where keys are token IDs and values are arrays of duplicate token IDs.- * Only includes tokens that have at least one duplicate.- */-export const findDuplicateTokens = ({- styleSources,- styles,- breakpoints,-}: {- styleSources: StyleSources;- styles: Styles;- breakpoints: Map<Breakpoint["id"], Breakpoint>;-}): Map<StyleSource["id"], StyleSource["id"][]> => {- const duplicatesMap = new Map<StyleSource["id"], StyleSource["id"][]>();- const stylesArray = Array.from(styles.values());- const tokens = Array.from(styleSources.values()).filter(- (source): source is Extract<StyleSource, { type: "token" }> =>- source.type === "token"- );-- // Build a map of signature -> token IDs- const signatureToTokenIds = new Map<string, StyleSource["id"][]>();- // Build a map of name -> token IDs- const nameToTokenIds = new Map<string, StyleSource["id"][]>();-- for (const token of tokens) {- // Group by signature (identical styles)- const signature = getStyleSourceStylesSignature(- token.id,- stylesArray,- breakpoints,- new Map()- );-- if (!signatureToTokenIds.has(signature)) {- signatureToTokenIds.set(signature, []);- }- signatureToTokenIds.get(signature)!.push(token.id);-- // Group by name (same token name)- if (!nameToTokenIds.has(token.name)) {- nameToTokenIds.set(token.name, []);- }- nameToTokenIds.get(token.name)!.push(token.id);- }-- // Build the duplicates map - include tokens with signature OR name duplicates- const processedTokens = new Set<StyleSource["id"]>();-- for (const [_signature, tokenIds] of signatureToTokenIds) {- if (tokenIds.length > 1) {- for (const tokenId of tokenIds) {- if (!duplicatesMap.has(tokenId)) {- duplicatesMap.set(tokenId, []);- }- const duplicates = tokenIds.filter((id) => id !== tokenId);- duplicatesMap.get(tokenId)!.push(...duplicates);- processedTokens.add(tokenId);- }- }- }-- for (const [_name, tokenIds] of nameToTokenIds) {- if (tokenIds.length > 1) {- for (const tokenId of tokenIds) {- if (!duplicatesMap.has(tokenId)) {- duplicatesMap.set(tokenId, []);- }- const duplicates = tokenIds.filter((id) => id !== tokenId);- // Avoid adding the same duplicate twice- for (const duplicate of duplicates) {- if (!duplicatesMap.get(tokenId)!.includes(duplicate)) {- duplicatesMap.get(tokenId)!.push(duplicate);- }- }- }- }- }-- return duplicatesMap;-};diff --git a/packages/project-build/src/runtime/style-utils.test.ts b/packages/project-build/src/runtime/style-utils.test.tsnew file mode 100644index 0000000000..acb6d07a3b--- /dev/null+++ b/packages/project-build/src/runtime/style-utils.test.ts@@ -0,0 +1,197 @@+import { expect, test } from "vitest";+import {+ getStyleDeclKey,+ type StyleDecl,+ type Styles,+ type StyleSource,+ type StyleSourceSelection,+} from "@webstudio-is/sdk";+import {+ cloneStyles,+ createStyleClonePayload,+ serializeStyleDeclarations,+} from "./style-utils";++const createStyleDecl = (+ styleSourceId: string,+ breakpointId: string,+ value?: string+): StyleDecl => {+ return {+ styleSourceId,+ breakpointId,+ property: "width",+ value: {+ type: "keyword",+ value: value ?? "value",+ },+ };+};++const createStyleDeclPair = (+ styleSourceId: string,+ breakpointId: string,+ state?: string,+ value?: string+) => {+ return [+ getStyleDeclKey({+ styleSourceId,+ breakpointId,+ state,+ property: "width",+ }),+ createStyleDecl(styleSourceId, breakpointId, value),+ ] as const;+};++test("clone styles with applied new style source ids", () => {+ const styles: Styles = new Map([+ createStyleDeclPair("styleSource1", "bp1"),+ createStyleDeclPair("styleSource2", "bp2"),+ createStyleDeclPair("styleSource1", "bp3"),+ createStyleDeclPair("styleSource3", "bp4"),+ createStyleDeclPair("styleSource1", "bp5"),+ createStyleDeclPair("styleSource3", "bp6"),+ ]);+ const clonedStyleSourceIds = new Map<StyleSource["id"], StyleSource["id"]>();+ clonedStyleSourceIds.set("styleSource2", "newStyleSource2");+ clonedStyleSourceIds.set("styleSource3", "newStyleSource3");+ expect(cloneStyles(styles, clonedStyleSourceIds)).toEqual([+ createStyleDecl("newStyleSource2", "bp2"),+ createStyleDecl("newStyleSource3", "bp4"),+ createStyleDecl("newStyleSource3", "bp6"),+ ]);+});++test("clones local styles while keeping design tokens shared", () => {+ const styleDecl: StyleDecl = {+ styleSourceId: "local-1",+ breakpointId: "base",+ property: "color",+ value: { type: "keyword", value: "red" },+ };+ const payload = createStyleClonePayload({+ styleSourceSelections: [+ { instanceId: "source-1", values: ["token-1", "local-1"] },+ ],+ styleSources: [+ { type: "local", id: "local-1" },+ { type: "token", id: "token-1", name: "Token" },+ ],+ styles: new Map([[getStyleDeclKey(styleDecl), styleDecl]]),+ nextIdById: new Map([["source-1", "clone-1"]]),+ createId: () => "local-copy",+ });++ expect(payload).toEqual([+ {+ namespace: "styleSources",+ patches: [+ {+ op: "add",+ path: ["local-copy"],+ value: { type: "local", id: "local-copy" },+ },+ ],+ },+ {+ namespace: "styleSourceSelections",+ patches: [+ {+ op: "add",+ path: ["clone-1"],+ value: {+ instanceId: "clone-1",+ values: ["token-1", "local-copy"],+ },+ },+ ],+ },+ {+ namespace: "styles",+ patches: [+ {+ op: "add",+ path: ["local-copy:base:color:"],+ value: { ...styleDecl, styleSourceId: "local-copy" },+ },+ ],+ },+ ]);+});++test("serializes direct and token style declarations for selected instances", () => {+ const styles: StyleDecl[] = [+ {+ styleSourceId: "local-1",+ breakpointId: "base",+ property: "color",+ value: { type: "keyword", value: "red" },+ },+ {+ styleSourceId: "token-1",+ breakpointId: "base",+ property: "backgroundColor",+ value: { type: "keyword", value: "blue" },+ },+ ];+ const styleSources: StyleSource[] = [+ { type: "local", id: "local-1" },+ { type: "token", id: "token-1", name: "Primary" },+ ];+ const styleSourceSelections: StyleSourceSelection[] = [+ { instanceId: "root-1", values: ["token-1", "local-1"] },+ ];++ expect(+ serializeStyleDeclarations({+ styles,+ styleSources,+ styleSourceSelections,+ instanceIds: new Set(["root-1"]),+ property: "color",+ })+ ).toEqual([+ {+ instanceId: "root-1",+ styleSourceId: "local-1",+ property: "color",+ value: { type: "keyword", value: "red" },+ breakpoint: "base",+ state: undefined,+ source: "local",+ },+ ]);+ expect(+ serializeStyleDeclarations({+ styles,+ styleSources,+ styleSourceSelections,+ instanceIds: new Set(["root-1"]),+ })+ ).toEqual([+ expect.objectContaining({+ styleSourceId: "local-1",+ source: "local",+ }),+ ]);+ expect(+ serializeStyleDeclarations({+ styles,+ styleSources,+ styleSourceSelections,+ instanceIds: new Set(["root-1"]),+ includeTokens: true,+ })+ ).toEqual([+ expect.objectContaining({+ styleSourceId: "local-1",+ source: "local",+ }),+ expect.objectContaining({+ styleSourceId: "token-1",+ source: "token",+ }),+ ]);+});diff --git a/packages/project-build/src/runtime/style-utils.ts b/packages/project-build/src/runtime/style-utils.tsnew file mode 100644index 0000000000..b556744d56--- /dev/null+++ b/packages/project-build/src/runtime/style-utils.ts@@ -0,0 +1,215 @@+import type {+ Instance,+ Styles,+ StyleDecl,+ StyleSource,+ StyleSourceSelection,+} from "@webstudio-is/sdk";+import { getStyleDeclKey } from "@webstudio-is/sdk";+import type { BuilderPatchChange } from "../contracts/patch";++export const serializeStyleDeclarations = ({+ styles,+ styleSources,+ styleSourceSelections,+ instanceIds,+ breakpoint,+ state,+ property,+ propertyFilter,+ includeTokens,+}: {+ styles: Iterable<StyleDecl>;+ styleSources: Iterable<StyleSource>;+ styleSourceSelections: Iterable<StyleSourceSelection>;+ instanceIds?: Set<Instance["id"]>;+ breakpoint?: string;+ state?: string;+ property?: string;+ propertyFilter?: string;+ includeTokens?: boolean;+}) => {+ const sourceById = new Map(+ Array.from(styleSources, (styleSource) => [styleSource.id, styleSource])+ );+ const selectionsBySource = new Map<StyleSource["id"], Instance["id"][]>();+ for (const selection of styleSourceSelections) {+ for (const styleSourceId of selection.values) {+ const list = selectionsBySource.get(styleSourceId) ?? [];+ list.push(selection.instanceId);+ selectionsBySource.set(styleSourceId, list);+ }+ }++ const declarations = [];+ for (const styleDecl of styles) {+ if (breakpoint !== undefined && styleDecl.breakpointId !== breakpoint) {+ continue;+ }+ if (state !== undefined && styleDecl.state !== state) {+ continue;+ }+ if (property !== undefined && styleDecl.property !== property) {+ continue;+ }+ if (+ propertyFilter !== undefined &&+ styleDecl.property.includes(propertyFilter) === false+ ) {+ continue;+ }+ const source = sourceById.get(styleDecl.styleSourceId);+ if (source?.type === "token" && includeTokens !== true) {+ continue;+ }+ const selectedInstanceIds =+ selectionsBySource.get(styleDecl.styleSourceId) ?? [];+ for (const instanceId of selectedInstanceIds) {+ if (instanceIds !== undefined && instanceIds.has(instanceId) === false) {+ continue;+ }+ declarations.push({+ instanceId,+ styleSourceId: styleDecl.styleSourceId,+ property: styleDecl.property,+ value: styleDecl.value,+ breakpoint: styleDecl.breakpointId,+ state: styleDecl.state,+ source: source?.type ?? "local",+ });+ }+ }+ return declarations;+};++export const cloneStyles = (+ styles: Styles,+ clonedStyleSourceIds: Map<StyleSource["id"], StyleSource["id"]>+) => {+ const clonedStyles: StyleDecl[] = [];+ for (const styleDecl of styles.values()) {+ const styleSourceId = clonedStyleSourceIds.get(styleDecl.styleSourceId);+ if (styleSourceId === undefined) {+ continue;+ }+ clonedStyles.push({+ ...styleDecl,+ styleSourceId,+ });+ }+ return clonedStyles;+};++export const createLocalStyleSourceClonePlan = ({+ styleSourceSelections,+ styleSources,+ newInstanceIds,+ createId,+}: {+ styleSourceSelections: Iterable<StyleSourceSelection>;+ styleSources: Iterable<StyleSource>;+ newInstanceIds: Map<Instance["id"], Instance["id"]>;+ createId: () => StyleSource["id"];+}) => {+ const styleSourceById = new Map(+ Array.from(styleSources, (styleSource) => [styleSource.id, styleSource])+ );+ const newLocalStyleSourceIds = new Map<+ StyleSource["id"],+ StyleSource["id"]+ >();+ const getNextStyleSourceId = (styleSourceId: StyleSource["id"]) => {+ const styleSource = styleSourceById.get(styleSourceId);+ if (styleSource?.type !== "local") {+ return styleSourceId;+ }+ let nextStyleSourceId = newLocalStyleSourceIds.get(styleSourceId);+ if (nextStyleSourceId === undefined) {+ nextStyleSourceId = createId();+ newLocalStyleSourceIds.set(styleSourceId, nextStyleSourceId);+ }+ return nextStyleSourceId;+ };++ const selections: StyleSourceSelection[] = [];+ for (const selection of styleSourceSelections) {+ const nextInstanceId = newInstanceIds.get(selection.instanceId);+ if (nextInstanceId === undefined) {+ continue;+ }+ selections.push({+ ...selection,+ instanceId: nextInstanceId,+ values: selection.values.map(getNextStyleSourceId),+ });+ }++ const localStyleSources: StyleSource[] = [];+ for (const [styleSourceId, nextStyleSourceId] of newLocalStyleSourceIds) {+ const styleSource = styleSourceById.get(styleSourceId);+ if (styleSource !== undefined) {+ localStyleSources.push({+ ...styleSource,+ id: nextStyleSourceId,+ });+ }+ }++ return {+ localStyleSources,+ localStyleSourceIds: newLocalStyleSourceIds,+ selections,+ };+};++export const createStyleClonePayload = ({+ styleSourceSelections,+ styleSources,+ styles,+ nextIdById,+ createId,+}: {+ styleSourceSelections: Iterable<StyleSourceSelection>;+ styleSources: Iterable<StyleSource>;+ styles: Styles;+ nextIdById: Map<Instance["id"], Instance["id"]>;+ createId: () => StyleSource["id"];+}): BuilderPatchChange[] => {+ const clonePlan = createLocalStyleSourceClonePlan({+ styleSourceSelections,+ styleSources,+ newInstanceIds: nextIdById,+ createId,+ });+ const changes: BuilderPatchChange[] = [+ {+ namespace: "styleSources",+ patches: clonePlan.localStyleSources.map((styleSource) => ({+ op: "add" as const,+ path: [styleSource.id],+ value: styleSource,+ })),+ },+ {+ namespace: "styleSourceSelections",+ patches: clonePlan.selections.map((selection) => ({+ op: "add" as const,+ path: [selection.instanceId],+ value: selection,+ })),+ },+ {+ namespace: "styles",+ patches: cloneStyles(styles, clonePlan.localStyleSourceIds).map(+ (styleDecl) => ({+ op: "add" as const,+ path: [getStyleDeclKey(styleDecl)],+ value: styleDecl,+ })+ ),+ },+ ];+ return changes.flatMap((change) =>+ change.patches.length === 0 ? [] : [change]+ );+};diff --git a/packages/project-build/src/runtime/styles.test.ts b/packages/project-build/src/runtime/styles.test.tsnew file mode 100644index 0000000000..1e76c873ed--- /dev/null+++ b/packages/project-build/src/runtime/styles.test.ts@@ -0,0 +1,3313 @@+import { enableMapSet } from "immer";+import { describe, expect, test } from "vitest";+import {+ type Breakpoint,+ getStyleDeclKey,+ type Instance,+ type StyleDecl,+ type StyleSource,+ type StyleSources,+ type StyleSourceSelection,+ type StyleSourceSelections,+ type Styles,+} from "@webstudio-is/sdk";+import type { StyleProperty, StyleValue } from "@webstudio-is/css-engine";+import {+ createCssVariableDeletePayload,+ createCssVariableReferenceRewritePayload,+ createCssVariableRootDefinePayload,+ createDesignTokenCreatePayload,+ createDesignTokenExtractionPayload,+ createDesignTokenStyleDeletePayload,+ createDesignTokenStyleInputs,+ createDesignTokenStyleUpdatePayload,+ createStyleDeclarationDeletePayload,+ createStyleDeclarationUpdatePayload,+ createStyleSourceSelectionAddPatch,+ createStyleSourceSelectionAddPlan,+ createStyleSourceSelectionAttachPayload,+ createStyleSourceSelectionDetachPayload,+ createStyleSourceSelectionRemovePatch,+ createStyleSourceSelectionRemovePlan,+ createStyleValueReplacementPayload,+ createTokenStyleSource,+ cssVariableValueInput,+ designTokenCreateInput,+ createDesignTokens,+ findDesignToken,+ findCssVariableUsagesByInstance,+ getDefinedCssVariableNames,+ getCssVariableDefinitionsByVariable,+ getInstanceIdByStyleSourceId,+ getReferencedCssVariables,+ getStyleSourceInsertionIndex,+ serializeCssVariables,+ createSelectedStyleDeclarationDeletePayload,+ createSelectedStyleDeclarationUpdatePayload,+ styleDeleteInput,+ styleReplaceInput,+ styleUpdateInput,+ defineCssVariables,+ deleteDesignTokenStyles,+ deleteStyleDeclarations,+ updateDesignTokenStyles,+ updateStyleDeclarations,+ validateCssVariableNameWithStyles,+ validateStyleSourceName,+} from "./styles";+import { createLocalStyleSourceClonePlan } from "./style-utils";+import {+ addStyleSourceToInstanceMutable,+ createLocalStyleSourcePatchPlan,+ createLocalStyleSourcePlan,+ createStyleDecl as createStyleDeclValue,+ createStyleDeclFromInput,+ deleteLocalStyleSourcesMutable,+ deleteStyleDeclMutable,+ deleteStyleSourceMutable,+ deleteStyleSourcesMutable,+ findDuplicateTokens,+ findUnusedTokens,+ getLocalStyleSourceId,+ getLocalStyleSourceIdWithCreated,+ getOrCreateLocalStyleSourceIdMutable,+ getStyleDeclKeyFromInput,+ isStyleSourceLocked,+ removeStyleSourceFromInstanceMutable,+ renameStyleSourceMutable,+ serializeDesignTokens,+ setStyleDeclMutable,+ toggleStyleSourceLockMutable,+ updateStyleDecl,+ validateAndRenameStyleSource,+} from "./styles";++const localStyleSource: StyleSource = {+ type: "local",+ id: "local-style-source",+};+const displayStyle: StyleDecl = {+ breakpointId: "base",+ styleSourceId: "local-style-source",+ property: "display",+ value: { type: "keyword", value: "flex" },+};+const displayStyleKey = getStyleDeclKey(displayStyle);++describe("selected style declaration payloads", () => {+ test("normalizes CSS property names in selected style declarations", () => {+ const fontSizeStyle: StyleDecl = {+ breakpointId: "base",+ styleSourceId: localStyleSource.id,+ property: "fontSize",+ value: { type: "unit", value: 24, unit: "px" },+ };+ const fontSizeStyleKey = getStyleDeclKey(fontSizeStyle);++ expect(+ createSelectedStyleDeclarationUpdatePayload({+ updates: [+ {+ instanceId: "box",+ styleSource: localStyleSource,+ styleSourceId: localStyleSource.id,+ property: "font-size",+ value: { type: "unit", value: 24, unit: "px" },+ },+ ],+ styleSources: new Map([[localStyleSource.id, localStyleSource]]),+ styleSourceSelections: [],+ styles: [],+ })+ ).toMatchObject({+ styleKeys: [fontSizeStyleKey],+ payload: expect.arrayContaining([+ {+ namespace: "styles",+ patches: [+ {+ op: "add",+ path: [fontSizeStyleKey],+ value: fontSizeStyle,+ },+ ],+ },+ ]),+ });+ });++ test("creates selected style source, selection, and declaration patches", () => {+ expect(+ createSelectedStyleDeclarationUpdatePayload({+ updates: [+ {+ instanceId: "box",+ styleSource: localStyleSource,+ styleSourceId: localStyleSource.id,+ breakpoint: "base",+ property: "display",+ value: { type: "keyword", value: "flex" },+ listed: true,+ },+ ],+ styleSources: new Map(),+ styleSourceSelections: [],+ styles: [],+ })+ ).toEqual({+ styleKeys: [displayStyleKey],+ payload: [+ {+ namespace: "styleSources",+ patches: [+ {+ op: "add",+ path: ["local-style-source"],+ value: localStyleSource,+ },+ ],+ },+ {+ namespace: "styleSourceSelections",+ patches: [+ {+ op: "add",+ path: ["box"],+ value: { instanceId: "box", values: ["local-style-source"] },+ },+ ],+ },+ {+ namespace: "styles",+ patches: [+ {+ op: "add",+ path: [displayStyleKey],+ value: {+ ...displayStyle,+ listed: true,+ },+ },+ ],+ },+ ],+ });+ });++ test("creates selected declaration delete payload", () => {+ const selection: StyleSourceSelection = {+ instanceId: "box",+ values: ["local-style-source"],+ };++ expect(+ createSelectedStyleDeclarationDeletePayload({+ deletions: [+ {+ styleSourceId: localStyleSource.id,+ breakpoint: "base",+ property: "display",+ },+ ],+ styles: [displayStyle],+ })+ ).toEqual({+ styleKeys: [displayStyleKey],+ payload: [+ {+ namespace: "styles",+ patches: [{ op: "remove", path: [displayStyleKey] }],+ },+ ],+ });+ expect(selection.values).toEqual(["local-style-source"]);+ });+});++describe("local style declaration payloads", () => {+ test("preserves listed flag", () => {+ expect(+ createStyleDeclarationUpdatePayload({+ updates: [+ {+ instanceId: "box",+ breakpoint: "base",+ property: "display",+ value: { type: "keyword", value: "flex" },+ listed: true,+ },+ ],+ styleSources: new Map(),+ styleSourceSelections: [],+ styles: [],+ createId: () => "local-style-source",+ }).payload+ ).toEqual([+ {+ namespace: "styleSources",+ patches: [+ {+ op: "add",+ path: ["local-style-source"],+ value: localStyleSource,+ },+ ],+ },+ {+ namespace: "styleSourceSelections",+ patches: [+ {+ op: "add",+ path: ["box"],+ value: { instanceId: "box", values: ["local-style-source"] },+ },+ ],+ },+ {+ namespace: "styles",+ patches: [+ {+ op: "add",+ path: [displayStyleKey],+ value: { ...displayStyle, listed: true },+ },+ ],+ },+ ]);+ });+});+const createCssVariableStyleDecl = (+ styleSourceId: string,+ property: string,+ value: string+): StyleDecl => ({+ styleSourceId,+ breakpointId: "base",+ property: property as StyleProperty,+ value: { type: "unparsed", value },+});++const createCssVariableId = () => "new-local";++describe("css variable usage", () => {+ test("parses css variable values used by the API", () => {+ expect(cssVariableValueInput.parse("10px")).toBe("10px");+ expect(+ cssVariableValueInput.parse({ type: "keyword", value: "red" })+ ).toEqual({+ type: "keyword",+ value: "red",+ });+ });++ test("finds defined css variable names", () => {+ expect(+ getDefinedCssVariableNames([+ createCssVariableStyleDecl("local", "--color", "red"),+ createCssVariableStyleDecl("local", "color", "var(--color)"),+ ])+ ).toEqual(new Set(["--color"]));+ });++ test("maps style sources to owning instances", () => {+ expect(+ getInstanceIdByStyleSourceId([+ { instanceId: "box", values: ["token", "local"] },+ ])+ ).toEqual(+ new Map([+ ["token", "box"],+ ["local", "box"],+ ])+ );+ });++ test("finds css variable usage counts and owning instances", () => {+ const styles = [+ createCssVariableStyleDecl("local-1", "--color", "red"),+ createCssVariableStyleDecl("local-2", "color", "var(--color)"),+ ];+ const props = [+ {+ id: "prop",+ instanceId: "embed",+ name: "code",+ type: "string",+ value: "var(--color)",+ },+ ] as const;++ expect(+ findCssVariableUsagesByInstance({+ styleSourceSelections: [+ { instanceId: "box", values: ["local-1"] },+ { instanceId: "text", values: ["local-2"] },+ ],+ styles,+ props,+ })+ ).toEqual({+ counts: new Map([["--color", 2]]),+ instances: new Map([["--color", new Set(["text", "embed"])]]),+ });+ });++ test("finds css variable definitions and references", () => {+ const styles = [+ createCssVariableStyleDecl("local-1", "--color", "red"),+ createCssVariableStyleDecl("local-2", "color", "var(--color)"),+ ];+ const props = [+ {+ id: "prop",+ instanceId: "embed",+ name: "code",+ type: "string",+ value: "var(--color)",+ },+ ] as const;++ expect(+ getCssVariableDefinitionsByVariable({+ styleSourceSelections: [+ { instanceId: "box", values: ["local-1"] },+ { instanceId: "text", values: ["local-2"] },+ ],+ styles,+ })+ ).toEqual(new Map([["--color", new Set(["box"])]]));+ expect(getReferencedCssVariables({ styles, props })).toEqual(+ new Set(["--color"])+ );+ });++ test("validates css variable names", () => {+ expect(+ validateCssVariableNameWithStyles({+ name: "",+ styles: [],+ })+ ).toEqual({+ type: "required",+ message: "CSS variable name cannot be empty",+ });+ expect(+ validateCssVariableNameWithStyles({+ name: "color",+ styles: [],+ })+ ).toEqual({+ type: "invalid",+ message: 'CSS variable name must start with "--"',+ });+ expect(+ validateCssVariableNameWithStyles({+ name: "--color",+ styles: [createCssVariableStyleDecl("local", "--color", "red")],+ })+ ).toEqual({+ type: "duplicate",+ message: 'CSS variable "--color" already exists',+ });+ expect(+ validateCssVariableNameWithStyles({+ name: "--color",+ currentProperty: "--color",+ styles: [createCssVariableStyleDecl("local", "--color", "red")],+ })+ ).toBeUndefined();+ });++ test("serializes css variables with scope and usage", () => {+ expect(+ serializeCssVariables({+ styles: [+ createCssVariableStyleDecl("local", "--color", "red"),+ createCssVariableStyleDecl("local", "color", "var(--color)"),+ ],+ props: [+ {+ id: "prop",+ instanceId: "box",+ name: "code",+ type: "string",+ value: "var(--color)",+ },+ ],+ styleSourceSelections: [{ instanceId: "box", values: ["local"] }],+ withUsage: true,+ })+ ).toEqual({+ vars: [+ {+ name: "--color",+ value: "red",+ scope: "box",+ usageCount: 2,+ },+ ],+ });+ });++ test("creates root css variable define payload with local style source", () => {+ const result = createCssVariableRootDefinePayload({+ rootInstanceId: "body",+ vars: { "--color": "red" },+ styleSources: new Map(),+ styleSourceSelections: [],+ styles: [],+ createId: createCssVariableId,+ });++ const localStyleSourceId = result.styleKeys[0]?.split(":")[0];+ expect(localStyleSourceId).toEqual(expect.any(String));+ expect(result).toEqual({+ payload: [+ {+ namespace: "styleSources",+ patches: [+ {+ op: "add",+ path: [localStyleSourceId],+ value: { type: "local", id: localStyleSourceId },+ },+ ],+ },+ {+ namespace: "styleSourceSelections",+ patches: [+ {+ op: "add",+ path: ["body"],+ value: { instanceId: "body", values: [localStyleSourceId] },+ },+ ],+ },+ {+ namespace: "styles",+ patches: [+ {+ op: "add",+ path: [`${localStyleSourceId}:base:--color:`],+ value: {+ styleSourceId: localStyleSourceId,+ breakpointId: "base",+ property: "--color",+ value: { type: "unparsed", value: "red" },+ },+ },+ ],+ },+ ],+ names: ["--color"],+ conflicts: [],+ styleKeys: [`${localStyleSourceId}:base:--color:`],+ missingRootStyleSource: false,+ });+ });++ test("reports css variable define conflicts and overwrites when requested", () => {+ const existing = createCssVariableStyleDecl("local", "--color", "red");+ expect(+ createCssVariableRootDefinePayload({+ rootInstanceId: "body",+ vars: { "--color": "blue" },+ styleSources: new Map([["local", { id: "local", type: "local" }]]),+ styleSourceSelections: [{ instanceId: "body", values: ["local"] }],+ styles: [existing],+ createId: createCssVariableId,+ }).conflicts+ ).toEqual(["--color"]);++ expect(+ createCssVariableRootDefinePayload({+ rootInstanceId: "body",+ vars: { "--color": "blue" },+ styleSources: new Map([["local", { id: "local", type: "local" }]]),+ styleSourceSelections: [{ instanceId: "body", values: ["local"] }],+ styles: [existing],+ overwrite: true,+ createId: createCssVariableId,+ }).payload+ ).toEqual([+ {+ namespace: "styles",+ patches: [+ {+ op: "replace",+ path: ["local:base:--color:"],+ value: {+ ...existing,+ value: { type: "unparsed", value: "blue" },+ },+ },+ ],+ },+ ]);+ });++ test("creates css variable delete patches and reports references", () => {+ const styles = [+ createCssVariableStyleDecl("local", "--color", "red"),+ createCssVariableStyleDecl("local", "color", "var(--color)"),+ ];+ expect(+ createCssVariableDeletePayload({+ names: ["--color"],+ styles,+ props: [],+ })+ ).toEqual({+ payload: [],+ styleKeys: [],+ referenced: ["--color"],+ });++ expect(+ createCssVariableDeletePayload({+ names: ["--color"],+ styles,+ props: [],+ force: true,+ })+ ).toEqual({+ payload: [+ {+ namespace: "styles",+ patches: [{ op: "remove", path: ["local:base:--color:"] }],+ },+ ],+ styleKeys: ["local:base:--color:"],+ referenced: [],+ });+ });++ test("creates css variable delete patches from style iterators", () => {+ const styles = new Map([+ [+ "local:base:--color:",+ createCssVariableStyleDecl("local", "--color", "red"),+ ],+ ]);++ expect(+ createCssVariableDeletePayload({+ names: ["--color"],+ styles: styles.values(),+ props: [],+ })+ ).toEqual({+ payload: [+ {+ namespace: "styles",+ patches: [{ op: "remove", path: ["local:base:--color:"] }],+ },+ ],+ styleKeys: ["local:base:--color:"],+ referenced: [],+ });+ });++ test("creates scoped css variable reference rewrite patches", () => {+ expect(+ createCssVariableReferenceRewritePayload({+ replacements: { "--old": "--new" },+ scopeRegex: /^box$/,+ styles: [+ createCssVariableStyleDecl("local", "color", "var(--old)"),+ createCssVariableStyleDecl("other-local", "color", "var(--old)"),+ ],+ props: [+ {+ id: "prop",+ instanceId: "box",+ name: "code",+ type: "string",+ value: "var(--old)",+ },+ ],+ styleSourceSelections: [+ { instanceId: "box", values: ["local"] },+ { instanceId: "other", values: ["other-local"] },+ ],+ })+ ).toEqual({+ payload: [+ {+ namespace: "styles",+ patches: [+ {+ op: "replace",+ path: ["local:base:color:"],+ value: createCssVariableStyleDecl("local", "color", "var(--new)"),+ },+ ],+ },+ {+ namespace: "props",+ patches: [+ {+ op: "replace",+ path: ["prop"],+ value: {+ id: "prop",+ instanceId: "box",+ name: "code",+ type: "string",+ value: "var(--new)",+ },+ },+ ],+ },+ ],+ styleKeys: ["local:base:color:"],+ propIds: ["prop"],+ });+ });+});+enableMapSet();++const getIdValuePair = <T extends { id: string }>(item: T) =>+ [item.id, item] as const;++const toMap = <T extends { id: string }>(list: T[]) =>+ new Map(list.map(getIdValuePair));++const createStyleDecl = (+ styleSourceId: string,+ breakpointId: string,+ property: StyleProperty,+ value: StyleValue | string+): StyleDecl => ({+ styleSourceId,+ breakpointId,+ property,+ value: typeof value === "string" ? { type: "unparsed", value } : value,+});++const createStyleDeclMap = (styles: StyleDecl[]) =>+ new Map(+ styles.map((style) => [+ `${style.styleSourceId}:${style.breakpointId}:${style.property}:${style.state ?? ""}`,+ style,+ ])+ );++const createId = () => "new-id";++const baseBreakpoints = toMap<Breakpoint>([{ id: "base", label: "base" }]);+const runtimeBreakpoints = toMap<Breakpoint>([+ { id: "desktop", label: "Base" },+ { id: "mobile", label: "Mobile", maxWidth: 767 },+]);+const token = (+ id: string,+ name = "Token",+ rest: Partial<Extract<StyleSource, { type: "token" }>> = {}+): Extract<StyleSource, { type: "token" }> => ({+ type: "token",+ id,+ name,+ ...rest,+});+const local = (id: string): Extract<StyleSource, { type: "local" }> => ({+ type: "local",+ id,+});++const sources = (items: StyleSource[]) => toMap<StyleSource>(items);++const instance = (id: string): Instance => ({+ type: "instance",+ id,+ component: "ws:element",+ children: [],+});++describe("runtime style operations", () => {+ test("update styles uses the project base breakpoint when omitted", () => {+ const mutation = updateStyleDeclarations(+ {+ breakpoints: runtimeBreakpoints,+ instances: toMap([instance("box")]),+ styles: new Map(),+ styleSources: sources([local("local")]),+ styleSourceSelections: new Map([+ ["box", { instanceId: "box", values: ["local"] }],+ ]),+ },+ {+ updates: [+ {+ instanceId: "box",+ property: "font-size",+ value: { type: "unit", value: 24, unit: "px" },+ },+ ],+ },+ { createId }+ );++ expect(mutation.result.styleKeys).toEqual(["local:desktop:fontSize:"]);+ });++ test("delete styles uses the project base breakpoint when omitted", () => {+ const mutation = deleteStyleDeclarations(+ {+ breakpoints: runtimeBreakpoints,+ instances: toMap([instance("box")]),+ styles: createStyleDeclMap([+ createStyleDecl("local", "desktop", "fontSize", {+ type: "unit",+ value: 24,+ unit: "px",+ }),+ ]),+ styleSources: sources([local("local")]),+ styleSourceSelections: new Map([+ ["box", { instanceId: "box", values: ["local"] }],+ ]),+ },+ { deletions: [{ instanceId: "box", property: "font-size" }] }+ );++ expect(mutation.result.styleKeys).toEqual(["local:desktop:fontSize:"]);+ });++ test("design token styles use the project base breakpoint when omitted", () => {+ const createMutation = createDesignTokens(+ {+ breakpoints: runtimeBreakpoints,+ styles: new Map(),+ styleSources: new Map(),+ styleSourceSelections: new Map(),+ },+ {+ tokens: [+ {+ tokenId: "token",+ name: "Primary",+ styles: { color: { type: "keyword", value: "red" } },+ },+ ],+ },+ { createId }+ );+ expect(createMutation.payload).toContainEqual({+ namespace: "styles",+ patches: [+ {+ op: "add",+ path: ["token:desktop:color:"],+ value: createStyleDecl("token", "desktop", "color", {+ type: "keyword",+ value: "red",+ }),+ },+ ],+ });++ const updateMutation = updateDesignTokenStyles(+ {+ breakpoints: runtimeBreakpoints,+ styles: new Map(),+ styleSources: sources([token("token", "Primary")]),+ styleSourceSelections: new Map(),+ },+ {+ designTokenId: "token",+ updates: [+ {+ property: "font-size",+ value: { type: "unit", value: 16, unit: "px" },+ },+ ],+ }+ );+ expect(updateMutation.result.styleKeys).toEqual([+ "token:desktop:fontSize:",+ ]);++ const deleteMutation = deleteDesignTokenStyles(+ {+ breakpoints: runtimeBreakpoints,+ styles: createStyleDeclMap([+ createStyleDecl("token", "desktop", "fontSize", {+ type: "unit",+ value: 16,+ unit: "px",+ }),+ ]),+ styleSources: sources([token("token", "Primary")]),+ styleSourceSelections: new Map(),+ },+ { designTokenId: "token", deletions: [{ property: "font-size" }] }+ );+ expect(deleteMutation.result.styleKeys).toEqual([+ "token:desktop:fontSize:",+ ]);+ });++ test("define css variables uses the project base breakpoint", () => {+ const mutation = defineCssVariables(+ {+ breakpoints: runtimeBreakpoints,+ pages: {+ homePageId: "home",+ rootFolderId: "root",+ pages: new Map([+ [+ "home",+ {+ id: "home",+ name: "Home",+ title: "",+ rootInstanceId: "root",+ meta: {},+ path: "",+ },+ ],+ ]),+ folders: new Map(),+ },+ styles: new Map(),+ styleSources: new Map(),+ styleSourceSelections: new Map(),+ },+ { vars: { "--color": "red" } },+ { createId }+ );++ expect(mutation.result.names).toEqual(["--color"]);+ expect(mutation.payload).toContainEqual({+ namespace: "styles",+ patches: [+ {+ op: "add",+ path: ["new-id:desktop:--color:"],+ value: createStyleDecl("new-id", "desktop", "--color", {+ type: "unparsed",+ value: "red",+ }),+ },+ ],+ });+ });+});++describe("serializeDesignTokens", () => {+ test("filters, sorts, includes styles, and counts usage when requested", () => {+ expect(+ serializeDesignTokens({+ styleSources: sources([+ token("secondary", "Secondary"),+ token("primary", "Primary"),+ local("local"),+ ]),+ styles: createStyleDeclMap([+ createStyleDecl("primary", "base", "color", {+ type: "keyword",+ value: "red",+ }),+ createStyleDecl("secondary", "base", "marginTop", {+ type: "unit",+ value: 10,+ unit: "px",+ }),+ ]),+ styleSourceSelections: [+ { instanceId: "box-1", values: ["primary", "local"] },+ { instanceId: "box-2", values: ["primary"] },+ { instanceId: "box-3", values: ["secondary"] },+ ],+ filter: "Primary",+ withUsage: true,+ })+ ).toEqual({+ tokens: [+ {+ id: "primary",+ name: "Primary",+ styles: { color: { type: "keyword", value: "red" } },+ usageCount: 2,+ },+ ],+ });++ expect(+ serializeDesignTokens({+ styleSources: sources([+ token("secondary", "Secondary"),+ token("primary", "Primary"),+ ]),+ styles: [],+ styleSourceSelections: [+ { instanceId: "box-1", values: ["primary"] },+ { instanceId: "box-2", values: ["secondary"] },+ { instanceId: "box-3", values: ["secondary"] },+ ],+ sort: "usage",+ }).tokens.map((item) => item.id)+ ).toEqual(["secondary", "primary"]);+ });+});++describe("getLocalStyleSourceId", () => {+ test("returns local style source id from selection", () => {+ const styleSources = sources([+ { id: "token", type: "token", name: "Token" },+ local("local"),+ ]);++ expect(+ getLocalStyleSourceId({+ styleSources,+ styleSourceSelection: {+ instanceId: "instance",+ values: ["token", "local"],+ },+ })+ ).toBe("local");+ });++ test("returns undefined when selection has no local source", () => {+ const styleSources = sources([+ { id: "token", type: "token", name: "Token" },+ ]);++ expect(+ getLocalStyleSourceId({+ styleSources,+ styleSourceSelection: {+ instanceId: "instance",+ values: ["token"],+ },+ })+ ).toBeUndefined();+ });+});++describe("style declaration helpers", () => {+ test("parse style and design token inputs used by the API", () => {+ expect(+ styleUpdateInput.parse({+ instanceId: "box",+ property: "color",+ value: { type: "keyword", value: "red" },+ createLocalIfMissing: true,+ })+ ).toEqual({+ instanceId: "box",+ property: "color",+ value: { type: "keyword", value: "red" },+ createLocalIfMissing: true,+ });++ expect(+ styleDeleteInput.parse({ instanceId: "box", property: "color" })+ ).toEqual({+ instanceId: "box",+ property: "color",+ });++ expect(+ styleReplaceInput.parse({+ property: "color",+ fromValue: { type: "keyword", value: "red" },+ toValue: { type: "keyword", value: "blue" },+ pagePath: "/about",+ })+ ).toEqual({+ property: "color",+ fromValue: { type: "keyword", value: "red" },+ toValue: { type: "keyword", value: "blue" },+ pagePath: "/about",+ });++ expect(+ designTokenCreateInput.parse({+ name: "Primary",+ styles: { color: { type: "keyword", value: "red" } },+ declarations: [+ {+ property: "fontSize",+ value: { type: "unit", value: 16, unit: "px" },+ },+ ],+ })+ ).toEqual({+ name: "Primary",+ styles: { color: { type: "keyword", value: "red" } },+ declarations: [+ {+ property: "fontSize",+ value: { type: "unit", value: 16, unit: "px" },+ },+ ],+ });+ });++ test("reject empty design token names", () => {+ expect(() => designTokenCreateInput.parse({ name: "" })).toThrow();+ });++ test("creates token style sources and omits unlocked state", () => {+ expect(createTokenStyleSource({ id: "token", name: "Token" })).toEqual({+ type: "token",+ id: "token",+ name: "Token",+ });+ expect(+ createTokenStyleSource({ id: "token", name: "Token", locked: true })+ ).toEqual({+ type: "token",+ id: "token",+ name: "Token",+ locked: true,+ });+ });++ test("finds design token style sources", () => {+ expect(+ findDesignToken(+ [local("local"), { id: "token", type: "token", name: "Token" }],+ "token"+ )+ ).toEqual({ id: "token", type: "token", name: "Token" });+ expect(findDesignToken([local("local")], "local")).toBeUndefined();+ });++ test("creates style declarations through the sdk schema", () => {+ expect(+ createStyleDeclValue({+ styleSourceId: "local",+ breakpointId: "base",+ property: "color",+ value: { type: "keyword", value: "red" },+ })+ ).toEqual({+ styleSourceId: "local",+ breakpointId: "base",+ property: "color",+ value: { type: "keyword", value: "red" },+ });+ });++ test("creates style declarations from user input with base breakpoint default", () => {+ expect(+ createStyleDeclFromInput({+ styleSourceId: "token",+ property: "color",+ value: { type: "keyword", value: "red" },+ state: ":hover",+ })+ ).toEqual({+ styleSourceId: "token",+ breakpointId: "base",+ property: "color",+ value: { type: "keyword", value: "red" },+ state: ":hover",+ });+ });++ test("creates style declaration keys from user input with base breakpoint default", () => {+ expect(+ getStyleDeclKeyFromInput({+ styleSourceId: "token",+ property: "color",+ state: ":hover",+ })+ ).toBe("token:base:color::hover");+ });++ test("sets and deletes style declarations through shared mutable helpers", () => {+ const styles = new Map();++ const { styleDecl, styleKey } = setStyleDeclMutable({+ styles,+ styleSourceId: "local",+ breakpointId: "base",+ property: "color",+ value: { type: "keyword", value: "red" },+ listed: true,+ });++ expect(styleKey).toBe("local:base:color:");+ expect(styles.get(styleKey)).toEqual(styleDecl);+ expect(+ deleteStyleDeclMutable({+ styles,+ styleSourceId: "local",+ breakpointId: "base",+ property: "color",+ })+ ).toBe(true);+ expect(styles.has(styleKey)).toBe(false);+ });++ test("creates design token style inputs from styles map and declarations", () => {+ expect(+ createDesignTokenStyleInputs({+ styles: {+ color: { type: "keyword", value: "red" },+ },+ declarations: [+ {+ property: "fontSize",+ value: { type: "unit", value: 16, unit: "px" },+ breakpoint: "desktop",+ },+ ],+ })+ ).toEqual([+ { property: "color", value: { type: "keyword", value: "red" } },+ {+ property: "fontSize",+ value: { type: "unit", value: 16, unit: "px" },+ breakpoint: "desktop",+ },+ ]);+ });++ test("updates style declarations through the sdk schema", () => {+ const declaration = createStyleDeclValue({+ styleSourceId: "local",+ breakpointId: "base",+ property: "color",+ value: { type: "keyword", value: "red" },+ });++ expect(+ updateStyleDecl(declaration, {+ value: { type: "keyword", value: "blue" },+ })+ ).toEqual({+ styleSourceId: "local",+ breakpointId: "base",+ property: "color",+ value: { type: "keyword", value: "blue" },+ });+ });+});++describe("createStyleSourceSelectionAddPatch", () => {+ const styleSources = sources([+ { id: "token", type: "token", name: "Token" },+ local("local"),+ ]);++ test("creates a style source selection when instance has none", () => {+ expect(+ createStyleSourceSelectionAddPatch({+ styleSourceSelection: undefined,+ styleSources,+ instanceId: "instance",+ styleSourceId: "token",+ })+ ).toEqual({+ op: "add",+ path: ["instance"],+ value: { instanceId: "instance", values: ["token"] },+ });+ });++ test("inserts before local style source by default", () => {+ expect(+ createStyleSourceSelectionAddPatch({+ styleSourceSelection: {+ instanceId: "instance",+ values: ["local"],+ },+ styleSources,+ instanceId: "instance",+ styleSourceId: "token",+ })+ ).toEqual({+ op: "add",+ path: ["instance", "values", 0],+ value: "token",+ });+ });++ test("does not create a patch when source is already selected", () => {+ expect(+ createStyleSourceSelectionAddPatch({+ styleSourceSelection: {+ instanceId: "instance",+ values: ["token"],+ },+ styleSources,+ instanceId: "instance",+ styleSourceId: "token",+ })+ ).toBeUndefined();+ });+});++describe("createStyleSourceSelectionAttachPayload", () => {+ const styleSources = sources([+ { id: "token", type: "token", name: "Token" },+ local("local"),+ ]);++ test("creates a selection payload for attached style sources", () => {+ expect(+ createStyleSourceSelectionAttachPayload({+ instanceIds: ["instance-a", "instance-b"],+ styleSourceSelections: [+ { instanceId: "instance-b", values: ["local"] },+ ],+ styleSources,+ styleSourceId: "token",+ })+ ).toEqual([+ {+ namespace: "styleSourceSelections",+ patches: [+ {+ op: "add",+ path: ["instance-a"],+ value: { instanceId: "instance-a", values: ["token"] },+ },+ {+ op: "add",+ path: ["instance-b", "values", 0],+ value: "token",+ },+ ],+ },+ ]);+ });++ test("returns empty payload when style source is already attached", () => {+ expect(+ createStyleSourceSelectionAttachPayload({+ instanceIds: ["instance"],+ styleSourceSelections: [{ instanceId: "instance", values: ["token"] }],+ styleSources,+ styleSourceId: "token",+ })+ ).toEqual([]);+ });+});++describe("createStyleSourceSelectionRemovePlan", () => {+ test("finds the selected style source index", () => {+ expect(+ createStyleSourceSelectionRemovePlan({+ styleSourceSelection: {+ instanceId: "instance",+ values: ["token-a", "token-b"],+ },+ styleSourceId: "token-b",+ })+ ).toEqual({ type: "remove", index: 1 });+ });++ test("reports missing selection", () => {+ expect(+ createStyleSourceSelectionRemovePlan({+ styleSourceSelection: undefined,+ styleSourceId: "token",+ })+ ).toEqual({ type: "missing" });+ });+});++describe("createStyleSourceSelectionRemovePatch", () => {+ test("creates a remove patch for selected style source", () => {+ expect(+ createStyleSourceSelectionRemovePatch({+ styleSourceSelection: {+ instanceId: "instance",+ values: ["token-a", "token-b"],+ },+ instanceId: "instance",+ styleSourceId: "token-b",+ })+ ).toEqual({+ op: "remove",+ path: ["instance", "values", 1],+ });+ });++ test("does not create a patch when source is not selected", () => {+ expect(+ createStyleSourceSelectionRemovePatch({+ styleSourceSelection: {+ instanceId: "instance",+ values: ["token-a"],+ },+ instanceId: "instance",+ styleSourceId: "token-b",+ })+ ).toBeUndefined();+ });+});++describe("createStyleSourceSelectionDetachPayload", () => {+ test("creates a selection payload for detached style sources", () => {+ expect(+ createStyleSourceSelectionDetachPayload({+ instanceIds: ["instance"],+ styleSourceSelections: [+ { instanceId: "instance", values: ["token-a", "token-b"] },+ ],+ styleSourceId: "token-b",+ })+ ).toEqual([+ {+ namespace: "styleSourceSelections",+ patches: [+ {+ op: "remove",+ path: ["instance", "values", 1],+ },+ ],+ },+ ]);+ });++ test("returns empty payload when style source is not attached", () => {+ expect(+ createStyleSourceSelectionDetachPayload({+ instanceIds: ["instance"],+ styleSourceSelections: [{ instanceId: "instance", values: ["token"] }],+ styleSourceId: "missing",+ })+ ).toEqual([]);+ });+});++describe("removeStyleSourceFromInstanceMutable", () => {+ test("removes selected style source", () => {+ const styleSourceSelections: StyleSourceSelections = new Map([+ ["instance", { instanceId: "instance", values: ["token-a", "token-b"] }],+ ]);++ removeStyleSourceFromInstanceMutable({+ styleSourceSelections,+ instanceId: "instance",+ styleSourceId: "token-a",+ });++ expect(styleSourceSelections.get("instance")?.values).toEqual(["token-b"]);+ });+});++describe("createDesignTokenExtractionPayload", () => {+ test("extracts local styles into a new token and attaches it to instances", () => {+ const { payload, styleKeys } = createDesignTokenExtractionPayload({+ tokenId: "token",+ tokenName: "Primary",+ instanceIds: ["box"],+ styleSources: sources([+ local("local"),+ { id: "existing-token", type: "token", name: "Existing" },+ ]),+ styleSourceSelections: [+ {+ instanceId: "box",+ values: ["existing-token", "local"],+ },+ ],+ styles: [+ createStyleDecl("local", "base", "color", {+ type: "keyword",+ value: "red",+ }),+ createStyleDecl("existing-token", "base", "color", {+ type: "keyword",+ value: "blue",+ }),+ ],+ });++ expect(payload).toEqual([+ {+ namespace: "styleSources",+ patches: [+ {+ op: "add",+ path: ["token"],+ value: { type: "token", id: "token", name: "Primary" },+ },+ ],+ },+ {+ namespace: "styles",+ patches: [+ {+ op: "add",+ path: ["token:base:color:"],+ value: createStyleDecl("token", "base", "color", {+ type: "keyword",+ value: "red",+ }),+ },+ ],+ },+ {+ namespace: "styleSourceSelections",+ patches: [+ {+ op: "add",+ path: ["box", "values", 1],+ value: "token",+ },+ ],+ },+ ]);+ expect(styleKeys).toEqual(["token:base:color:"]);+ });++ test("removes extracted local properties when requested", () => {+ const { payload, styleKeys } = createDesignTokenExtractionPayload({+ tokenId: "token",+ tokenName: "Primary",+ instanceIds: ["box"],+ styleSources: sources([local("local")]),+ styleSourceSelections: [{ instanceId: "box", values: ["local"] }],+ styles: [+ createStyleDecl("local", "base", "color", {+ type: "keyword",+ value: "red",+ }),+ createStyleDecl("local", "base", "fontSize", {+ type: "unit",+ value: 16,+ unit: "px",+ }),+ ],+ removeLocalProps: ["color"],+ });++ expect(payload[1]).toEqual({+ namespace: "styles",+ patches: [+ {+ op: "add",+ path: ["token:base:color:"],+ value: createStyleDecl("token", "base", "color", {+ type: "keyword",+ value: "red",+ }),+ },+ {+ op: "remove",+ path: ["local:base:color:"],+ },+ ],+ });+ expect(styleKeys).toEqual(["token:base:color:"]);+ });++ test("dedupes token declarations extracted from multiple local sources", () => {+ const { payload, styleKeys } = createDesignTokenExtractionPayload({+ tokenId: "token",+ tokenName: "Primary",+ instanceIds: ["box-a", "box-b"],+ styleSources: sources([+ { id: "local-a", type: "local" },+ { id: "local-b", type: "local" },+ ]),+ styleSourceSelections: [+ { instanceId: "box-a", values: ["local-a"] },+ { instanceId: "box-b", values: ["local-b"] },+ ],+ styles: [+ createStyleDecl("local-a", "base", "color", {+ type: "keyword",+ value: "red",+ }),+ createStyleDecl("local-b", "base", "color", {+ type: "keyword",+ value: "red",+ }),+ ],+ });++ expect(payload[1]).toEqual({+ namespace: "styles",+ patches: [+ {+ op: "add",+ path: ["token:base:color:"],+ value: createStyleDecl("token", "base", "color", {+ type: "keyword",+ value: "red",+ }),+ },+ ],+ });+ expect(styleKeys).toEqual(["token:base:color:"]);+ });++ test("omits empty styles and selection namespaces", () => {+ const { payload, styleKeys } = createDesignTokenExtractionPayload({+ tokenId: "token",+ tokenName: "Primary",+ instanceIds: [],+ styleSources: sources([]),+ styleSourceSelections: [],+ styles: [],+ });++ expect(payload).toEqual([+ {+ namespace: "styleSources",+ patches: [+ {+ op: "add",+ path: ["token"],+ value: { type: "token", id: "token", name: "Primary" },+ },+ ],+ },+ ]);+ expect(styleKeys).toEqual([]);+ });+});++describe("createStyleDeclarationUpdatePayload", () => {+ test("normalizes CSS property names before creating style keys", () => {+ const { payload, styleKeys } = createStyleDeclarationUpdatePayload({+ styleSources: sources([local("local")]),+ styleSourceSelections: [{ instanceId: "box", values: ["local"] }],+ styles: [],+ createId,+ updates: [+ {+ instanceId: "box",+ property: "background-color",+ value: { type: "keyword", value: "black" },+ },+ ],+ });++ expect(payload).toEqual([+ {+ namespace: "styles",+ patches: [+ {+ op: "add",+ path: ["local:base:backgroundColor:"],+ value: createStyleDecl("local", "base", "backgroundColor", {+ type: "keyword",+ value: "black",+ }),+ },+ ],+ },+ ]);+ expect(styleKeys).toEqual(["local:base:backgroundColor:"]);+ });++ test("creates style add patches for local style sources", () => {+ const { payload, styleKeys, missingLocalStyleSourceInstanceIds } =+ createStyleDeclarationUpdatePayload({+ styleSources: sources([local("local")]),+ styleSourceSelections: [{ instanceId: "box", values: ["local"] }],+ styles: [],+ createId,+ updates: [+ {+ instanceId: "box",+ property: "color",+ value: { type: "keyword", value: "red" },+ },+ ],+ });++ expect(payload).toEqual([+ {+ namespace: "styles",+ patches: [+ {+ op: "add",+ path: ["local:base:color:"],+ value: createStyleDecl("local", "base", "color", {+ type: "keyword",+ value: "red",+ }),+ },+ ],+ },+ ]);+ expect(styleKeys).toEqual(["local:base:color:"]);+ expect(missingLocalStyleSourceInstanceIds).toEqual([]);+ });++ test("reports missing local style source when creation is disabled", () => {+ const result = createStyleDeclarationUpdatePayload({+ styleSources: new Map(),+ styleSourceSelections: [],+ styles: [],+ createId,+ updates: [+ {+ instanceId: "box",+ property: "color",+ value: { type: "keyword", value: "red" },+ createLocalIfMissing: false,+ },+ ],+ });++ expect(result).toEqual({+ payload: [],+ styleKeys: [],+ missingLocalStyleSourceInstanceIds: ["box"],+ });+ });++ test("replaces repeated style keys within the same batch", () => {+ const { payload, styleKeys } = createStyleDeclarationUpdatePayload({+ styleSources: sources([local("local")]),+ styleSourceSelections: [{ instanceId: "box", values: ["local"] }],+ styles: [],+ createId,+ updates: [+ {+ instanceId: "box",+ property: "color",+ value: { type: "keyword", value: "red" },+ },+ {+ instanceId: "box",+ property: "color",+ value: { type: "keyword", value: "blue" },+ },+ ],+ });++ expect(payload).toEqual([+ {+ namespace: "styles",+ patches: [+ {+ op: "add",+ path: ["local:base:color:"],+ value: createStyleDecl("local", "base", "color", {+ type: "keyword",+ value: "red",+ }),+ },+ {+ op: "replace",+ path: ["local:base:color:"],+ value: createStyleDecl("local", "base", "color", {+ type: "keyword",+ value: "blue",+ }),+ },+ ],+ },+ ]);+ expect(styleKeys).toEqual(["local:base:color:", "local:base:color:"]);+ });+});++describe("createStyleDeclarationDeletePayload", () => {+ test("normalizes CSS property names before deleting style keys", () => {+ const { payload, styleKeys } = createStyleDeclarationDeletePayload({+ styleSources: sources([local("local")]),+ styleSourceSelections: [{ instanceId: "box", values: ["local"] }],+ styles: [+ createStyleDecl("local", "base", "fontSize", {+ type: "unit",+ value: 16,+ unit: "px",+ }),+ ],+ deletions: [{ instanceId: "box", property: "font-size" }],+ });++ expect(payload).toEqual([+ {+ namespace: "styles",+ patches: [{ op: "remove", path: ["local:base:fontSize:"] }],+ },+ ]);+ expect(styleKeys).toEqual(["local:base:fontSize:"]);+ });++ test("creates remove patches for existing local declarations", () => {+ const { payload, styleKeys } = createStyleDeclarationDeletePayload({+ styleSources: sources([local("local")]),+ styleSourceSelections: [{ instanceId: "box", values: ["local"] }],+ styles: [+ createStyleDecl("local", "base", "color", {+ type: "keyword",+ value: "red",+ }),+ ],+ deletions: [{ instanceId: "box", property: "color" }],+ });++ expect(payload).toEqual([+ {+ namespace: "styles",+ patches: [{ op: "remove", path: ["local:base:color:"] }],+ },+ ]);+ expect(styleKeys).toEqual(["local:base:color:"]);+ });++ test("skips missing local declarations", () => {+ expect(+ createStyleDeclarationDeletePayload({+ styleSources: new Map(),+ styleSourceSelections: [],+ styles: [],+ deletions: [{ instanceId: "box", property: "color" }],+ })+ ).toEqual({ payload: [], styleKeys: [] });+ });+});++describe("createStyleValueReplacementPayload", () => {+ test("normalizes CSS property names before replacing style values", () => {+ const { payload, styleKeys } = createStyleValueReplacementPayload({+ styleSources: [local("local")],+ styleSourceSelections: [{ instanceId: "box", values: ["local"] }],+ styles: [+ createStyleDecl("local", "base", "fontWeight", {+ type: "keyword",+ value: "400",+ }),+ ],+ property: "font-weight",+ fromValue: { type: "keyword", value: "400" },+ toValue: { type: "keyword", value: "700" },+ });++ expect(payload).toEqual([+ {+ namespace: "styles",+ patches: [+ {+ op: "replace",+ path: ["local:base:fontWeight:"],+ value: createStyleDecl("local", "base", "fontWeight", {+ type: "keyword",+ value: "700",+ }),+ },+ ],+ },+ ]);+ expect(styleKeys).toEqual(["local:base:fontWeight:"]);+ });++ test("replaces matching local style values in scope", () => {+ const { payload, styleKeys } = createStyleValueReplacementPayload({+ styleSources: [+ local("local"),+ { id: "token", type: "token", name: "Token" },+ ],+ styleSourceSelections: [+ { instanceId: "box", values: ["token", "local"] },+ { instanceId: "other", values: ["other-local"] },+ ],+ instanceIds: new Set(["box"]),+ styles: [+ createStyleDecl("local", "base", "color", {+ type: "keyword",+ value: "red",+ }),+ createStyleDecl("token", "base", "color", {+ type: "keyword",+ value: "red",+ }),+ ],+ property: "color",+ fromValue: { type: "keyword", value: "red" },+ toValue: { type: "keyword", value: "blue" },+ });++ expect(payload).toEqual([+ {+ namespace: "styles",+ patches: [+ {+ op: "replace",+ path: ["local:base:color:"],+ value: createStyleDecl("local", "base", "color", {+ type: "keyword",+ value: "blue",+ }),+ },+ ],+ },+ ]);+ expect(styleKeys).toEqual(["local:base:color:"]);+ });+});++describe("design token patch helpers", () => {+ test("creates token and style patches", () => {+ const { payload, tokenIds, errors } = createDesignTokenCreatePayload({+ styleSources: new Map(),+ createId,+ tokens: [+ {+ tokenId: "token",+ name: "Primary",+ styles: { color: { type: "keyword", value: "red" } },+ },+ ],+ });++ expect(errors).toEqual([]);+ expect(tokenIds).toEqual(["token"]);+ expect(payload).toEqual([+ {+ namespace: "styleSources",+ patches: [+ {+ op: "add",+ path: ["token"],+ value: { type: "token", id: "token", name: "Primary" },+ },+ ],+ },+ {+ namespace: "styles",+ patches: [+ {+ op: "add",+ path: ["token:base:color:"],+ value: createStyleDecl("token", "base", "color", {+ type: "keyword",+ value: "red",+ }),+ },+ ],+ },+ ]);+ });++ test("does not emit empty style patch namespace for token without styles", () => {+ const { payload, tokenIds, errors } = createDesignTokenCreatePayload({+ styleSources: new Map(),+ createId,+ tokens: [{ tokenId: "token", name: "Primary" }],+ });++ expect(errors).toEqual([]);+ expect(tokenIds).toEqual(["token"]);+ expect(payload).toEqual([+ {+ namespace: "styleSources",+ patches: [+ {+ op: "add",+ path: ["token"],+ value: { type: "token", id: "token", name: "Primary" },+ },+ ],+ },+ ]);+ });++ test("reports token create conflicts", () => {+ const result = createDesignTokenCreatePayload({+ styleSources: sources([{ id: "token", type: "token", name: "Primary" }]),+ createId,+ tokens: [+ { tokenId: "token", name: "Primary" },+ { tokenId: "next", name: "Primary" },+ ],+ });++ expect(result.errors).toEqual([+ { type: "duplicate-id", tokenId: "token" },+ {+ type: "invalid-name",+ tokenId: "next",+ error: { type: "duplicate", id: "next" },+ },+ ]);+ });++ test("updates token styles with same-batch add then replace", () => {+ const { payload, styleKeys } = createDesignTokenStyleUpdatePayload({+ designTokenId: "token",+ styles: [],+ updates: [+ {+ property: "color",+ value: { type: "keyword", value: "red" },+ },+ {+ property: "color",+ value: { type: "keyword", value: "blue" },+ },+ ],+ });++ expect(payload).toEqual([+ {+ namespace: "styles",+ patches: [+ {+ op: "add",+ path: ["token:base:color:"],+ value: createStyleDecl("token", "base", "color", {+ type: "keyword",+ value: "red",+ }),+ },+ {+ op: "replace",+ path: ["token:base:color:"],+ value: createStyleDecl("token", "base", "color", {+ type: "keyword",+ value: "blue",+ }),+ },+ ],+ },+ ]);+ expect(styleKeys).toEqual(["token:base:color:", "token:base:color:"]);+ });++ test("returns empty payload when token style updates are empty", () => {+ const { payload, styleKeys } = createDesignTokenStyleUpdatePayload({+ designTokenId: "token",+ styles: [],+ updates: [],+ });++ expect(payload).toEqual([]);+ expect(styleKeys).toEqual([]);+ });++ test("deletes existing token styles", () => {+ const { payload, styleKeys } = createDesignTokenStyleDeletePayload({+ designTokenId: "token",+ styles: [+ createStyleDecl("token", "base", "color", {+ type: "keyword",+ value: "red",+ }),+ ],+ deletions: [{ property: "color" }],+ });++ expect(payload).toEqual([+ {+ namespace: "styles",+ patches: [{ op: "remove", path: ["token:base:color:"] }],+ },+ ]);+ expect(styleKeys).toEqual(["token:base:color:"]);+ });+});++describe("validateStyleSourceName", () => {+ test("validates required and duplicate token names", () => {+ const styleSources = sources([+ { id: "token", type: "token", name: "Token" },+ local("local"),+ ]);++ expect(+ validateStyleSourceName({+ id: "next",+ name: "",+ styleSources,+ })+ ).toEqual({ type: "minlength", id: "next" });+ expect(+ validateStyleSourceName({+ id: "next",+ name: "Token",+ styleSources,+ })+ ).toEqual({ type: "duplicate", id: "next" });+ expect(+ validateStyleSourceName({+ id: "token",+ name: "Token",+ styleSources,+ })+ ).toBeUndefined();+ });+});++describe("getOrCreateLocalStyleSourceIdMutable", () => {+ test("returns existing local style source", () => {+ const styleSources = sources([local("local")]);+ const styleSourceSelections: StyleSourceSelections = new Map([+ ["instance", { instanceId: "instance", values: ["local"] }],+ ]);++ expect(+ getOrCreateLocalStyleSourceIdMutable({+ styleSourceSelections,+ styleSources,+ instanceId: "instance",+ createId: () => "new-local",+ })+ ).toBe("local");+ expect(Array.from(styleSources.values())).toEqual([local("local")]);+ });++ test("creates local style source on existing token selection", () => {+ const styleSources = sources([+ { id: "token", type: "token", name: "Token" },+ ]);+ const styleSourceSelections: StyleSourceSelections = new Map([+ ["instance", { instanceId: "instance", values: ["token"] }],+ ]);++ expect(+ getOrCreateLocalStyleSourceIdMutable({+ styleSourceSelections,+ styleSources,+ instanceId: "instance",+ createId: () => "local",+ })+ ).toBe("local");+ expect(styleSources.get("local")).toEqual(local("local"));+ expect(styleSourceSelections.get("instance")?.values).toEqual([+ "token",+ "local",+ ]);+ });++ test("creates selection when missing", () => {+ const styleSources: StyleSources = new Map();+ const styleSourceSelections: StyleSourceSelections = new Map();++ expect(+ getOrCreateLocalStyleSourceIdMutable({+ styleSourceSelections,+ styleSources,+ instanceId: "instance",+ createId: () => "local",+ })+ ).toBe("local");+ expect(styleSourceSelections.get("instance")).toEqual({+ instanceId: "instance",+ values: ["local"],+ });+ });+});++describe("createLocalStyleSourcePlan", () => {+ test("returns existing local style source", () => {+ const styleSources = sources([local("local")]);++ expect(+ createLocalStyleSourcePlan({+ styleSources,+ styleSourceSelection: { instanceId: "instance", values: ["local"] },+ instanceId: "instance",+ })+ ).toEqual({ styleSourceId: "local" });+ });++ test("creates style source and selection when instance has no selection", () => {+ const styleSources: StyleSources = new Map();++ expect(+ createLocalStyleSourcePlan({+ styleSources,+ styleSourceSelection: undefined,+ instanceId: "instance",+ createId: () => "local",+ })+ ).toEqual({+ styleSourceId: "local",+ styleSource: { type: "local", id: "local" },+ selection: { instanceId: "instance", values: ["local"] },+ });+ });++ test("appends style source to existing selection without local source", () => {+ const styleSources = sources([token("token", "Token")]);++ expect(+ createLocalStyleSourcePlan({+ styleSources,+ styleSourceSelection: { instanceId: "instance", values: ["token"] },+ instanceId: "instance",+ createId: () => "local",+ })+ ).toEqual({+ styleSourceId: "local",+ styleSource: { type: "local", id: "local" },+ selectionValueIndex: 1,+ });+ });+});++describe("getStyleSourceInsertionIndex", () => {+ const styleSources = sources([token("token", "Token"), local("local")]);++ test("inserts before local style source by default", () => {+ expect(+ getStyleSourceInsertionIndex({+ styleSourceIds: ["token", "local"],+ styleSources,+ })+ ).toBe(1);+ });++ test("inserts after local style source when requested", () => {+ expect(+ getStyleSourceInsertionIndex({+ styleSourceIds: ["token", "local"],+ styleSources,+ position: "after-local",+ })+ ).toBe(2);+ });++ test("inserts at end when no local style source exists", () => {+ expect(+ getStyleSourceInsertionIndex({+ styleSourceIds: ["token"],+ styleSources,+ })+ ).toBe(1);+ });+});++describe("addStyleSourceToInstanceMutable", () => {+ test("creates missing selection and adds style source", () => {+ const styleSources = sources([+ { id: "token", type: "token", name: "Token" },+ ]);+ const styleSourceSelections: StyleSourceSelections = new Map();++ addStyleSourceToInstanceMutable({+ styleSourceSelections,+ styleSources,+ instanceId: "instance",+ styleSourceId: "token",+ });++ expect(styleSourceSelections.get("instance")).toEqual({+ instanceId: "instance",+ values: ["token"],+ });+ });++ test("adds token before local style source", () => {+ const styleSources = sources([+ { id: "token", type: "token", name: "Token" },+ local("local"),+ ]);+ const styleSourceSelections: StyleSourceSelections = new Map([+ ["instance", { instanceId: "instance", values: ["local"] }],+ ]);++ addStyleSourceToInstanceMutable({+ styleSourceSelections,+ styleSources,+ instanceId: "instance",+ styleSourceId: "token",+ });++ expect(styleSourceSelections.get("instance")?.values).toEqual([+ "token",+ "local",+ ]);+ });+});++describe("createLocalStyleSourceClonePlan", () => {+ test("clones local style sources and remaps copied selections", () => {+ const plan = createLocalStyleSourceClonePlan({+ styleSourceSelections: [+ { instanceId: "source", values: ["token", "local"] },+ { instanceId: "ignored", values: ["local"] },+ ],+ styleSources: [+ { id: "token", type: "token", name: "Token" },+ local("local"),+ ],+ newInstanceIds: new Map([["source", "copy"]]),+ createId: () => "local-copy",+ });++ expect(plan.localStyleSourceIds).toEqual(+ new Map([["local", "local-copy"]])+ );+ expect(plan.localStyleSources).toEqual([+ { id: "local-copy", type: "local" },+ ]);+ expect(plan.selections).toEqual([+ { instanceId: "copy", values: ["token", "local-copy"] },+ ]);+ });++ test("reuses a cloned local style source across copied selections", () => {+ let idIndex = 0;+ const plan = createLocalStyleSourceClonePlan({+ styleSourceSelections: [+ { instanceId: "source-1", values: ["local"] },+ { instanceId: "source-2", values: ["local"] },+ ],+ styleSources: [local("local")],+ newInstanceIds: new Map([+ ["source-1", "copy-1"],+ ["source-2", "copy-2"],+ ]),+ createId: () => `local-copy-${idIndex++}`,+ });++ expect(plan.localStyleSourceIds).toEqual(+ new Map([["local", "local-copy-0"]])+ );+ expect(plan.localStyleSources).toEqual([+ { id: "local-copy-0", type: "local" },+ ]);+ expect(plan.selections).toEqual([+ { instanceId: "copy-1", values: ["local-copy-0"] },+ { instanceId: "copy-2", values: ["local-copy-0"] },+ ]);+ });+});++describe("createLocalStyleSourcePatchPlan", () => {+ test("returns existing local style source", () => {+ const styleSources = sources([local("local")]);+ expect(+ createLocalStyleSourcePatchPlan({+ createdLocalSourceIds: new Map(),+ instanceId: "instance",+ styleSources,+ styleSourceSelection: { instanceId: "instance", values: ["local"] },+ shouldCreate: true,+ })+ ).toEqual({ styleSourceId: "local", payload: [] });+ });++ test("creates a missing selection", () => {+ const createdLocalSourceIds = new Map<string, string>();+ const result = createLocalStyleSourcePatchPlan({+ createdLocalSourceIds,+ instanceId: "instance",+ styleSources: new Map(),+ styleSourceSelection: undefined,+ shouldCreate: true,+ });+ const styleSourceId = result?.styleSourceId;++ expect(styleSourceId).toEqual(expect.any(String));+ expect(createdLocalSourceIds).toEqual(+ new Map([["instance", styleSourceId]])+ );+ expect(result).toEqual({+ styleSourceId,+ payload: [+ {+ namespace: "styleSources",+ patches: [+ {+ op: "add",+ path: [styleSourceId],+ value: { type: "local", id: styleSourceId },+ },+ ],+ },+ {+ namespace: "styleSourceSelections",+ patches: [+ {+ op: "add",+ path: ["instance"],+ value: { instanceId: "instance", values: [styleSourceId] },+ },+ ],+ },+ ],+ });+ });++ test("inserts into an existing selection", () => {+ const result = createLocalStyleSourcePatchPlan({+ createdLocalSourceIds: new Map(),+ instanceId: "instance",+ styleSources: new Map(),+ styleSourceSelection: { instanceId: "instance", values: ["token"] },+ shouldCreate: true,+ });++ expect(result?.payload[1]).toEqual({+ namespace: "styleSourceSelections",+ patches: [+ {+ op: "add",+ path: ["instance", "values", 1],+ value: result?.styleSourceId,+ },+ ],+ });+ });++ test("skips missing local style source when creation is disabled", () => {+ expect(+ createLocalStyleSourcePatchPlan({+ createdLocalSourceIds: new Map(),+ instanceId: "instance",+ styleSources: new Map(),+ styleSourceSelection: undefined,+ shouldCreate: false,+ })+ ).toBeUndefined();+ });++ test("prefers created local style source ids", () => {+ expect(+ getLocalStyleSourceIdWithCreated({+ createdLocalSourceIds: new Map([["instance", "created"]]),+ instanceId: "instance",+ styleSources: new Map(),+ styleSourceSelection: undefined,+ })+ ).toBe("created");+ });+});++describe("createStyleSourceSelectionAddPlan", () => {+ test("creates missing selection", () => {+ const styleSources = sources([+ { id: "token", type: "token", name: "Token" },+ ]);++ expect(+ createStyleSourceSelectionAddPlan({+ styleSourceSelection: undefined,+ styleSources,+ instanceId: "instance",+ styleSourceId: "token",+ })+ ).toEqual({+ type: "create",+ selection: { instanceId: "instance", values: ["token"] },+ });+ });++ test("skips existing style source", () => {+ const styleSources = sources([+ { id: "token", type: "token", name: "Token" },+ ]);++ expect(+ createStyleSourceSelectionAddPlan({+ styleSourceSelection: { instanceId: "instance", values: ["token"] },+ styleSources,+ instanceId: "instance",+ styleSourceId: "token",+ })+ ).toEqual({ type: "exists" });+ });++ test("inserts before local source by default", () => {+ const styleSources = sources([+ { id: "token", type: "token", name: "Token" },+ local("local"),+ ]);++ expect(+ createStyleSourceSelectionAddPlan({+ styleSourceSelection: { instanceId: "instance", values: ["local"] },+ styleSources,+ instanceId: "instance",+ styleSourceId: "token",+ })+ ).toEqual({ type: "insert", index: 0 });+ });+});++describe("deleteStyleSourceMutable", () => {+ test("deletes style source from styleSources map", () => {+ const styleSources: StyleSources = new Map([+ ["token1", token("token1", "Primary Color")],+ ["token2", token("token2", "Secondary Color")],+ ]);+ const styleSourceSelections: StyleSourceSelections = new Map();+ const styles: Styles = new Map();++ deleteStyleSourceMutable({+ styleSourceId: "token1",+ styleSources,+ styleSourceSelections,+ styles,+ });++ expect(styleSources.has("token1")).toBe(false);+ expect(styleSources.has("token2")).toBe(true);+ });++ test("removes style source from style source selections", () => {+ const styleSources: StyleSources = new Map([+ ["token1", token("token1", "Primary Color")],+ ]);+ const styleSourceSelections: StyleSourceSelections = new Map([+ ["instance1", { instanceId: "instance1", values: ["token1", "local1"] }],+ ["instance2", { instanceId: "instance2", values: ["token1"] }],+ ["instance3", { instanceId: "instance3", values: ["local2"] }],+ ]);+ const styles: Styles = new Map();++ deleteStyleSourceMutable({+ styleSourceId: "token1",+ styleSources,+ styleSourceSelections,+ styles,+ });++ const selection1 = styleSourceSelections.get("instance1");+ expect(selection1?.values).toEqual(["local1"]);++ const selection2 = styleSourceSelections.get("instance2");+ expect(selection2?.values).toEqual([]);++ const selection3 = styleSourceSelections.get("instance3");+ expect(selection3?.values).toEqual(["local2"]);+ });++ test("deletes all styles associated with the style source", () => {+ const styleSources: StyleSources = new Map([+ ["token1", token("token1", "Primary Color")],+ ]);+ const styleSourceSelections: StyleSourceSelections = new Map();+ const styles: Styles = new Map([+ [+ "token1:base:color",+ {+ breakpointId: "base",+ styleSourceId: "token1",+ property: "color",+ value: { type: "keyword", value: "red" },+ },+ ],+ [+ "token1:base:fontSize",+ {+ breakpointId: "base",+ styleSourceId: "token1",+ property: "fontSize",+ value: { type: "unit", value: 16, unit: "px" },+ },+ ],+ [+ "local1:base:display",+ {+ breakpointId: "base",+ styleSourceId: "local1",+ property: "display",+ value: { type: "keyword", value: "flex" },+ },+ ],+ ]);++ deleteStyleSourceMutable({+ styleSourceId: "token1",+ styleSources,+ styleSourceSelections,+ styles,+ });++ expect(styles.has("token1:base:color")).toBe(false);+ expect(styles.has("token1:base:fontSize")).toBe(false);+ expect(styles.has("local1:base:display")).toBe(true);+ expect(styles.size).toBe(1);+ });++ test("handles deletion of non-existent style source gracefully", () => {+ const styleSources: StyleSources = new Map();+ const styleSourceSelections: StyleSourceSelections = new Map();+ const styles: Styles = new Map();++ expect(() => {+ deleteStyleSourceMutable({+ styleSourceId: "non-existent",+ styleSources,+ styleSourceSelections,+ styles,+ });+ }).not.toThrow();+ });+});++describe("findUnusedTokens", () => {+ test("identifies tokens with no usages", () => {+ const styleSources = sources([+ token("token1", "Used Token"),+ token("token2", "Unused Token"),+ token("token3", "Another Unused"),+ local("local1"),+ ]);+ const styleSourceUsages = new Map<string, Set<string>>([+ ["token1", new Set(["instance1", "instance2"])],+ ["token2", new Set()],+ ["local1", new Set(["instance3"])],+ ]);++ const unusedTokens = findUnusedTokens({ styleSources, styleSourceUsages });++ expect(unusedTokens).toContain("token2");+ expect(unusedTokens).toContain("token3");+ expect(unusedTokens).not.toContain("token1");+ expect(unusedTokens).not.toContain("local1");+ expect(unusedTokens.length).toBe(2);+ });++ test("returns empty array when all tokens are used", () => {+ const styleSources: StyleSources = new Map([+ ["token1", token("token1", "Used Token 1")],+ ["token2", token("token2", "Used Token 2")],+ ]);+ const styleSourceUsages = new Map([+ ["token1", new Set(["instance1"])],+ ["token2", new Set(["instance2"])],+ ]);++ const unusedTokens = findUnusedTokens({ styleSources, styleSourceUsages });++ expect(unusedTokens).toEqual([]);+ });++ test("ignores local style sources", () => {+ const styleSources: StyleSources = new Map([+ ["local1", local("local1")],+ ["local2", local("local2")],+ ]);+ const styleSourceUsages = new Map();++ const unusedTokens = findUnusedTokens({ styleSources, styleSourceUsages });++ expect(unusedTokens).toEqual([]);+ });++ test("treats undefined usages as unused", () => {+ const styleSources: StyleSources = new Map([+ ["token1", token("token1", "Unused Token")],+ ]);+ const styleSourceUsages = new Map();++ const unusedTokens = findUnusedTokens({ styleSources, styleSourceUsages });++ expect(unusedTokens).toEqual(["token1"]);+ });+});++describe("deleteStyleSourcesMutable", () => {+ test("deletes multiple style sources", () => {+ const styleSources: StyleSources = new Map([+ ["token1", token("token1", "Token 1")],+ ["token2", token("token2", "Token 2")],+ ["token3", token("token3", "Token 3")],+ ]);+ const styleSourceSelections: StyleSourceSelections = new Map();+ const styles: Styles = new Map();++ deleteStyleSourcesMutable({+ styleSourceIds: ["token1", "token3"],+ styleSources,+ styleSourceSelections,+ styles,+ });++ expect(styleSources.has("token1")).toBe(false);+ expect(styleSources.has("token2")).toBe(true);+ expect(styleSources.has("token3")).toBe(false);+ });++ test("removes deleted style sources from all selections", () => {+ const styleSources: StyleSources = new Map([+ ["token1", token("token1", "Token 1")],+ ["token2", token("token2", "Token 2")],+ ]);+ const styleSourceSelections: StyleSourceSelections = new Map([+ [+ "instance1",+ { instanceId: "instance1", values: ["token1", "token2", "local1"] },+ ],+ ["instance2", { instanceId: "instance2", values: ["token1"] }],+ ]);+ const styles: Styles = new Map();++ deleteStyleSourcesMutable({+ styleSourceIds: ["token1", "token2"],+ styleSources,+ styleSourceSelections,+ styles,+ });++ const selection1 = styleSourceSelections.get("instance1");+ expect(selection1?.values).toEqual(["local1"]);++ const selection2 = styleSourceSelections.get("instance2");+ expect(selection2?.values).toEqual([]);+ });++ test("deletes all associated styles", () => {+ const styleSources: StyleSources = new Map([+ ["token1", token("token1", "Token 1")],+ ["token2", token("token2", "Token 2")],+ ]);+ const styleSourceSelections: StyleSourceSelections = new Map();+ const styles: Styles = new Map([+ [+ "token1:base:color",+ {+ breakpointId: "base",+ styleSourceId: "token1",+ property: "color",+ value: { type: "keyword", value: "red" },+ },+ ],+ [+ "token2:base:fontSize",+ {+ breakpointId: "base",+ styleSourceId: "token2",+ property: "fontSize",+ value: { type: "unit", value: 16, unit: "px" },+ },+ ],+ [+ "local1:base:display",+ {+ breakpointId: "base",+ styleSourceId: "local1",+ property: "display",+ value: { type: "keyword", value: "flex" },+ },+ ],+ ]);++ deleteStyleSourcesMutable({+ styleSourceIds: ["token1", "token2"],+ styleSources,+ styleSourceSelections,+ styles,+ });++ expect(styles.has("token1:base:color")).toBe(false);+ expect(styles.has("token2:base:fontSize")).toBe(false);+ expect(styles.has("local1:base:display")).toBe(true);+ expect(styles.size).toBe(1);+ });++ test("handles empty array of style source IDs", () => {+ const styleSources: StyleSources = new Map([+ ["token1", token("token1", "Token 1")],+ ]);+ const styleSourceSelections: StyleSourceSelections = new Map();+ const styles: Styles = new Map();++ deleteStyleSourcesMutable({+ styleSourceIds: [],+ styleSources,+ styleSourceSelections,+ styles,+ });++ expect(styleSources.has("token1")).toBe(true);+ });+});++describe("validateAndRenameStyleSource", () => {+ test("returns undefined for valid rename", () => {+ const styleSources: StyleSources = new Map([+ ["token1", token("token1", "Old Name")],+ ["token2", token("token2", "Other Token")],+ ]);++ const error = validateAndRenameStyleSource({+ id: "token1",+ name: "New Name",+ styleSources,+ });++ expect(error).toBeUndefined();+ });++ test("returns minlength error for empty name", () => {+ const styleSources: StyleSources = new Map([+ ["token1", token("token1", "Old Name")],+ ]);++ const error = validateAndRenameStyleSource({+ id: "token1",+ name: "",+ styleSources,+ });++ expect(error).toEqual({ type: "minlength", id: "token1" });+ });++ test("returns minlength error for whitespace-only name", () => {+ const styleSources: StyleSources = new Map([+ ["token1", token("token1", "Old Name")],+ ]);++ const error = validateAndRenameStyleSource({+ id: "token1",+ name: " ",+ styleSources,+ });++ expect(error).toEqual({ type: "minlength", id: "token1" });+ });++ test("returns duplicate error when name already exists", () => {+ const styleSources: StyleSources = new Map([+ ["token1", token("token1", "Primary Color")],+ ["token2", token("token2", "Secondary Color")],+ ]);++ const error = validateAndRenameStyleSource({+ id: "token1",+ name: "Secondary Color",+ styleSources,+ });++ expect(error).toEqual({ type: "duplicate", id: "token1" });+ });++ test("allows renaming to same name (no change)", () => {+ const styleSources: StyleSources = new Map([+ ["token1", token("token1", "Primary Color")],+ ]);++ const error = validateAndRenameStyleSource({+ id: "token1",+ name: "Primary Color",+ styleSources,+ });++ expect(error).toBeUndefined();+ });++ test("ignores local style sources when checking duplicates", () => {+ const styleSources = sources([+ token("token1", "Primary Color"),+ local("local1"),+ ]);++ const error = validateAndRenameStyleSource({+ id: "token1",+ name: "Some Name",+ styleSources,+ });++ expect(error).toBeUndefined();+ });+});++describe("renameStyleSourceMutable", () => {+ test("renames a token style source", () => {+ const styleSources: StyleSources = new Map([+ ["token1", token("token1", "Old Name")],+ ]);++ renameStyleSourceMutable({+ id: "token1",+ name: "New Name",+ styleSources,+ });++ const styleSource = styleSources.get("token1");+ expect(styleSource?.type).toBe("token");+ if (styleSource?.type === "token") {+ expect(styleSource.name).toBe("New Name");+ }+ });++ test("does not rename local style source", () => {+ const styleSources: StyleSources = new Map([["local1", local("local1")]]);++ renameStyleSourceMutable({+ id: "local1",+ name: "New Name",+ styleSources,+ });++ const styleSource = styleSources.get("local1");+ expect(styleSource?.type).toBe("local");+ });++ test("handles non-existent style source gracefully", () => {+ const styleSources: StyleSources = new Map();++ expect(() => {+ renameStyleSourceMutable({+ id: "non-existent",+ name: "New Name",+ styleSources,+ });+ }).not.toThrow();+ });++ test("preserves other properties of the style source", () => {+ const styleSources: StyleSources = new Map([+ ["token1", token("token1", "Old Name")],+ ]);++ renameStyleSourceMutable({+ id: "token1",+ name: "New Name",+ styleSources,+ });++ const styleSource = styleSources.get("token1");+ expect(styleSource?.id).toBe("token1");+ expect(styleSource?.type).toBe("token");+ });+});++describe("toggleStyleSourceLockMutable", () => {+ test("locks a token style source", () => {+ const styleSources: StyleSources = new Map([+ ["token1", token("token1", "Token")],+ ]);++ toggleStyleSourceLockMutable({+ id: "token1",+ locked: true,+ styleSources,+ });++ expect(styleSources.get("token1")).toEqual({+ type: "token",+ id: "token1",+ name: "Token",+ locked: true,+ });+ });++ test("unlocks a token style source by removing the locked field", () => {+ const styleSources: StyleSources = new Map([+ ["token1", token("token1", "Token", { locked: true })],+ ]);++ toggleStyleSourceLockMutable({+ id: "token1",+ locked: false,+ styleSources,+ });++ expect(styleSources.get("token1")).toEqual({+ type: "token",+ id: "token1",+ name: "Token",+ });+ });++ test("does not lock local style sources", () => {+ const styleSources: StyleSources = new Map([["local1", local("local1")]]);++ toggleStyleSourceLockMutable({+ id: "local1",+ locked: true,+ styleSources,+ });++ expect(styleSources.get("local1")).toEqual({+ type: "local",+ id: "local1",+ });+ });+});++describe("isStyleSourceLocked", () => {+ test("returns true only for locked tokens", () => {+ expect(+ isStyleSourceLocked({+ type: "token",+ id: "token1",+ name: "Token",+ locked: true,+ })+ ).toBe(true);+ expect(+ isStyleSourceLocked({+ type: "token",+ id: "token1",+ name: "Token",+ })+ ).toBe(false);+ expect(isStyleSourceLocked({ type: "local", id: "local1" })).toBe(false);+ expect(isStyleSourceLocked(undefined)).toBe(false);+ });+});++describe("deleteLocalStyleSourcesMutable", () => {+ test("deletes local style sources from styleSources map", () => {+ const localStyleSourceIds = new Set(["local1", "local2"]);+ const styleSources = sources([+ local("local1"),+ local("local2"),+ local("local3"),+ token("token1", "Token"),+ ]);+ const styles: Styles = new Map();++ deleteLocalStyleSourcesMutable({+ localStyleSourceIds,+ styleSources,+ styles,+ });++ expect(styleSources.has("local1")).toBe(false);+ expect(styleSources.has("local2")).toBe(false);+ expect(styleSources.has("local3")).toBe(true);+ expect(styleSources.has("token1")).toBe(true);+ });++ test("deletes styles associated with local style sources", () => {+ const localStyleSourceIds = new Set(["local1", "local2"]);+ const styleSources: StyleSources = new Map([+ ["local1", local("local1")],+ ["local2", local("local2")],+ ]);+ const styles: Styles = new Map([+ [+ "local1:base:color",+ {+ breakpointId: "base",+ styleSourceId: "local1",+ property: "color",+ value: { type: "keyword", value: "red" },+ },+ ],+ [+ "local2:base:fontSize",+ {+ breakpointId: "base",+ styleSourceId: "local2",+ property: "fontSize",+ value: { type: "unit", value: 16, unit: "px" },+ },+ ],+ [+ "local3:base:display",+ {+ breakpointId: "base",+ styleSourceId: "local3",+ property: "display",+ value: { type: "keyword", value: "flex" },+ },+ ],+ ]);++ deleteLocalStyleSourcesMutable({+ localStyleSourceIds,+ styleSources,+ styles,+ });++ expect(styles.has("local1:base:color")).toBe(false);+ expect(styles.has("local2:base:fontSize")).toBe(false);+ expect(styles.has("local3:base:display")).toBe(true);+ expect(styles.size).toBe(1);+ });++ test("handles empty set of local style source IDs", () => {+ const localStyleSourceIds = new Set<string>();+ const styleSources: StyleSources = new Map([["local1", local("local1")]]);+ const styles: Styles = new Map();++ deleteLocalStyleSourcesMutable({+ localStyleSourceIds,+ styleSources,+ styles,+ });++ expect(styleSources.has("local1")).toBe(true);+ });+});+describe("findDuplicateTokens", () => {+ const findDuplicates = ({+ styleSources,+ styles,+ breakpoints = baseBreakpoints,+ }: {+ styleSources: StyleSource[];+ styles: StyleDecl[];+ breakpoints?: Breakpoint[] | Map<string, Breakpoint>;+ }) =>+ findDuplicateTokens({+ styleSources: toMap(styleSources),+ styles: createStyleDeclMap(styles),+ breakpoints: Array.isArray(breakpoints)+ ? toMap(breakpoints)+ : breakpoints,+ });++ test("finds tokens with identical styles", () => {+ const duplicates = findDuplicates({+ styleSources: [+ { type: "token", id: "token1", name: "Primary Red" },+ { type: "token", id: "token2", name: "Accent Red" },+ { type: "token", id: "token3", name: "Blue" },+ { type: "local", id: "local1" },+ ],+ styles: [+ createStyleDecl("token1", "base", "color", {+ type: "keyword",+ value: "red",+ }),+ createStyleDecl("token2", "base", "color", {+ type: "keyword",+ value: "red",+ }),+ createStyleDecl("token3", "base", "color", {+ type: "keyword",+ value: "blue",+ }),+ ],+ });++ expect(duplicates.size).toBe(2);+ expect(duplicates.get("token1")).toEqual(["token2"]);+ expect(duplicates.get("token2")).toEqual(["token1"]);+ expect(duplicates.has("token3")).toBe(false);+ expect(duplicates.has("local1")).toBe(false);+ });++ test("finds tokens with same name", () => {+ const duplicates = findDuplicates({+ styleSources: [+ { type: "token", id: "token1", name: "Primary" },+ { type: "token", id: "token2", name: "Primary" },+ { type: "token", id: "token3", name: "Secondary" },+ ],+ styles: [+ createStyleDecl("token1", "base", "color", {+ type: "keyword",+ value: "red",+ }),+ createStyleDecl("token2", "base", "color", {+ type: "keyword",+ value: "blue",+ }),+ createStyleDecl("token3", "base", "color", {+ type: "keyword",+ value: "green",+ }),+ ],+ });++ expect(duplicates.size).toBe(2);+ expect(duplicates.get("token1")).toEqual(["token2"]);+ expect(duplicates.get("token2")).toEqual(["token1"]);+ expect(duplicates.has("token3")).toBe(false);+ });++ test("finds tokens with same name AND same styles without duplicating", () => {+ const duplicates = findDuplicates({+ styleSources: [+ { type: "token", id: "token1", name: "Primary" },+ { type: "token", id: "token2", name: "Primary" },+ ],+ styles: [+ createStyleDecl("token1", "base", "color", {+ type: "keyword",+ value: "red",+ }),+ createStyleDecl("token2", "base", "color", {+ type: "keyword",+ value: "red",+ }),+ ],+ });++ expect(duplicates.size).toBe(2);+ // Should list each token only once, not twice (once for name, once for styles)+ expect(duplicates.get("token1")).toEqual(["token2"]);+ expect(duplicates.get("token2")).toEqual(["token1"]);+ });++ test("finds mixed duplicates: some by style, some by name", () => {+ const duplicates = findDuplicates({+ styleSources: [+ { type: "token", id: "token1", name: "Red A" },+ { type: "token", id: "token2", name: "Red B" },+ { type: "token", id: "token3", name: "Duplicate Name" },+ { type: "token", id: "token4", name: "Duplicate Name" },+ ],+ styles: [+ createStyleDecl("token1", "base", "color", {+ type: "keyword",+ value: "red",+ }),+ createStyleDecl("token2", "base", "color", {+ type: "keyword",+ value: "red",+ }),+ createStyleDecl("token3", "base", "color", {+ type: "keyword",+ value: "blue",+ }),+ createStyleDecl("token4", "base", "color", {+ type: "keyword",+ value: "green",+ }),+ ],+ });++ expect(duplicates.size).toBe(4);+ expect(duplicates.get("token1")).toEqual(["token2"]);+ expect(duplicates.get("token2")).toEqual(["token1"]);+ expect(duplicates.get("token3")).toEqual(["token4"]);+ expect(duplicates.get("token4")).toEqual(["token3"]);+ });++ test("finds multiple groups of duplicates", () => {+ const duplicates = findDuplicates({+ styleSources: [+ { type: "token", id: "token1", name: "Red 1" },+ { type: "token", id: "token2", name: "Red 2" },+ { type: "token", id: "token3", name: "Blue 1" },+ { type: "token", id: "token4", name: "Blue 2" },+ { type: "token", id: "token5", name: "Blue 3" },+ ],+ styles: [+ createStyleDecl("token1", "base", "color", {+ type: "keyword",+ value: "red",+ }),+ createStyleDecl("token2", "base", "color", {+ type: "keyword",+ value: "red",+ }),+ createStyleDecl("token3", "base", "color", {+ type: "keyword",+ value: "blue",+ }),+ createStyleDecl("token4", "base", "color", {+ type: "keyword",+ value: "blue",+ }),+ createStyleDecl("token5", "base", "color", {+ type: "keyword",+ value: "blue",+ }),+ ],+ });++ expect(duplicates.size).toBe(5);+ expect(duplicates.get("token1")).toEqual(["token2"]);+ expect(duplicates.get("token2")).toEqual(["token1"]);+ expect(duplicates.get("token3")).toEqual(["token4", "token5"]);+ expect(duplicates.get("token4")).toEqual(["token3", "token5"]);+ expect(duplicates.get("token5")).toEqual(["token3", "token4"]);+ });++ test("returns empty map when no duplicates exist", () => {+ const duplicates = findDuplicates({+ styleSources: [+ { type: "token", id: "token1", name: "Red" },+ { type: "token", id: "token2", name: "Blue" },+ ],+ styles: [+ createStyleDecl("token1", "base", "color", {+ type: "keyword",+ value: "red",+ }),+ createStyleDecl("token2", "base", "color", {+ type: "keyword",+ value: "blue",+ }),+ ],+ });++ expect(duplicates.size).toBe(0);+ });++ test("compares tokens across breakpoints and states", () => {+ const duplicates = findDuplicates({+ breakpoints: [+ { id: "base", label: "base" },+ { id: "tablet", label: "tablet", minWidth: 768 },+ ],+ styleSources: [+ { type: "token", id: "token1", name: "Token 1" },+ { type: "token", id: "token2", name: "Token 2" },+ ],+ styles: [+ createStyleDecl("token1", "base", "color", {+ type: "keyword",+ value: "red",+ }),+ {+ ...createStyleDecl("token1", "tablet", "color", {+ type: "keyword",+ value: "blue",+ }),+ state: ":hover",+ },+ createStyleDecl("token2", "base", "color", {+ type: "keyword",+ value: "red",+ }),+ {+ ...createStyleDecl("token2", "tablet", "color", {+ type: "keyword",+ value: "blue",+ }),+ state: ":hover",+ },+ ],+ });++ expect(duplicates.size).toBe(2);+ expect(duplicates.get("token1")).toEqual(["token2"]);+ expect(duplicates.get("token2")).toEqual(["token1"]);+ });++ test("ignores local style sources", () => {+ const duplicates = findDuplicates({+ styleSources: [+ { type: "local", id: "local1" },+ { type: "local", id: "local2" },+ ],+ styles: [+ createStyleDecl("local1", "base", "color", {+ type: "keyword",+ value: "red",+ }),+ createStyleDecl("local2", "base", "color", {+ type: "keyword",+ value: "red",+ }),+ ],+ });++ expect(duplicates.size).toBe(0);+ });++ test("handles tokens with no styles", () => {+ const duplicates = findDuplicates({+ styleSources: [+ { type: "token", id: "token1", name: "Empty 1" },+ { type: "token", id: "token2", name: "Empty 2" },+ { type: "token", id: "token3", name: "With Styles" },+ ],+ styles: [+ createStyleDecl("token3", "base", "color", {+ type: "keyword",+ value: "red",+ }),+ ],+ });++ // Empty tokens should be considered duplicates of each other+ expect(duplicates.size).toBe(2);+ expect(duplicates.get("token1")).toEqual(["token2"]);+ expect(duplicates.get("token2")).toEqual(["token1"]);+ expect(duplicates.has("token3")).toBe(false);+ });+});diff --git a/packages/project-build/src/runtime/styles.ts b/packages/project-build/src/runtime/styles.tsnew file mode 100644index 0000000000..137d762de0--- /dev/null+++ b/packages/project-build/src/runtime/styles.ts@@ -0,0 +1,2880 @@+import { z } from "zod";+import { nanoid } from "nanoid";+import deepEqual from "fast-deep-equal";+import { camelCaseProperty } from "@webstudio-is/css-data";+import { styleValue, toValue, type StyleValue } from "@webstudio-is/css-engine";+import {+ getStyleDeclKey,+ styleDecl as styleDeclSchema,+ type Breakpoint,+ type Breakpoints,+ type Instance,+ type Prop,+ type StyleDecl,+ type StyleSource,+ type StyleSourceSelection,+ type StyleSourceSelections,+ type StyleSources,+ type Styles,+} from "@webstudio-is/sdk";+import type { BuilderPatch, BuilderPatchChange } from "../contracts/patch";+import type { BuilderState } from "../state/builder-state";+import {+ findSerializedPageByInput,+ getHomePageRootInstanceId,+ getSerializedPages,+} from "./pages";+import { getInstanceDepths } from "./instances";+import { throwBuilderRuntimeError } from "./errors";+import { createRuntimeMutation } from "./mutation";+import { serializeStyleDeclarations } from "./style-utils";+import { createPropValue } from "./props";+import { getStyleSourceStylesSignature } from "./style-copy";+import { isBaseBreakpoint } from "./breakpoints";++export const serializeDesignTokens = ({+ styleSources,+ styles,+ styleSourceSelections,+ filter,+ withUsage,+ sort,+}: {+ styleSources: Iterable<StyleSource> | Map<string, StyleSource>;+ styles: Iterable<StyleDecl> | Map<string, StyleDecl>;+ styleSourceSelections:+ | Iterable<StyleSourceSelection>+ | Map<string, StyleSourceSelection>;+ filter?: string;+ withUsage?: boolean;+ sort?: "name" | "usage";+}) => {+ const shouldCountUsage = withUsage === true || sort === "usage";+ const styleDecls =+ styles instanceof Map ? Array.from(styles.values()) : Array.from(styles);+ const selections =+ styleSourceSelections instanceof Map+ ? Array.from(styleSourceSelections.values())+ : Array.from(styleSourceSelections);+ const tokens = (+ styleSources instanceof Map+ ? Array.from(styleSources.values())+ : Array.from(styleSources)+ )+ .filter((styleSource) => styleSource.type === "token")+ .filter(+ (styleSource) => filter === undefined || styleSource.name.includes(filter)+ )+ .map((styleSource) => {+ const tokenStyles = Object.fromEntries(+ styleDecls+ .filter((style) => style.styleSourceId === styleSource.id)+ .map((style) => [style.property, style.value])+ );+ const usageCount = selections.filter((selection) =>+ selection.values.includes(styleSource.id)+ ).length;+ return {+ id: styleSource.id,+ name: styleSource.name,+ styles: tokenStyles,+ usageCount: shouldCountUsage ? usageCount : undefined,+ };+ });++ tokens.sort((left, right) =>+ sort === "usage"+ ? (right.usageCount ?? 0) - (left.usageCount ?? 0)+ : left.name.localeCompare(right.name)+ );+ return { tokens };+};++const getRequiredStyleState = (+ state: Pick<BuilderState, "styles" | "styleSources" | "styleSourceSelections">+) => {+ if (+ state.styles === undefined ||+ state.styleSources === undefined ||+ state.styleSourceSelections === undefined+ ) {+ return throwBuilderRuntimeError(+ "BAD_REQUEST",+ "Style namespaces are missing"+ );+ }+ return {+ styles: state.styles,+ styleSources: state.styleSources,+ styleSourceSelections: state.styleSourceSelections,+ };+};++export const getStyleDeclarations = (+ state: Pick<+ BuilderState,+ "pages" | "instances" | "styles" | "styleSources" | "styleSourceSelections"+ >,+ input: {+ instanceIds?: string[];+ pageId?: string;+ pagePath?: string;+ breakpoint?: string;+ state?: string;+ property?: string;+ propertyFilter?: string;+ includeTokens?: boolean;+ } = {}+) => {+ const property =+ input.property === undefined+ ? undefined+ : normalizeStyleProperty(input.property);+ const styleState = getRequiredStyleState(state);+ const hasPageFilter =+ input.pageId !== undefined || input.pagePath !== undefined;+ const pages = hasPageFilter ? getSerializedPages(state) : undefined;+ const page =+ pages === undefined ? undefined : findSerializedPageByInput(pages, input);+ if (hasPageFilter && page === undefined) {+ return throwBuilderRuntimeError("NOT_FOUND", "Page not found");+ }+ const pageInstanceIds =+ page === undefined+ ? undefined+ : state.instances === undefined+ ? throwBuilderRuntimeError(+ "BAD_REQUEST",+ "Instances namespace is missing"+ )+ : new Set(+ getInstanceDepths(state.instances, [page.rootInstanceId]).keys()+ );+ const inputInstanceIds =+ input.instanceIds === undefined ? undefined : new Set(input.instanceIds);+ const instanceIds =+ pageInstanceIds === undefined+ ? inputInstanceIds+ : new Set(+ Array.from(inputInstanceIds ?? pageInstanceIds).filter((instanceId) =>+ pageInstanceIds.has(instanceId)+ )+ );+ return {+ declarations: serializeStyleDeclarations({+ styles: styleState.styles.values(),+ styleSources: styleState.styleSources.values(),+ styleSourceSelections: styleState.styleSourceSelections.values(),+ instanceIds,+ breakpoint: input.breakpoint,+ state: input.state,+ property,+ propertyFilter: input.propertyFilter,+ includeTokens: input.includeTokens,+ }),+ };+};++export const listDesignTokens = (+ state: Pick<+ BuilderState,+ "styles" | "styleSources" | "styleSourceSelections"+ >,+ input: {+ filter?: string;+ withUsage?: boolean;+ sort?: "name" | "usage";+ } = {}+) => serializeDesignTokens({ ...getRequiredStyleState(state), ...input });++const DEFAULT_BREAKPOINT_ID = "base";++const normalizeStyleProperty = (property: unknown): StyleDecl["property"] =>+ typeof property === "string"+ ? camelCaseProperty(property as StyleDecl["property"])+ : (property as StyleDecl["property"]);++const getBaseBreakpointId = (breakpoints: Breakpoints | undefined) => {+ const breakpoint = Array.from(breakpoints?.values() ?? []).find(+ isBaseBreakpoint+ );+ return breakpoint?.id ?? DEFAULT_BREAKPOINT_ID;+};++const withDefaultBreakpoint = <Input extends { breakpoint?: string }>(+ input: Input,+ breakpoint: string+): Input => ({+ ...input,+ breakpoint: input.breakpoint ?? breakpoint,+});++export const styleUpdateInput = z.object({+ instanceId: z.string(),+ property: z.string(),+ value: z.unknown(),+ breakpoint: z.string().optional(),+ state: z.string().optional(),+ listed: z.boolean().optional(),+ createLocalIfMissing: z.boolean().optional(),+});++export const styleDeleteInput = z.object({+ instanceId: z.string(),+ property: z.string(),+ breakpoint: z.string().optional(),+ state: z.string().optional(),+});++export const styleReplaceInput = z.object({+ property: z.string(),+ fromValue: z.unknown(),+ toValue: z.unknown(),+ pageId: z.string().optional(),+ pagePath: z.string().optional(),+});++const escapeRegex = (value: string) =>+ value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");++const createCssVariableNameRegex = (name: string) =>+ new RegExp(`${escapeRegex(name)}(?![\\w-])`, "g");++export const createCssVariableNamesRegex = (names: Set<string>) => {+ if (names.size === 0) {+ return;+ }+ return new RegExp(+ `(?:${Array.from(names)+ .sort((left, right) => right.length - left.length)+ .map(escapeRegex)+ .join("|")})(?![\\w-])`,+ "g"+ );+};++export const collectCssVariableReferences = (value: string, regex?: RegExp) => {+ const references = new Set<string>();+ if (regex === undefined) {+ return references;+ }+ regex.lastIndex = 0;+ for (const match of value.matchAll(regex)) {+ references.add(match[0]);+ }+ return references;+};++export const rewriteCssVariableReferencesInStyleValue = (+ value: StyleValue,+ replacements: Record<string, string>+) => {+ let serialized = JSON.stringify(value);+ for (const [fromName, toName] of Object.entries(replacements)) {+ serialized = serialized.replace(+ new RegExp(`("value":")${escapeRegex(fromName.slice(2))}(?![\\w-])`, "g"),+ `$1${toName.slice(2)}`+ );+ serialized = serialized.replace(+ createCssVariableNameRegex(fromName),+ toName+ );+ }+ return JSON.parse(serialized) as StyleValue;+};++export const rewriteCssVariableReferencesInString = (+ value: string,+ replacements: Record<string, string>+) => {+ let nextValue = value;+ for (const [fromName, toName] of Object.entries(replacements)) {+ nextValue = nextValue.replace(createCssVariableNameRegex(fromName), toName);+ }+ return nextValue;+};++export const getDefinedCssVariableNames = (styles: Iterable<StyleDecl>) => {+ const names = new Set<string>();+ for (const styleDecl of styles) {+ if (styleDecl.property.startsWith("--")) {+ names.add(styleDecl.property);+ }+ }+ return names;+};++export type CssVariableNameError =+ | { type: "required"; message: string }+ | { type: "invalid"; message: string }+ | { type: "duplicate"; message: string };++export const cssVariableValueInput = z.union([z.string(), styleValue]);++export const validateCssVariableNameWithStyles = ({+ name,+ styles,+ currentProperty,+}: {+ name: string;+ styles: Iterable<StyleDecl>;+ currentProperty?: string;+}): CssVariableNameError | undefined => {+ if (name.trim().length === 0) {+ return {+ type: "required",+ message: "CSS variable name cannot be empty",+ };+ }+ if (name.startsWith("--") === false) {+ return {+ type: "invalid",+ message: 'CSS variable name must start with "--"',+ };+ }+ for (const styleDecl of styles) {+ if (+ styleDecl.property === name &&+ styleDecl.property !== currentProperty &&+ styleDecl.property.startsWith("--")+ ) {+ return {+ type: "duplicate",+ message: `CSS variable "${name}" already exists`,+ };+ }+ }+};++export const getInstanceIdByStyleSourceId = (+ styleSourceSelections: Iterable<StyleSourceSelection>+) => {+ const instanceIdByStyleSourceId = new Map<string, Instance["id"]>();+ for (const selection of styleSourceSelections) {+ for (const styleSourceId of selection.values) {+ instanceIdByStyleSourceId.set(styleSourceId, selection.instanceId);+ }+ }+ return instanceIdByStyleSourceId;+};++const valuesOf = <Value>(+ value: Iterable<Value> | Map<unknown, Value>+): Iterable<Value> => (value instanceof Map ? value.values() : value);++const getCssVariableUsageCounts = ({+ styles,+ props,+}: {+ styles: Iterable<StyleDecl>;+ props: Iterable<Prop>;+}) => {+ const styleList = Array.from(styles);+ const names = getDefinedCssVariableNames(styleList);+ const regex = createCssVariableNamesRegex(names);+ const counts = new Map<string, number>();+ const addReferences = (value: string) => {+ for (const name of collectCssVariableReferences(value, regex)) {+ counts.set(name, (counts.get(name) ?? 0) + 1);+ }+ };+ for (const declaration of styleList) {+ addReferences(toValue(declaration.value));+ }+ for (const prop of props) {+ if (prop.type === "string" && prop.name === "code") {+ addReferences(prop.value);+ }+ }+ return counts;+};++export const findCssVariableUsagesByInstance = ({+ styleSourceSelections,+ styles,+ props,+}: {+ styleSourceSelections:+ | Iterable<StyleSourceSelection>+ | Map<string, StyleSourceSelection>;+ styles: Iterable<StyleDecl> | Map<string, StyleDecl>;+ props: Iterable<Prop> | Map<string, Prop>;+}): {+ counts: Map<string, number>;+ instances: Map<string, Set<Instance["id"]>>;+} => {+ const counts = new Map<string, number>();+ const instances = new Map<string, Set<Instance["id"]>>();+ const styleList = Array.from(valuesOf(styles));+ const definedVariables = getDefinedCssVariableNames(styleList);+ if (definedVariables.size === 0) {+ return { counts, instances };+ }+ const definedVariablesRegex = createCssVariableNamesRegex(definedVariables);+ const instancesByStyleSource = getInstanceIdByStyleSourceId(+ valuesOf(styleSourceSelections)+ );++ const addReference = (name: string, instanceId: Instance["id"]) => {+ counts.set(name, (counts.get(name) ?? 0) + 1);+ const instanceIds = instances.get(name) ?? new Set<Instance["id"]>();+ instanceIds.add(instanceId);+ instances.set(name, instanceIds);+ };++ for (const styleDecl of styleList) {+ const instanceId = instancesByStyleSource.get(styleDecl.styleSourceId);+ if (instanceId === undefined) {+ continue;+ }+ for (const name of collectCssVariableReferences(+ toValue(styleDecl.value),+ definedVariablesRegex+ )) {+ addReference(name, instanceId);+ }+ }++ for (const prop of valuesOf(props)) {+ if (prop.type === "string" && prop.name === "code" && prop.value) {+ for (const name of collectCssVariableReferences(+ prop.value,+ definedVariablesRegex+ )) {+ addReference(name, prop.instanceId);+ }+ }+ }++ return { counts, instances };+};++export const getCssVariableDefinitionsByVariable = ({+ styleSourceSelections,+ styles,+}: {+ styleSourceSelections:+ | Iterable<StyleSourceSelection>+ | Map<string, StyleSourceSelection>;+ styles: Iterable<StyleDecl> | Map<string, StyleDecl>;+}) => {+ const definitions = new Map<string, Set<Instance["id"]>>();+ const instancesByStyleSource = getInstanceIdByStyleSourceId(+ valuesOf(styleSourceSelections)+ );++ for (const styleDecl of valuesOf(styles)) {+ if (styleDecl.property.startsWith("--") === false) {+ continue;+ }+ const instanceId = instancesByStyleSource.get(styleDecl.styleSourceId);+ if (instanceId === undefined) {+ continue;+ }+ const instanceIds =+ definitions.get(styleDecl.property) ?? new Set<Instance["id"]>();+ instanceIds.add(instanceId);+ definitions.set(styleDecl.property, instanceIds);+ }++ return definitions;+};++export const getReferencedCssVariables = ({+ styles,+ props,+}: {+ styles: Iterable<StyleDecl> | Map<string, StyleDecl>;+ props: Iterable<Prop> | Map<string, Prop>;+}) => {+ const styleList = Array.from(valuesOf(styles));+ const names = getDefinedCssVariableNames(styleList);+ const regex = createCssVariableNamesRegex(names);+ const referenced = new Set<string>();+ const addReferences = (value: string) => {+ for (const name of collectCssVariableReferences(value, regex)) {+ referenced.add(name);+ }+ };++ for (const styleDecl of styleList) {+ addReferences(toValue(styleDecl.value));+ }+ for (const prop of valuesOf(props)) {+ if (prop.type === "string" && prop.name === "code" && prop.value) {+ addReferences(prop.value);+ }+ }++ return referenced;+};++const toCssVariableStyleValue = (value: string | StyleValue): StyleValue =>+ typeof value === "string" ? { type: "unparsed", value } : value;++const createCssVariableDeclaration = ({+ styleSourceId,+ property,+ value,+ breakpointId,+}: {+ styleSourceId: string;+ property: string;+ value: string | StyleValue;+ breakpointId: string;+}) =>+ createStyleDecl({+ styleSourceId,+ breakpointId,+ property,+ value: toCssVariableStyleValue(value),+ });++const createCssVariableDefinePayload = ({+ vars,+ rootStyleSourceId,+ styles,+ overwrite,+ breakpointId = DEFAULT_BREAKPOINT_ID,+}: {+ vars: Record<string, string | StyleValue>;+ rootStyleSourceId: string;+ styles: Iterable<StyleDecl>;+ overwrite?: boolean;+ breakpointId?: string;+}): {+ payload: BuilderPatchChange[];+ names: string[];+ conflicts: string[];+ styleKeys: string[];+} => {+ const stylesList = Array.from(styles);+ const stylePatches = [];+ const conflicts = [];++ for (const [property, value] of Object.entries(vars)) {+ const existingDeclarations = stylesList.filter(+ (declaration) => declaration.property === property+ );+ if (existingDeclarations.length > 0 && overwrite !== true) {+ conflicts.push(property);+ continue;+ }+ const declarations =+ existingDeclarations.length === 0+ ? [+ createCssVariableDeclaration({+ styleSourceId: rootStyleSourceId,+ property,+ value,+ breakpointId,+ }),+ ]+ : existingDeclarations.map((declaration) =>+ updateStyleDecl(declaration, {+ value: toCssVariableStyleValue(value),+ })+ );+ const existingStyleKeys = new Set(+ existingDeclarations.map((declaration) => getStyleDeclKey(declaration))+ );+ for (const declaration of declarations) {+ const key = getStyleDeclKey(declaration);+ stylePatches.push({+ op: existingStyleKeys.has(key)+ ? ("replace" as const)+ : ("add" as const),+ path: [key],+ value: declaration,+ });+ }+ }++ return {+ payload:+ stylePatches.length === 0+ ? []+ : [{ namespace: "styles", patches: stylePatches }],+ names: Object.keys(vars),+ conflicts,+ styleKeys: stylePatches.map((patch) => String(patch.path[0])),+ };+};++export const createCssVariableRootDefinePayload = ({+ rootInstanceId,+ vars,+ styleSources,+ styleSourceSelections,+ styles,+ overwrite,+ breakpointId = DEFAULT_BREAKPOINT_ID,+ createId,+}: {+ rootInstanceId: Instance["id"];+ vars: Record<string, string | StyleValue>;+ styleSources: Map<StyleSource["id"], StyleSource>;+ styleSourceSelections: Iterable<StyleSourceSelection>;+ styles: Iterable<StyleDecl>;+ overwrite?: boolean;+ breakpointId?: string;+ createId: () => StyleSource["id"];+}) => {+ const rootStyleSourceResult = createLocalStyleSourcePatchPlan({+ createdLocalSourceIds: new Map(),+ instanceId: rootInstanceId,+ styleSources,+ styleSourceSelection: Array.from(styleSourceSelections).find(+ (selection) => selection.instanceId === rootInstanceId+ ),+ shouldCreate: true,+ createId,+ });+ if (rootStyleSourceResult === undefined) {+ return {+ payload: [],+ names: Object.keys(vars),+ conflicts: [],+ styleKeys: [],+ missingRootStyleSource: true,+ };+ }+ const result = createCssVariableDefinePayload({+ vars,+ rootStyleSourceId: rootStyleSourceResult.styleSourceId,+ styles,+ overwrite,+ breakpointId,+ });+ return {+ ...result,+ payload: [...rootStyleSourceResult.payload, ...result.payload],+ missingRootStyleSource: false,+ };+};++export const createCssVariableDeletePayload = ({+ names,+ styles,+ props,+ force,+}: {+ names: string[];+ styles: Iterable<StyleDecl>;+ props: Iterable<Prop>;+ force?: boolean;+}): {+ payload: BuilderPatchChange[];+ styleKeys: string[];+ referenced: string[];+} => {+ const styleList = Array.from(styles);+ const usageCounts = getCssVariableUsageCounts({ styles: styleList, props });+ const referenced =+ force === true+ ? []+ : names.filter((name) => (usageCounts.get(name) ?? 0) > 0);+ if (referenced.length > 0) {+ return { payload: [], styleKeys: [], referenced };+ }+ const namesSet = new Set(names);+ const styleKeys = styleList.flatMap((declaration) =>+ namesSet.has(declaration.property) ? [getStyleDeclKey(declaration)] : []+ );++ return {+ payload:+ styleKeys.length === 0+ ? []+ : [+ {+ namespace: "styles",+ patches: styleKeys.map((key) => ({+ op: "remove" as const,+ path: [key],+ })),+ },+ ],+ styleKeys,+ referenced,+ };+};++export const createCssVariableReferenceRewritePayload = ({+ replacements,+ scopeRegex,+ styles,+ props,+ styleSourceSelections,+}: {+ replacements: Record<string, string>;+ scopeRegex?: RegExp;+ styles: Iterable<StyleDecl>;+ props: Iterable<Prop>;+ styleSourceSelections: Iterable<StyleSourceSelection>;+}): {+ payload: BuilderPatchChange[];+ styleKeys: string[];+ propIds: string[];+} => {+ const instanceIdByStyleSourceId = getInstanceIdByStyleSourceId(+ styleSourceSelections+ );+ const stylePatches = [];+ for (const declaration of styles) {+ const scope =+ instanceIdByStyleSourceId.get(declaration.styleSourceId) ??+ declaration.styleSourceId;+ if (scopeRegex !== undefined && scopeRegex.test(scope) === false) {+ continue;+ }+ const value = rewriteCssVariableReferencesInStyleValue(+ declaration.value,+ replacements+ );+ if (JSON.stringify(value) === JSON.stringify(declaration.value)) {+ continue;+ }+ const nextDeclaration = updateStyleDecl(declaration, { value });+ stylePatches.push({+ op: "replace" as const,+ path: [getStyleDeclKey(nextDeclaration)],+ value: nextDeclaration,+ });+ }+ const propPatches = [];+ for (const prop of props) {+ if (prop.type !== "string" || prop.name !== "code") {+ continue;+ }+ if (+ scopeRegex !== undefined &&+ scopeRegex.test(prop.instanceId) === false+ ) {+ continue;+ }+ const value = rewriteCssVariableReferencesInString(+ prop.value,+ replacements+ );+ if (value === prop.value) {+ continue;+ }+ propPatches.push({+ op: "replace" as const,+ path: [prop.id],+ value: createPropValue({ ...prop, value }),+ });+ }+ const payload: BuilderPatchChange[] = [];+ if (stylePatches.length > 0) {+ payload.push({ namespace: "styles", patches: stylePatches });+ }+ if (propPatches.length > 0) {+ payload.push({ namespace: "props", patches: propPatches });+ }++ return {+ payload,+ styleKeys: stylePatches.map((patch) => String(patch.path[0])),+ propIds: propPatches.map((patch) => String(patch.path[0])),+ };+};++export const performCssVariableRename = (+ styles: Map<string, StyleDecl>,+ oldProperty: string,+ newProperty: string+): Map<string, StyleDecl> => {+ const updatedStyles = new Map(styles);+ const definitionsToUpdate = [];+ for (const [key, declaration] of updatedStyles) {+ if (declaration.property === oldProperty) {+ definitionsToUpdate.push({ key, declaration });+ }+ }+ for (const { key, declaration } of definitionsToUpdate) {+ updatedStyles.delete(key);+ const nextDeclaration = {+ ...declaration,+ property: newProperty as StyleDecl["property"],+ };+ updatedStyles.set(getStyleDeclKey(nextDeclaration), nextDeclaration);+ }+ for (const [key, declaration] of updatedStyles) {+ const value = rewriteCssVariableReferencesInStyleValue(declaration.value, {+ [oldProperty]: newProperty,+ });+ if (JSON.stringify(value) !== JSON.stringify(declaration.value)) {+ updatedStyles.set(key, { ...declaration, value });+ }+ }+ return updatedStyles;+};++export const updateVarReferencesInProps = (+ props: Map<string, Prop>,+ oldProperty: string,+ newProperty: string+) => {+ const updatedProps = new Map(props);+ for (const [key, prop] of updatedProps) {+ if (prop.type !== "string" || prop.name !== "code" || prop.value === "") {+ continue;+ }+ const value = rewriteCssVariableReferencesInString(prop.value, {+ [oldProperty]: newProperty,+ });+ if (value !== prop.value) {+ updatedProps.set(key, createPropValue({ ...prop, value }));+ }+ }+ return updatedProps;+};++export const renameCssVariableMutable = ({+ styles,+ props,+ oldProperty,+ newProperty,+}: {+ styles: Map<string, StyleDecl>;+ props: Map<string, Prop>;+ oldProperty: string;+ newProperty: string;+}) => {+ const updatedStyles = performCssVariableRename(+ styles,+ oldProperty,+ newProperty+ );+ styles.clear();+ for (const [key, value] of updatedStyles) {+ styles.set(key, value);+ }++ const updatedProps = updateVarReferencesInProps(+ props,+ oldProperty,+ newProperty+ );+ props.clear();+ for (const [key, value] of updatedProps) {+ props.set(key, value);+ }+};++export const serializeCssVariables = ({+ styles,+ props,+ styleSourceSelections,+ filter,+ withUsage,+}: {+ styles: Iterable<StyleDecl>;+ props: Iterable<Prop>;+ styleSourceSelections: Iterable<StyleSourceSelection>;+ filter?: string;+ withUsage?: boolean;+}) => {+ const instanceIdByStyleSourceId = getInstanceIdByStyleSourceId(+ styleSourceSelections+ );+ const usageCounts =+ withUsage === true+ ? getCssVariableUsageCounts({ styles, props })+ : undefined;+ return {+ vars: Array.from(styles)+ .filter((declaration) => declaration.property.startsWith("--"))+ .filter(+ (declaration) =>+ filter === undefined || declaration.property.includes(filter)+ )+ .map((declaration) => ({+ name: declaration.property,+ value: toValue(declaration.value),+ scope:+ instanceIdByStyleSourceId.get(declaration.styleSourceId) ??+ declaration.styleSourceId,+ usageCount:+ withUsage === true+ ? (usageCounts?.get(declaration.property) ?? 0)+ : undefined,+ })),+ };+};++export const designTokenStyleInput = z.object({+ property: z.string(),+ value: z.unknown(),+ breakpoint: z.string().optional(),+ state: z.string().optional(),+});++export const designTokenCreateInput = z.object({+ tokenId: z.string().optional(),+ name: z.string().min(1),+ styles: z.record(z.unknown()).optional(),+ declarations: z.array(designTokenStyleInput).optional(),+});++export const createTokenStyleSource = ({+ id,+ name,+ locked,+}: {+ id: StyleSource["id"];+ name: string;+ locked?: boolean;+}): Extract<StyleSource, { type: "token" }> => ({+ type: "token",+ id,+ name,+ ...(locked === true ? { locked: true } : {}),+});++export const findDesignToken = (+ styleSources: Iterable<StyleSource>,+ tokenId: StyleSource["id"]+) =>+ Array.from(styleSources).find(+ (styleSource) => styleSource.type === "token" && styleSource.id === tokenId+ );++export type RenameStyleSourceError =+ | { type: "minlength"; id: StyleSource["id"] }+ | { type: "duplicate"; id: StyleSource["id"] };++export const validateStyleSourceName = ({+ id,+ name,+ styleSources,+}: {+ id: StyleSource["id"];+ name: string;+ styleSources: StyleSources;+}): RenameStyleSourceError | undefined => {+ if (name.trim().length === 0) {+ return { type: "minlength", id };+ }+ for (const styleSource of styleSources.values()) {+ if (+ styleSource.type === "token" &&+ styleSource.name === name &&+ styleSource.id !== id+ ) {+ return { type: "duplicate", id };+ }+ }+};++export const createDesignTokenStyleInputs = (input: {+ styles?: Record<string, unknown>;+ declarations?: Array<{+ property: string;+ value?: unknown;+ breakpoint?: string;+ state?: StyleDecl["state"];+ }>;+}): Array<{+ property: string;+ value?: unknown;+ breakpoint?: string;+ state?: StyleDecl["state"];+}> => [+ ...Object.entries(input.styles ?? {}).map(([property, value]) => ({+ property,+ value,+ })),+ ...(input.declarations ?? []),+];++export const getLocalStyleSourceId = ({+ styleSources,+ styleSourceSelection,+}: {+ styleSources: Pick<StyleSources, "get">;+ styleSourceSelection: StyleSourceSelection | undefined;+}) =>+ styleSourceSelection?.values.find(+ (styleSourceId) => styleSources.get(styleSourceId)?.type === "local"+ );++export const getOrCreateStyleSourceSelectionMutable = (+ styleSourceSelections: StyleSourceSelections,+ instanceId: Instance["id"]+) => {+ let styleSourceSelection = styleSourceSelections.get(instanceId);+ if (styleSourceSelection === undefined) {+ styleSourceSelection = {+ instanceId,+ values: [],+ };+ styleSourceSelections.set(instanceId, styleSourceSelection);+ }+ return styleSourceSelection;+};++export const getStyleSourceInsertionIndex = ({+ styleSourceIds,+ styleSources,+ position = "before-local",+}: {+ styleSourceIds: StyleSource["id"][];+ styleSources: Pick<StyleSources, "get">;+ position?: "before-local" | "after-local";+}) => {+ const localIndex = styleSourceIds.findIndex(+ (styleSourceId) => styleSources.get(styleSourceId)?.type === "local"+ );+ if (localIndex === -1) {+ return styleSourceIds.length;+ }+ return position === "after-local" ? localIndex + 1 : localIndex;+};++export const isStyleSourceLocked = (styleSource: StyleSource | undefined) =>+ styleSource?.type === "token" && styleSource.locked === true;++type StyleSourceSelectionAddPlan =+ | {+ type: "create";+ selection: StyleSourceSelection;+ }+ | {+ type: "insert";+ index: number;+ }+ | {+ type: "exists";+ };++type StyleSourceSelectionRemovePlan =+ | {+ type: "remove";+ index: number;+ }+ | {+ type: "missing";+ };++export const createStyleSourceSelectionAddPlan = ({+ styleSourceSelection,+ styleSources,+ instanceId,+ styleSourceId,+ position,+}: {+ styleSourceSelection: StyleSourceSelection | undefined;+ styleSources: Pick<StyleSources, "get">;+ instanceId: Instance["id"];+ styleSourceId: StyleSource["id"];+ position?: "before-local" | "after-local";+}): StyleSourceSelectionAddPlan => {+ if (styleSourceSelection === undefined) {+ return {+ type: "create",+ selection: { instanceId, values: [styleSourceId] },+ };+ }+ if (styleSourceSelection.values.includes(styleSourceId)) {+ return { type: "exists" };+ }+ return {+ type: "insert",+ index: getStyleSourceInsertionIndex({+ styleSourceIds: styleSourceSelection.values,+ styleSources,+ position,+ }),+ };+};++export const createStyleSourceSelectionAddPatch = ({+ styleSourceSelection,+ styleSources,+ instanceId,+ styleSourceId,+ position,+}: {+ styleSourceSelection: StyleSourceSelection | undefined;+ styleSources: Pick<StyleSources, "get">;+ instanceId: Instance["id"];+ styleSourceId: StyleSource["id"];+ position?: "before-local" | "after-local";+}) => {+ const plan = createStyleSourceSelectionAddPlan({+ styleSourceSelection,+ styleSources,+ instanceId,+ styleSourceId,+ position,+ });+ if (plan.type === "exists") {+ return;+ }+ if (plan.type === "create") {+ return {+ op: "add" as const,+ path: [instanceId],+ value: plan.selection,+ };+ }+ return {+ op: "add" as const,+ path: [instanceId, "values", plan.index],+ value: styleSourceId,+ };+};++export const createStyleSourceSelectionRemovePlan = ({+ styleSourceSelection,+ styleSourceId,+}: {+ styleSourceSelection: StyleSourceSelection | undefined;+ styleSourceId: StyleSource["id"];+}): StyleSourceSelectionRemovePlan => {+ const index = styleSourceSelection?.values.indexOf(styleSourceId) ?? -1;+ return index === -1 ? { type: "missing" } : { type: "remove", index };+};++export const createStyleSourceSelectionRemovePatch = ({+ styleSourceSelection,+ instanceId,+ styleSourceId,+}: {+ styleSourceSelection: StyleSourceSelection | undefined;+ instanceId: Instance["id"];+ styleSourceId: StyleSource["id"];+}) => {+ const plan = createStyleSourceSelectionRemovePlan({+ styleSourceSelection,+ styleSourceId,+ });+ return plan.type === "missing"+ ? undefined+ : {+ op: "remove" as const,+ path: [instanceId, "values", plan.index],+ };+};++export const addStyleSourceToInstanceMutable = ({+ styleSourceSelections,+ styleSources,+ instanceId,+ styleSourceId,+ position,+}: {+ styleSourceSelections: StyleSourceSelections;+ styleSources: StyleSources;+ instanceId: Instance["id"];+ styleSourceId: StyleSource["id"];+ position?: "before-local" | "after-local";+}) => {+ const styleSourceSelection = styleSourceSelections.get(instanceId);+ const plan = createStyleSourceSelectionAddPlan({+ styleSourceSelection,+ styleSources,+ instanceId,+ styleSourceId,+ position,+ });+ if (plan.type === "exists") {+ return;+ }+ if (plan.type === "create") {+ styleSourceSelections.set(instanceId, plan.selection);+ return;+ }+ styleSourceSelection?.values.splice(plan.index, 0, styleSourceId);+};++export const removeStyleSourceFromInstanceMutable = ({+ styleSourceSelections,+ instanceId,+ styleSourceId,+}: {+ styleSourceSelections: StyleSourceSelections;+ instanceId: Instance["id"];+ styleSourceId: StyleSource["id"];+}) => {+ const styleSourceSelection = styleSourceSelections.get(instanceId);+ const plan = createStyleSourceSelectionRemovePlan({+ styleSourceSelection,+ styleSourceId,+ });+ if (plan.type === "missing") {+ return;+ }+ styleSourceSelection?.values.splice(plan.index, 1);+};++const createStyleSourceSelectionPayload = (+ patches: BuilderPatch[]+): BuilderPatchChange[] =>+ patches.length === 0+ ? []+ : [+ {+ namespace: "styleSourceSelections" as const,+ patches,+ },+ ];++export const createStyleSourceSelectionAttachPayload = ({+ instanceIds,+ styleSourceSelections,+ styleSources,+ styleSourceId,+ position,+}: {+ instanceIds: Instance["id"][];+ styleSourceSelections: Iterable<StyleSourceSelection>;+ styleSources: Pick<StyleSources, "get">;+ styleSourceId: StyleSource["id"];+ position?: "before-local" | "after-local";+}) => {+ const selectionByInstanceId = new Map(+ Array.from(styleSourceSelections, (selection) => [+ selection.instanceId,+ selection,+ ])+ );+ const patches = instanceIds.flatMap((instanceId) => {+ const patch = createStyleSourceSelectionAddPatch({+ styleSourceSelection: selectionByInstanceId.get(instanceId),+ styleSources,+ instanceId,+ styleSourceId,+ position,+ });+ return patch === undefined ? [] : [patch];+ });+ return createStyleSourceSelectionPayload(patches);+};++export const createStyleSourceSelectionDetachPayload = ({+ instanceIds,+ styleSourceSelections,+ styleSourceId,+}: {+ instanceIds: Instance["id"][];+ styleSourceSelections: Iterable<StyleSourceSelection>;+ styleSourceId: StyleSource["id"];+}) => {+ const selectionByInstanceId = new Map(+ Array.from(styleSourceSelections, (selection) => [+ selection.instanceId,+ selection,+ ])+ );+ const patches = instanceIds.flatMap((instanceId) => {+ const patch = createStyleSourceSelectionRemovePatch({+ styleSourceSelection: selectionByInstanceId.get(instanceId),+ instanceId,+ styleSourceId,+ });+ return patch === undefined ? [] : [patch];+ });+ return createStyleSourceSelectionPayload(patches);+};++type LocalStyleSourcePlan =+ | {+ styleSourceId: StyleSource["id"];+ styleSource?: undefined;+ selection?: undefined;+ selectionValueIndex?: undefined;+ }+ | {+ styleSourceId: StyleSource["id"];+ styleSource: StyleSource;+ selection: StyleSourceSelection;+ selectionValueIndex?: undefined;+ }+ | {+ styleSourceId: StyleSource["id"];+ styleSource: StyleSource;+ selection?: undefined;+ selectionValueIndex: number;+ };++export const createLocalStyleSourcePlan = ({+ styleSourceSelection,+ styleSources,+ instanceId,+ createId = nanoid,+}: {+ styleSourceSelection: StyleSourceSelection | undefined;+ styleSources: Pick<StyleSources, "get">;+ instanceId: Instance["id"];+ createId?: () => StyleSource["id"];+}): LocalStyleSourcePlan => {+ const localStyleSourceId = getLocalStyleSourceId({+ styleSources,+ styleSourceSelection,+ });+ if (localStyleSourceId !== undefined) {+ return { styleSourceId: localStyleSourceId };+ }++ const styleSourceId = createId();+ const styleSource: StyleSource = { type: "local", id: styleSourceId };+ if (styleSourceSelection === undefined) {+ return {+ styleSourceId,+ styleSource,+ selection: { instanceId, values: [styleSourceId] },+ };+ }++ return {+ styleSourceId,+ styleSource,+ selectionValueIndex: styleSourceSelection.values.length,+ };+};++export const getLocalStyleSourceIdWithCreated = ({+ createdLocalSourceIds,+ instanceId,+ styleSources,+ styleSourceSelection,+}: {+ createdLocalSourceIds: Map<Instance["id"], StyleSource["id"]>;+ instanceId: Instance["id"];+ styleSources: Pick<StyleSources, "get">;+ styleSourceSelection: StyleSourceSelection | undefined;+}) => {+ const created = createdLocalSourceIds.get(instanceId);+ if (created !== undefined) {+ return created;+ }+ return getLocalStyleSourceId({ styleSources, styleSourceSelection });+};++export const createLocalStyleSourcePatchPlan = ({+ createdLocalSourceIds,+ instanceId,+ styleSources,+ styleSourceSelection,+ shouldCreate,+ createId = nanoid,+}: {+ createdLocalSourceIds: Map<Instance["id"], StyleSource["id"]>;+ instanceId: Instance["id"];+ styleSources: Pick<StyleSources, "get">;+ styleSourceSelection: StyleSourceSelection | undefined;+ shouldCreate: boolean;+ createId?: () => StyleSource["id"];+}) => {+ const existingStyleSourceId = getLocalStyleSourceIdWithCreated({+ createdLocalSourceIds,+ instanceId,+ styleSources,+ styleSourceSelection,+ });+ if (existingStyleSourceId !== undefined) {+ return { styleSourceId: existingStyleSourceId, payload: [] };+ }+ if (shouldCreate === false) {+ return;+ }+ const plan = createLocalStyleSourcePlan({+ styleSourceSelection,+ styleSources,+ instanceId,+ createId,+ });+ const { styleSourceId } = plan;+ createdLocalSourceIds.set(instanceId, styleSourceId);+ if (plan.styleSource === undefined) {+ return { styleSourceId, payload: [] };+ }+ const selectionPatch =+ plan.selection !== undefined+ ? {+ op: "add" as const,+ path: [instanceId],+ value: plan.selection,+ }+ : {+ op: "add" as const,+ path: [instanceId, "values", plan.selectionValueIndex],+ value: styleSourceId,+ };+ return {+ styleSourceId,+ payload: [+ {+ namespace: "styleSources" as const,+ patches: [+ {+ op: "add" as const,+ path: [styleSourceId],+ value: plan.styleSource,+ },+ ],+ },+ {+ namespace: "styleSourceSelections" as const,+ patches: [selectionPatch],+ },+ ],+ };+};++export const getOrCreateLocalStyleSourceIdMutable = ({+ styleSourceSelections,+ styleSources,+ instanceId,+ createId = nanoid,+}: {+ styleSourceSelections: StyleSourceSelections;+ styleSources: StyleSources;+ instanceId: Instance["id"];+ createId?: () => StyleSource["id"];+}) => {+ const styleSourceSelection = styleSourceSelections.get(instanceId);+ const plan = createLocalStyleSourcePlan({+ styleSources,+ styleSourceSelection,+ instanceId,+ createId,+ });+ if (plan.styleSource !== undefined) {+ styleSources.set(plan.styleSourceId, plan.styleSource);+ }+ if (plan.selection !== undefined) {+ styleSourceSelections.set(instanceId, plan.selection);+ } else if (plan.selectionValueIndex !== undefined) {+ styleSourceSelection?.values.splice(+ plan.selectionValueIndex,+ 0,+ plan.styleSourceId+ );+ }+ return plan.styleSourceId;+};++export const createStyleDecl = ({+ styleSourceId,+ breakpointId,+ property,+ value,+ state,+ listed,+}: {+ styleSourceId: StyleDecl["styleSourceId"];+ breakpointId: StyleDecl["breakpointId"];+ property: unknown;+ value: unknown;+ state?: StyleDecl["state"];+ listed?: StyleDecl["listed"];+}) =>+ styleDeclSchema.parse({+ styleSourceId,+ breakpointId,+ state,+ property: normalizeStyleProperty(property),+ value,+ listed,+ });++export const createStyleDeclFromInput = ({+ styleSourceId,+ property,+ value,+ breakpoint = DEFAULT_BREAKPOINT_ID,+ state,+ listed,+}: {+ styleSourceId: StyleSource["id"];+ property: unknown;+ value: unknown;+ breakpoint?: string;+ state?: StyleDecl["state"];+ listed?: StyleDecl["listed"];+}): StyleDecl =>+ createStyleDecl({+ styleSourceId,+ breakpointId: breakpoint,+ state,+ property,+ value,+ listed,+ });++export const getStyleDeclKeyFromInput = ({+ styleSourceId,+ property,+ breakpoint = DEFAULT_BREAKPOINT_ID,+ state,+}: {+ styleSourceId: StyleSource["id"];+ property: unknown;+ breakpoint?: string;+ state?: StyleDecl["state"];+}) =>+ getStyleDeclKey({+ styleSourceId,+ breakpointId: breakpoint,+ state,+ property: normalizeStyleProperty(property),+ });++export const updateStyleDecl = (+ declaration: StyleDecl,+ values: Partial<Omit<StyleDecl, "property" | "value">> & {+ property?: unknown;+ value?: unknown;+ }+) =>+ styleDeclSchema.parse({+ ...declaration,+ ...values,+ property:+ values.property === undefined+ ? declaration.property+ : normalizeStyleProperty(values.property),+ });++export const setStyleDeclMutable = ({+ styles,+ styleSourceId,+ breakpointId,+ property,+ value,+ state,+ listed,+}: {+ styles: Styles;+ styleSourceId: StyleDecl["styleSourceId"];+ breakpointId: StyleDecl["breakpointId"];+ property: unknown;+ value: unknown;+ state?: StyleDecl["state"];+ listed?: StyleDecl["listed"];+}) => {+ const styleDecl = createStyleDecl({+ styleSourceId,+ breakpointId,+ property,+ value,+ state,+ listed,+ });+ const styleKey = getStyleDeclKey(styleDecl);+ styles.set(styleKey, styleDecl);+ return { styleDecl, styleKey };+};++export const deleteStyleDeclMutable = ({+ styles,+ styleSourceId,+ breakpointId,+ property,+ state,+}: {+ styles: Styles;+ styleSourceId: StyleDecl["styleSourceId"];+ breakpointId: StyleDecl["breakpointId"];+ property: unknown;+ state?: StyleDecl["state"];+}) => {+ const styleKey = getStyleDeclKey({+ styleSourceId,+ breakpointId,+ state,+ property: normalizeStyleProperty(property),+ });+ return styles.delete(styleKey);+};++export const deleteStyleSourceMutable = ({+ styleSourceId,+ styleSources,+ styleSourceSelections,+ styles,+}: {+ styleSourceId: StyleSource["id"];+ styleSources: StyleSources;+ styleSourceSelections: StyleSourceSelections;+ styles: Styles;+}): void => {+ styleSources.delete(styleSourceId);+ for (const styleSourceSelection of styleSourceSelections.values()) {+ const index = styleSourceSelection.values.indexOf(styleSourceId);+ if (index !== -1) {+ styleSourceSelection.values.splice(index, 1);+ }+ }+ for (const [styleDeclKey, styleDecl] of styles) {+ if (styleDecl.styleSourceId === styleSourceId) {+ styles.delete(styleDeclKey);+ }+ }+};++export const findUnusedTokens = ({+ styleSources,+ styleSourceUsages,+}: {+ styleSources: StyleSources;+ styleSourceUsages: Map<StyleSource["id"], Set<Instance["id"]>>;+}): StyleSource["id"][] => {+ const unusedTokenIds: StyleSource["id"][] = [];+ for (const styleSource of styleSources.values()) {+ if (styleSource.type === "token") {+ const usages = styleSourceUsages.get(styleSource.id);+ if (usages === undefined || usages.size === 0) {+ unusedTokenIds.push(styleSource.id);+ }+ }+ }+ return unusedTokenIds;+};++export const deleteStyleSourcesMutable = ({+ styleSourceIds,+ styleSources,+ styleSourceSelections,+ styles,+}: {+ styleSourceIds: StyleSource["id"][];+ styleSources: StyleSources;+ styleSourceSelections: StyleSourceSelections;+ styles: Styles;+}): void => {+ for (const styleSourceId of styleSourceIds) {+ deleteStyleSourceMutable({+ styleSourceId,+ styleSources,+ styleSourceSelections,+ styles,+ });+ }+};++export const validateAndRenameStyleSource = ({+ id,+ name,+ styleSources,+}: {+ id: StyleSource["id"];+ name: string;+ styleSources: StyleSources;+}): RenameStyleSourceError | undefined => {+ const error = validateStyleSourceName({ id, name, styleSources });+ if (error !== undefined) {+ return error;+ }+};++export const renameStyleSourceMutable = ({+ id,+ name,+ styleSources,+}: {+ id: StyleSource["id"];+ name: string;+ styleSources: StyleSources;+}): void => {+ const styleSource = styleSources.get(id);+ if (styleSource?.type === "token") {+ styleSource.name = name;+ }+};++export const toggleStyleSourceLockMutable = ({+ id,+ locked,+ styleSources,+}: {+ id: StyleSource["id"];+ locked: boolean;+ styleSources: StyleSources;+}): void => {+ const styleSource = styleSources.get(id);+ if (styleSource?.type !== "token") {+ return;+ }+ if (locked) {+ styleSource.locked = true;+ return;+ }+ delete styleSource.locked;+};++export const deleteLocalStyleSourcesMutable = ({+ localStyleSourceIds,+ styleSources,+ styles,+}: {+ localStyleSourceIds: Set<StyleSource["id"]>;+ styleSources: StyleSources;+ styles: Styles;+}): void => {+ for (const styleSourceId of localStyleSourceIds) {+ styleSources.delete(styleSourceId);+ }+ for (const [styleDeclKey, styleDecl] of styles) {+ if (localStyleSourceIds.has(styleDecl.styleSourceId)) {+ styles.delete(styleDeclKey);+ }+ }+};++export const findDuplicateTokens = ({+ styleSources,+ styles,+ breakpoints,+}: {+ styleSources: StyleSources;+ styles: Styles;+ breakpoints: Map<Breakpoint["id"], Breakpoint>;+}): Map<StyleSource["id"], StyleSource["id"][]> => {+ const duplicatesMap = new Map<StyleSource["id"], StyleSource["id"][]>();+ const stylesArray = Array.from(styles.values());+ const tokens = Array.from(styleSources.values()).filter(+ (source): source is Extract<StyleSource, { type: "token" }> =>+ source.type === "token"+ );+ const signatureToTokenIds = new Map<string, StyleSource["id"][]>();+ const nameToTokenIds = new Map<string, StyleSource["id"][]>();++ for (const token of tokens) {+ const signature = getStyleSourceStylesSignature(+ token.id,+ stylesArray,+ breakpoints,+ new Map()+ );+ const tokensWithSignature = signatureToTokenIds.get(signature) ?? [];+ tokensWithSignature.push(token.id);+ signatureToTokenIds.set(signature, tokensWithSignature);++ const tokensWithName = nameToTokenIds.get(token.name) ?? [];+ tokensWithName.push(token.id);+ nameToTokenIds.set(token.name, tokensWithName);+ }++ const addDuplicates = (tokenIds: StyleSource["id"][]) => {+ if (tokenIds.length <= 1) {+ return;+ }+ for (const tokenId of tokenIds) {+ const duplicates = duplicatesMap.get(tokenId) ?? [];+ for (const duplicate of tokenIds) {+ if (duplicate !== tokenId && duplicates.includes(duplicate) === false) {+ duplicates.push(duplicate);+ }+ }+ duplicatesMap.set(tokenId, duplicates);+ }+ };++ for (const tokenIds of signatureToTokenIds.values()) {+ addDuplicates(tokenIds);+ }+ for (const tokenIds of nameToTokenIds.values()) {+ addDuplicates(tokenIds);+ }++ return duplicatesMap;+};++const createStyleRemovePayload = (styleKeys: string[]) =>+ styleKeys.length === 0+ ? []+ : [+ {+ namespace: "styles" as const,+ patches: styleKeys.map((key) => ({+ op: "remove" as const,+ path: [key],+ })),+ },+ ];++export const createDesignTokenCreatePayload = ({+ tokens,+ styleSources,+ createId,+}: {+ tokens: Array<z.infer<typeof designTokenCreateInput>>;+ styleSources: StyleSources;+ createId: () => StyleSource["id"];+}) => {+ const styleSourcePatches = [];+ const stylePatches = [];+ const tokenIds = [];+ const errors: Array<+ | { type: "duplicate-id"; tokenId: StyleSource["id"] }+ | {+ type: "invalid-name";+ tokenId: StyleSource["id"];+ error: ReturnType<typeof validateStyleSourceName>;+ }+ > = [];++ for (const token of tokens) {+ const tokenId = token.tokenId ?? createId();+ if (styleSources.has(tokenId)) {+ errors.push({ type: "duplicate-id", tokenId });+ continue;+ }+ const nameError = validateStyleSourceName({+ id: tokenId,+ name: token.name,+ styleSources,+ });+ if (nameError !== undefined) {+ errors.push({ type: "invalid-name", tokenId, error: nameError });+ continue;+ }+ tokenIds.push(tokenId);+ const styleSource = createTokenStyleSource({+ id: tokenId,+ name: token.name,+ });+ styleSources.set(tokenId, styleSource);+ styleSourcePatches.push({+ op: "add" as const,+ path: [tokenId],+ value: styleSource,+ });+ for (const declaration of createDesignTokenStyleInputs(token)) {+ const style = createStyleDeclFromInput({+ styleSourceId: tokenId,+ breakpoint: declaration.breakpoint,+ property: declaration.property,+ value: declaration.value,+ state: declaration.state,+ });+ stylePatches.push({+ op: "add" as const,+ path: [getStyleDeclKey(style)],+ value: style,+ });+ }+ }++ return {+ payload: [+ ...(styleSourcePatches.length === 0+ ? []+ : [+ {+ namespace: "styleSources" as const,+ patches: styleSourcePatches,+ },+ ]),+ ...(stylePatches.length === 0+ ? []+ : [{ namespace: "styles" as const, patches: stylePatches }]),+ ],+ tokenIds,+ errors,+ };+};++export const createDesignTokenStyleUpdatePayload = ({+ designTokenId,+ updates,+ styles,+}: {+ designTokenId: StyleSource["id"];+ updates: Array<z.infer<typeof designTokenStyleInput>>;+ styles: Iterable<StyleDecl>;+}) => {+ const styleKeys = new Set(+ Array.from(styles, (styleDecl) => getStyleDeclKey(styleDecl))+ );+ const patches = updates.map((update) => {+ const style = createStyleDeclFromInput({+ styleSourceId: designTokenId,+ breakpoint: update.breakpoint,+ property: update.property,+ value: update.value,+ state: update.state,+ });+ const key = getStyleDeclKey(style);+ const patch = {+ op: styleKeys.has(key) ? ("replace" as const) : ("add" as const),+ path: [key],+ value: style,+ };+ styleKeys.add(key);+ return patch;+ });++ return {+ payload:+ patches.length === 0 ? [] : [{ namespace: "styles" as const, patches }],+ styleKeys: patches.map((patch) => String(patch.path[0])),+ };+};++export const createDesignTokenStyleDeletePayload = ({+ designTokenId,+ deletions,+ styles,+}: {+ designTokenId: StyleSource["id"];+ deletions: Array<Omit<z.infer<typeof styleDeleteInput>, "instanceId">>;+ styles: Iterable<StyleDecl>;+}) => {+ const existingStyleKeys = new Set(+ Array.from(styles, (styleDecl) => getStyleDeclKey(styleDecl))+ );+ const styleKeys = deletions.flatMap((deletion) => {+ const key = getStyleDeclKeyFromInput({+ styleSourceId: designTokenId,+ breakpoint: deletion.breakpoint,+ state: deletion.state,+ property: deletion.property,+ });+ return existingStyleKeys.has(key) ? [key] : [];+ });++ return {+ payload: createStyleRemovePayload(styleKeys),+ styleKeys,+ };+};++export const createDesignTokenExtractionPayload = ({+ tokenId,+ tokenName,+ instanceIds,+ styleSources,+ styleSourceSelections,+ styles,+ removeLocalProps,+}: {+ tokenId: StyleSource["id"];+ tokenName: string;+ instanceIds: Instance["id"][];+ styleSources: Pick<StyleSources, "get">;+ styleSourceSelections: Iterable<StyleSourceSelection>;+ styles: Iterable<StyleDecl>;+ removeLocalProps?: string[];+}) => {+ const selectionByInstanceId = new Map(+ Array.from(styleSourceSelections, (selection) => [+ selection.instanceId,+ selection,+ ])+ );+ const selectedLocalSourceIds = new Set<StyleSource["id"]>();+ for (const instanceId of instanceIds) {+ const styleSourceId = getLocalStyleSourceIdWithCreated({+ createdLocalSourceIds: new Map(),+ instanceId,+ styleSources,+ styleSourceSelection: selectionByInstanceId.get(instanceId),+ });+ if (styleSourceId !== undefined) {+ selectedLocalSourceIds.add(styleSourceId);+ }+ }+ const properties =+ removeLocalProps === undefined ? undefined : new Set(removeLocalProps);+ const tokenStylePatches = [];+ const localStyleRemovePatches = [];+ const coveredKeys = new Set<string>();+ for (const declaration of styles) {+ if (+ selectedLocalSourceIds.has(declaration.styleSourceId) === false ||+ (properties !== undefined &&+ properties.has(declaration.property) === false)+ ) {+ continue;+ }+ const tokenDeclaration = updateStyleDecl(declaration, {+ styleSourceId: tokenId,+ });+ const tokenKey = getStyleDeclKey(tokenDeclaration);+ if (coveredKeys.has(tokenKey) === false) {+ coveredKeys.add(tokenKey);+ tokenStylePatches.push({+ op: "add" as const,+ path: [tokenKey],+ value: tokenDeclaration,+ });+ }+ if (properties !== undefined) {+ localStyleRemovePatches.push({+ op: "remove" as const,+ path: [getStyleDeclKey(declaration)],+ });+ }+ }+ const selectionPatches = instanceIds.flatMap((instanceId) => {+ const patch = createStyleSourceSelectionAddPatch({+ styleSourceSelection: selectionByInstanceId.get(instanceId),+ styleSources,+ instanceId,+ styleSourceId: tokenId,+ });+ return patch === undefined ? [] : [patch];+ });++ return {+ payload: [+ {+ namespace: "styleSources" as const,+ patches: [+ {+ op: "add" as const,+ path: [tokenId],+ value: createTokenStyleSource({ id: tokenId, name: tokenName }),+ },+ ],+ },+ ...(tokenStylePatches.length === 0 && localStyleRemovePatches.length === 0+ ? []+ : [+ {+ namespace: "styles" as const,+ patches: [...tokenStylePatches, ...localStyleRemovePatches],+ },+ ]),+ ...(selectionPatches.length === 0+ ? []+ : [+ {+ namespace: "styleSourceSelections" as const,+ patches: selectionPatches,+ },+ ]),+ ],+ styleKeys: tokenStylePatches.map((patch) => String(patch.path[0])),+ };+};++export const createStyleDeclarationUpdatePayload = ({+ updates,+ styleSources,+ styleSourceSelections,+ styles,+ createdLocalSourceIds = new Map(),+ createId,+}: {+ updates: Array<z.infer<typeof styleUpdateInput>>;+ styleSources: Pick<StyleSources, "get">;+ styleSourceSelections: Iterable<StyleSourceSelection>;+ styles: Iterable<StyleDecl>;+ createdLocalSourceIds?: Map<Instance["id"], StyleSource["id"]>;+ createId: () => StyleSource["id"];+}) => {+ const payload = [];+ const stylePatches = [];+ const styleKeys = new Set(+ Array.from(styles, (styleDecl) => getStyleDeclKey(styleDecl))+ );+ const styleSourceSelectionByInstanceId = new Map(+ Array.from(styleSourceSelections, (selection) => [+ selection.instanceId,+ selection,+ ])+ );+ const missingLocalStyleSourceInstanceIds = [];++ for (const update of updates) {+ const result = createLocalStyleSourcePatchPlan({+ createdLocalSourceIds,+ instanceId: update.instanceId,+ styleSources,+ styleSourceSelection: styleSourceSelectionByInstanceId.get(+ update.instanceId+ ),+ shouldCreate: update.createLocalIfMissing ?? true,+ createId,+ });+ if (result === undefined) {+ missingLocalStyleSourceInstanceIds.push(update.instanceId);+ continue;+ }+ payload.push(...result.payload);+ const nextStyleDecl = createStyleDeclFromInput({+ styleSourceId: result.styleSourceId,+ breakpoint: update.breakpoint,+ property: update.property,+ value: update.value,+ state: update.state,+ listed: update.listed,+ });+ const key = getStyleDeclKey(nextStyleDecl);+ stylePatches.push({+ op: styleKeys.has(key) ? ("replace" as const) : ("add" as const),+ path: [key],+ value: nextStyleDecl,+ });+ styleKeys.add(key);+ }++ if (stylePatches.length > 0) {+ payload.push({ namespace: "styles" as const, patches: stylePatches });+ }++ return {+ payload,+ styleKeys: stylePatches.map((patch) => String(patch.path[0])),+ missingLocalStyleSourceInstanceIds,+ };+};++export const createStyleDeclarationDeletePayload = ({+ deletions,+ styleSources,+ styleSourceSelections,+ styles,+}: {+ deletions: Array<z.infer<typeof styleDeleteInput>>;+ styleSources: Pick<StyleSources, "get">;+ styleSourceSelections: Iterable<StyleSourceSelection>;+ styles: Iterable<StyleDecl>;+}) => {+ const styleKeys = new Set<string>();+ const styleSourceSelectionByInstanceId = new Map(+ Array.from(styleSourceSelections, (selection) => [+ selection.instanceId,+ selection,+ ])+ );+ const existingStyleKeys = new Set(+ Array.from(styles, (styleDecl) => getStyleDeclKey(styleDecl))+ );++ for (const deletion of deletions) {+ const styleSourceId = getLocalStyleSourceIdWithCreated({+ createdLocalSourceIds: new Map(),+ instanceId: deletion.instanceId,+ styleSources,+ styleSourceSelection: styleSourceSelectionByInstanceId.get(+ deletion.instanceId+ ),+ });+ if (styleSourceId === undefined) {+ continue;+ }+ const key = getStyleDeclKeyFromInput({+ styleSourceId,+ breakpoint: deletion.breakpoint,+ state: deletion.state,+ property: deletion.property,+ });+ if (existingStyleKeys.has(key)) {+ styleKeys.add(key);+ }+ }++ const removedStyleKeys = Array.from(styleKeys);+ return {+ payload: createStyleRemovePayload(removedStyleKeys),+ styleKeys: removedStyleKeys,+ };+};++export const createSelectedStyleDeclarationUpdatePayload = ({+ updates,+ styleSources,+ styleSourceSelections,+ styles,+}: {+ updates: Array<+ Omit<z.infer<typeof styleUpdateInput>, "createLocalIfMissing"> & {+ styleSource: StyleSource;+ styleSourceId: StyleSource["id"];+ }+ >;+ styleSources: Pick<StyleSources, "get">;+ styleSourceSelections: Iterable<StyleSourceSelection>;+ styles: Iterable<StyleDecl>;+}) => {+ const payload: BuilderPatchChange[] = [];+ const styleSourcePatches: BuilderPatchChange["patches"] = [];+ const styleSelectionPatches: BuilderPatchChange["patches"] = [];+ const stylePatches: BuilderPatchChange["patches"] = [];+ const existingStyleKeys = new Set(+ Array.from(styles, (styleDecl) => getStyleDeclKey(styleDecl))+ );+ const nextStyleSourceIds = new Set<string>();+ const styleSourceSelectionByInstanceId = new Map(+ Array.from(styleSourceSelections, (selection) => [+ selection.instanceId,+ selection,+ ])+ );+ const nextSelectionValuesByInstanceId = new Map(+ Array.from(styleSourceSelectionByInstanceId, ([instanceId, selection]) => [+ instanceId,+ [...selection.values],+ ])+ );++ for (const update of updates) {+ if (nextStyleSourceIds.has(update.styleSource.id) === false) {+ const styleSourceExists =+ styleSources.get(update.styleSource.id) !== undefined;+ styleSourcePatches.push({+ op: styleSourceExists ? ("replace" as const) : ("add" as const),+ path: [update.styleSource.id],+ value: update.styleSource,+ });+ nextStyleSourceIds.add(update.styleSource.id);+ }++ const selection = styleSourceSelectionByInstanceId.get(update.instanceId);+ const hasPendingSelection =+ selection === undefined &&+ nextSelectionValuesByInstanceId.has(update.instanceId);+ const selectionValues =+ nextSelectionValuesByInstanceId.get(update.instanceId) ?? [];+ if (selectionValues.includes(update.styleSourceId) === false) {+ styleSelectionPatches.push(+ selection === undefined && hasPendingSelection === false+ ? {+ op: "add" as const,+ path: [update.instanceId],+ value: {+ instanceId: update.instanceId,+ values: [update.styleSourceId],+ },+ }+ : {+ op: "add" as const,+ path: [update.instanceId, "values", selectionValues.length],+ value: update.styleSourceId,+ }+ );+ nextSelectionValuesByInstanceId.set(update.instanceId, [+ ...selectionValues,+ update.styleSourceId,+ ]);+ }++ const styleDecl = createStyleDeclFromInput({+ styleSourceId: update.styleSourceId,+ breakpoint: update.breakpoint,+ property: update.property,+ value: update.value,+ state: update.state,+ listed: update.listed,+ });+ const styleKey = getStyleDeclKey(styleDecl);+ stylePatches.push({+ op: existingStyleKeys.has(styleKey)+ ? ("replace" as const)+ : ("add" as const),+ path: [styleKey],+ value: styleDecl,+ });+ existingStyleKeys.add(styleKey);+ }++ if (styleSourcePatches.length > 0) {+ payload.push({+ namespace: "styleSources" as const,+ patches: styleSourcePatches,+ });+ }+ if (styleSelectionPatches.length > 0) {+ payload.push({+ namespace: "styleSourceSelections" as const,+ patches: styleSelectionPatches,+ });+ }+ if (stylePatches.length > 0) {+ payload.push({ namespace: "styles" as const, patches: stylePatches });+ }++ return {+ payload,+ styleKeys: stylePatches.map((patch) => String(patch.path[0])),+ };+};++export const createSelectedStyleDeclarationDeletePayload = ({+ deletions,+ styles,+}: {+ deletions: Array<+ Omit<z.infer<typeof styleDeleteInput>, "instanceId"> & {+ styleSourceId: StyleSource["id"];+ }+ >;+ styles: Iterable<StyleDecl>;+}) => {+ const existingStyleKeys = new Set(+ Array.from(styles, (styleDecl) => getStyleDeclKey(styleDecl))+ );+ const styleKeys = deletions.flatMap((deletion) => {+ const styleKey = getStyleDeclKeyFromInput({+ styleSourceId: deletion.styleSourceId,+ breakpoint: deletion.breakpoint,+ state: deletion.state,+ property: deletion.property,+ });+ return existingStyleKeys.has(styleKey) ? [styleKey] : [];+ });+ return {+ payload: createStyleRemovePayload(styleKeys),+ styleKeys,+ };+};++export const createStyleValueReplacementPayload = ({+ styles,+ styleSources,+ styleSourceSelections,+ instanceIds,+ property,+ fromValue,+ toValue,+}: {+ styles: Iterable<StyleDecl>;+ styleSources: Iterable<StyleSource>;+ styleSourceSelections: Iterable<StyleSourceSelection>;+ instanceIds?: Set<Instance["id"]>;+ property: string;+ fromValue: unknown;+ toValue: unknown;+}) => {+ const normalizedProperty = normalizeStyleProperty(property);+ const styleSourceById = new Map(+ Array.from(styleSources, (styleSource) => [styleSource.id, styleSource])+ );+ const selectedLocalSources = new Set(+ Array.from(styleSourceSelections)+ .filter(+ (selection) =>+ instanceIds === undefined || instanceIds.has(selection.instanceId)+ )+ .flatMap((selection) => selection.values)+ .filter(+ (styleSourceId) => styleSourceById.get(styleSourceId)?.type === "local"+ )+ );+ const patches = Array.from(styles).flatMap((declaration) => {+ if (+ declaration.property !== normalizedProperty ||+ selectedLocalSources.has(declaration.styleSourceId) === false ||+ deepEqual(declaration.value, fromValue) === false+ ) {+ return [];+ }+ const nextStyleDecl = updateStyleDecl(declaration, { value: toValue });+ return [+ {+ op: "replace" as const,+ path: [getStyleDeclKey(declaration)],+ value: nextStyleDecl,+ },+ ];+ });++ return {+ payload:+ patches.length === 0 ? [] : [{ namespace: "styles" as const, patches }],+ styleKeys: patches.map((patch) => String(patch.path[0])),+ };+};++const getRequiredStyleMutationState = (+ state: Pick<+ BuilderState,+ "instances" | "styles" | "styleSources" | "styleSourceSelections"+ >+) => {+ const styleState = getRequiredStyleState(state);+ if (state.instances === undefined) {+ return throwBuilderRuntimeError(+ "BAD_REQUEST",+ "Instances namespace is missing"+ );+ }+ return { ...styleState, instances: state.instances };+};++const assertStyleInstances = (+ instances: Map<Instance["id"], Instance>,+ instanceIds: Iterable<Instance["id"]>+) => {+ for (const instanceId of instanceIds) {+ if (instances.has(instanceId) === false) {+ return throwBuilderRuntimeError("NOT_FOUND", "Instance not found");+ }+ }+};++export const updateStyleDeclarations = (+ state: Pick<+ BuilderState,+ | "breakpoints"+ | "instances"+ | "styles"+ | "styleSources"+ | "styleSourceSelections"+ >,+ input: { updates: Array<z.infer<typeof styleUpdateInput>> },+ context: { createId: () => string }+) => {+ const styleState = getRequiredStyleMutationState(state);+ assertStyleInstances(+ styleState.instances,+ input.updates.map((update) => update.instanceId)+ );+ const { payload, styleKeys, missingLocalStyleSourceInstanceIds } =+ createStyleDeclarationUpdatePayload({+ updates: input.updates.map((update) =>+ withDefaultBreakpoint(update, getBaseBreakpointId(state.breakpoints))+ ),+ styleSources: styleState.styleSources,+ styleSourceSelections: styleState.styleSourceSelections.values(),+ styles: styleState.styles.values(),+ createId: context.createId,+ });+ if (missingLocalStyleSourceInstanceIds.length > 0) {+ return throwBuilderRuntimeError(+ "NOT_FOUND",+ "Local style source not found for instance"+ );+ }+ return createRuntimeMutation({+ payload,+ result: { styleKeys },+ invalidatesNamespaces: ["styles", "styleSources", "styleSourceSelections"],+ });+};++export const deleteStyleDeclarations = (+ state: Pick<+ BuilderState,+ | "breakpoints"+ | "instances"+ | "styles"+ | "styleSources"+ | "styleSourceSelections"+ >,+ input: { deletions: Array<z.infer<typeof styleDeleteInput>> }+) => {+ const styleState = getRequiredStyleMutationState(state);+ assertStyleInstances(+ styleState.instances,+ input.deletions.map((deletion) => deletion.instanceId)+ );+ const { payload, styleKeys } = createStyleDeclarationDeletePayload({+ deletions: input.deletions.map((deletion) =>+ withDefaultBreakpoint(deletion, getBaseBreakpointId(state.breakpoints))+ ),+ styleSources: styleState.styleSources,+ styleSourceSelections: styleState.styleSourceSelections.values(),+ styles: styleState.styles.values(),+ });+ return createRuntimeMutation({+ payload,+ result: { styleKeys },+ invalidatesNamespaces: ["styles"],+ });+};++export const replaceStyleValues = (+ state: Pick<+ BuilderState,+ "pages" | "instances" | "styles" | "styleSources" | "styleSourceSelections"+ >,+ input: z.infer<typeof styleReplaceInput>+) => {+ const styleState = getRequiredStyleMutationState(state);+ const hasPageFilter =+ input.pageId !== undefined || input.pagePath !== undefined;+ const pages = hasPageFilter ? getSerializedPages(state) : undefined;+ const page =+ pages === undefined ? undefined : findSerializedPageByInput(pages, input);+ if (hasPageFilter && page === undefined) {+ return throwBuilderRuntimeError("NOT_FOUND", "Page not found");+ }+ const pageInstanceIds =+ page === undefined+ ? undefined+ : new Set(+ getInstanceDepths(styleState.instances, [page.rootInstanceId]).keys()+ );+ const { payload, styleKeys } = createStyleValueReplacementPayload({+ styles: styleState.styles.values(),+ styleSources: styleState.styleSources.values(),+ styleSourceSelections: styleState.styleSourceSelections.values(),+ instanceIds: pageInstanceIds,+ property: input.property,+ fromValue: input.fromValue,+ toValue: input.toValue,+ });+ return createRuntimeMutation({+ payload,+ result: { styleKeys },+ invalidatesNamespaces: ["styles"],+ });+};++const compileOptionalRegex = (pattern: string | undefined) => {+ if (pattern === undefined) {+ return;+ }+ try {+ return new RegExp(pattern);+ } catch {+ return throwBuilderRuntimeError("BAD_REQUEST", "Invalid scope regex");+ }+};++const assertCssVariableName = (name: string) => {+ const error = validateCssVariableNameWithStyles({ name, styles: [] });+ if (error !== undefined) {+ return throwBuilderRuntimeError("BAD_REQUEST", error.message);+ }+};++export const listCssVariables = (+ state: Pick<+ BuilderState,+ "styles" | "props" | "styleSources" | "styleSourceSelections"+ >,+ input: {+ filter?: string;+ withUsage?: boolean;+ } = {}+) => {+ if (state.props === undefined) {+ return throwBuilderRuntimeError(+ "BAD_REQUEST",+ "Props namespace is missing"+ );+ }+ const styleState = getRequiredStyleState(state);+ return serializeCssVariables({+ styles: styleState.styles.values(),+ props: state.props.values(),+ styleSourceSelections: styleState.styleSourceSelections.values(),+ filter: input.filter,+ withUsage: input.withUsage,+ });+};++export const defineCssVariables = (+ state: Pick<+ BuilderState,+ | "breakpoints"+ | "pages"+ | "styles"+ | "styleSources"+ | "styleSourceSelections"+ >,+ input: {+ vars: Record<string, string | StyleValue>;+ overwrite?: boolean;+ },+ context: { createId: () => string }+) => {+ const rootInstanceId =+ state.pages === undefined+ ? undefined+ : getHomePageRootInstanceId(state.pages);+ if (rootInstanceId === undefined) {+ return throwBuilderRuntimeError("NOT_FOUND", "Home page not found");+ }+ for (const [property] of Object.entries(input.vars)) {+ assertCssVariableName(property);+ }+ const styleState = getRequiredStyleState(state);+ const resultPayload = createCssVariableRootDefinePayload({+ rootInstanceId,+ vars: input.vars,+ styleSources: styleState.styleSources,+ styleSourceSelections: styleState.styleSourceSelections.values(),+ styles: styleState.styles.values(),+ overwrite: input.overwrite,+ breakpointId: getBaseBreakpointId(state.breakpoints),+ createId: context.createId,+ });+ if (resultPayload.missingRootStyleSource) {+ return throwBuilderRuntimeError(+ "NOT_FOUND",+ "Local style source not found for instance"+ );+ }+ const conflict = resultPayload.conflicts.at(0);+ if (conflict !== undefined) {+ return throwBuilderRuntimeError(+ "CONFLICT",+ `CSS variable "${conflict}" already exists`+ );+ }+ return createRuntimeMutation({+ payload: resultPayload.payload,+ result: { names: Object.keys(input.vars) },+ invalidatesNamespaces: ["styles", "styleSources", "styleSourceSelections"],+ });+};++export const deleteCssVariables = (+ state: Pick<+ BuilderState,+ "styles" | "props" | "styleSources" | "styleSourceSelections"+ >,+ input: { names: string[]; force?: boolean }+) => {+ for (const name of input.names) {+ assertCssVariableName(name);+ }+ if (state.props === undefined) {+ return throwBuilderRuntimeError(+ "BAD_REQUEST",+ "Props namespace is missing"+ );+ }+ const styleState = getRequiredStyleState(state);+ const { payload, styleKeys, referenced } = createCssVariableDeletePayload({+ names: input.names,+ styles: styleState.styles.values(),+ props: state.props.values(),+ force: input.force,+ });+ if (referenced.length > 0) {+ return throwBuilderRuntimeError(+ "BAD_REQUEST",+ `CSS variables are still referenced: ${referenced.join(", ")}`+ );+ }+ return createRuntimeMutation({+ payload,+ result: { names: input.names, styleKeys },+ invalidatesNamespaces: ["styles"],+ });+};++export const rewriteCssVariableRefs = (+ state: Pick<+ BuilderState,+ "styles" | "props" | "styleSources" | "styleSourceSelections"+ >,+ input: { map: Record<string, string>; scopeRegex?: string }+) => {+ for (const [fromName, toName] of Object.entries(input.map)) {+ assertCssVariableName(fromName);+ assertCssVariableName(toName);+ }+ if (state.props === undefined) {+ return throwBuilderRuntimeError(+ "BAD_REQUEST",+ "Props namespace is missing"+ );+ }+ const styleState = getRequiredStyleState(state);+ const { payload, styleKeys, propIds } =+ createCssVariableReferenceRewritePayload({+ replacements: input.map,+ scopeRegex: compileOptionalRegex(input.scopeRegex),+ styles: styleState.styles.values(),+ props: state.props.values(),+ styleSourceSelections: styleState.styleSourceSelections.values(),+ });+ return createRuntimeMutation({+ payload,+ result: { styleKeys, propIds },+ invalidatesNamespaces: ["styles", "props"],+ });+};++const getDesignTokenOrThrow = (+ styleSources: Iterable<StyleSource>,+ tokenId: StyleSource["id"]+) => {+ const token = findDesignToken(styleSources, tokenId);+ if (token === undefined) {+ return throwBuilderRuntimeError("NOT_FOUND", "Design token not found");+ }+ return token;+};++export const createDesignTokens = (+ state: Pick<+ BuilderState,+ "breakpoints" | "styles" | "styleSources" | "styleSourceSelections"+ >,+ input: { tokens: Array<z.infer<typeof designTokenCreateInput>> },+ context: { createId: () => string }+) => {+ const styleState = getRequiredStyleState(state);+ const { payload, tokenIds, errors } = createDesignTokenCreatePayload({+ tokens: input.tokens.map((token) => ({+ ...token,+ styles: undefined,+ declarations: createDesignTokenStyleInputs(token).map((declaration) =>+ withDefaultBreakpoint(+ declaration,+ getBaseBreakpointId(state.breakpoints)+ )+ ),+ })),+ styleSources: new Map(styleState.styleSources),+ createId: context.createId,+ });+ const error = errors.at(0);+ if (error?.type === "duplicate-id") {+ return throwBuilderRuntimeError(+ "CONFLICT",+ "Design token id already exists"+ );+ }+ if (error?.type === "invalid-name") {+ return throwBuilderRuntimeError(+ "CONFLICT",+ error.error?.type === "minlength"+ ? "Design token name is required"+ : "Design token name already exists"+ );+ }+ return createRuntimeMutation({+ payload,+ result: { tokenIds },+ invalidatesNamespaces: ["styleSources", "styles"],+ });+};++export const updateDesignTokenStyles = (+ state: Pick<+ BuilderState,+ "breakpoints" | "styles" | "styleSources" | "styleSourceSelections"+ >,+ input: {+ designTokenId: string;+ updates: Array<z.infer<typeof designTokenStyleInput>>;+ }+) => {+ const styleState = getRequiredStyleState(state);+ getDesignTokenOrThrow(styleState.styleSources.values(), input.designTokenId);+ const { payload, styleKeys } = createDesignTokenStyleUpdatePayload({+ designTokenId: input.designTokenId,+ updates: input.updates.map((update) =>+ withDefaultBreakpoint(update, getBaseBreakpointId(state.breakpoints))+ ),+ styles: styleState.styles.values(),+ });+ return createRuntimeMutation({+ payload,+ result: { designTokenId: input.designTokenId, styleKeys },+ invalidatesNamespaces: ["styles"],+ });+};++export const deleteDesignTokenStyles = (+ state: Pick<+ BuilderState,+ "breakpoints" | "styles" | "styleSources" | "styleSourceSelections"+ >,+ input: {+ designTokenId: string;+ deletions: Array<Omit<z.infer<typeof styleDeleteInput>, "instanceId">>;+ }+) => {+ const styleState = getRequiredStyleState(state);+ getDesignTokenOrThrow(styleState.styleSources.values(), input.designTokenId);+ const { payload, styleKeys } = createDesignTokenStyleDeletePayload({+ designTokenId: input.designTokenId,+ deletions: input.deletions.map((deletion) =>+ withDefaultBreakpoint(deletion, getBaseBreakpointId(state.breakpoints))+ ),+ styles: styleState.styles.values(),+ });+ return createRuntimeMutation({+ payload,+ result: { designTokenId: input.designTokenId, styleKeys },+ invalidatesNamespaces: ["styles"],+ });+};++export const attachDesignToken = (+ state: Pick<+ BuilderState,+ "instances" | "styles" | "styleSources" | "styleSourceSelections"+ >,+ input: {+ designTokenId: string;+ instanceIds: string[];+ position?: "before-local" | "after-local";+ }+) => {+ const styleState = getRequiredStyleMutationState(state);+ getDesignTokenOrThrow(styleState.styleSources.values(), input.designTokenId);+ assertStyleInstances(styleState.instances, input.instanceIds);+ const payload = createStyleSourceSelectionAttachPayload({+ instanceIds: input.instanceIds,+ styleSourceSelections: styleState.styleSourceSelections.values(),+ styleSources: styleState.styleSources,+ styleSourceId: input.designTokenId,+ position: input.position,+ });+ return createRuntimeMutation({+ payload,+ result: { designTokenId: input.designTokenId },+ invalidatesNamespaces: ["styleSourceSelections"],+ });+};++export const detachDesignToken = (+ state: Pick<+ BuilderState,+ "instances" | "styles" | "styleSources" | "styleSourceSelections"+ >,+ input: { designTokenId: string; instanceIds: string[] }+) => {+ const styleState = getRequiredStyleMutationState(state);+ getDesignTokenOrThrow(styleState.styleSources.values(), input.designTokenId);+ assertStyleInstances(styleState.instances, input.instanceIds);+ const payload = createStyleSourceSelectionDetachPayload({+ instanceIds: input.instanceIds,+ styleSourceSelections: styleState.styleSourceSelections.values(),+ styleSourceId: input.designTokenId,+ });+ return createRuntimeMutation({+ payload,+ result: { designTokenId: input.designTokenId },+ invalidatesNamespaces: ["styleSourceSelections"],+ });+};++export const extractDesignToken = (+ state: Pick<+ BuilderState,+ "instances" | "styles" | "styleSources" | "styleSourceSelections"+ >,+ input: {+ instanceIds: string[];+ name: string;+ removeLocalProps?: string[];+ },+ context: { createId: () => string }+) => {+ const styleState = getRequiredStyleMutationState(state);+ assertStyleInstances(styleState.instances, input.instanceIds);+ const tokenId = context.createId();+ const { payload, styleKeys } = createDesignTokenExtractionPayload({+ tokenId,+ tokenName: input.name,+ instanceIds: input.instanceIds,+ styleSources: styleState.styleSources,+ styleSourceSelections: styleState.styleSourceSelections.values(),+ styles: styleState.styles.values(),+ removeLocalProps: input.removeLocalProps,+ });+ return createRuntimeMutation({+ payload,+ result: { designTokenId: tokenId, styleKeys },+ invalidatesNamespaces: ["styles", "styleSources", "styleSourceSelections"],+ });+};diff --git a/packages/project-build/src/runtime/unwrap.test.ts b/packages/project-build/src/runtime/unwrap.test.tsnew file mode 100644index 0000000000..51ef6577fe--- /dev/null+++ b/packages/project-build/src/runtime/unwrap.test.ts@@ -0,0 +1,16 @@+import { createDraft } from "immer";+import { expect, test } from "vitest";+import { unwrap } from "./unwrap";++test("returns plain values unchanged", () => {+ const value = { name: "Page" };++ expect(unwrap(value)).toBe(value);+});++test("returns current value for immer drafts", () => {+ const draft = createDraft({ name: "Page" });+ draft.name = "Updated";++ expect(unwrap(draft)).toEqual({ name: "Updated" });+});diff --git a/packages/project-build/src/runtime/unwrap.ts b/packages/project-build/src/runtime/unwrap.tsnew file mode 100644index 0000000000..4269e2517b--- /dev/null+++ b/packages/project-build/src/runtime/unwrap.ts@@ -0,0 +1,4 @@+import { current, isDraft } from "immer";++export const unwrap = <Value>(value: Value) =>+ isDraft(value) ? current(value) : value;diff --git a/packages/project-build/src/state/adapters.test.ts b/packages/project-build/src/state/adapters.test.tsnew file mode 100644index 0000000000..cb1290b26c--- /dev/null+++ b/packages/project-build/src/state/adapters.test.ts@@ -0,0 +1,118 @@+import { expect, test } from "vitest";+import { serializePages } from "@webstudio-is/project-migrations/pages";+import { build, pages } from "./fixtures.test-utils";+import {+ createBuilderStateFromBuildData,+ createBuilderStateFromCompactBuild,+ createBuilderStateFromSerializedSnapshot,+ createBuilderStateFromSnapshot,+ createSerializedBuilderStateSnapshotFromState,+ createBuilderStateSnapshotFromState,+ createBuilderStateFromStores,+} from "./adapters";++test("adapts snapshots without sharing mutable maps", () => {+ const state = createBuilderStateFromSnapshot(build);++ expect(state.pages?.homePageId).toBe(pages.homePageId);+ expect(state.pages?.rootFolderId).toBe(pages.rootFolderId);+ expect(state.pages?.pages).toEqual(pages.pages);+ expect(state.pages?.folders).toEqual(pages.folders);+ expect(state.pages).not.toBe(pages);+ expect(state.pages?.pages).not.toBe(pages.pages);+ expect(state.pages?.folders).not.toBe(pages.folders);+ expect(state.instances).toEqual(new Map(build.instances));+ expect(state.instances).not.toBe(build.instances);+ expect(state.instances?.get("instance-root")).not.toBe(+ build.instances[0]?.[1]+ );+});++test("adapts store boundaries without importing builder stores", () => {+ const state = createBuilderStateFromStores({+ pages: { get: () => pages },+ instances: { get: () => new Map(build.instances) },+ props: { get: () => undefined },+ });++ expect(state.pages?.pages).toEqual(pages.pages);+ expect(state.pages).not.toBe(pages);+ expect(state.pages?.pages).not.toBe(pages.pages);+ expect(state.instances).toEqual(new Map(build.instances));+ expect(state.instances?.get("instance-root")).not.toBe(+ build.instances[0]?.[1]+ );+ expect(state.props).toBeUndefined();+});++test("adapts serialized snapshots with migrated pages", () => {+ const state = createBuilderStateFromSerializedSnapshot({+ pages: {+ ...pages,+ pages: Array.from(pages.pages.values()),+ folders: Array.from(pages.folders.values()),+ },+ props: build.props,+ });++ expect(state.pages?.pages).toEqual(pages.pages);+ expect(state.pages?.folders).toEqual(pages.folders);+ expect(state.props).toEqual(new Map(build.props));+});++test("adapts array build data snapshots into normalized builder state", () => {+ const state = createBuilderStateFromBuildData({+ pages,+ instances: Array.from(new Map(build.instances).values()),+ props: Array.from(new Map(build.props).values()),+ styles: [],+ styleSources: [],+ styleSourceSelections: [],+ dataSources: [],+ resources: [],+ assets: [],+ breakpoints: [],+ marketplaceProduct: build.marketplaceProduct,+ });++ expect(state.pages?.pages).toEqual(pages.pages);+ expect(state.instances).toEqual(new Map(build.instances));+ expect(state.props).toEqual(new Map(build.props));+});++test("adapts compact build snapshots into normalized builder state", () => {+ const state = createBuilderStateFromCompactBuild({+ pages,+ instances: Array.from(new Map(build.instances).values()),+ props: Array.from(new Map(build.props).values()),+ styles: [],+ styleSources: [],+ styleSourceSelections: [],+ dataSources: [],+ resources: [],+ assets: [],+ breakpoints: [],+ marketplaceProduct: build.marketplaceProduct,+ });++ expect(state.pages?.pages).toEqual(pages.pages);+ expect(state.instances).toEqual(new Map(build.instances));+ expect(state.props).toEqual(new Map(build.props));+});++test("serializes builder state into a persisted snapshot shape", () => {+ const state = createBuilderStateFromSnapshot(build);+ const snapshot = createBuilderStateSnapshotFromState(state);++ expect(snapshot.pages).toEqual(state.pages);+ expect(snapshot.instances).toEqual(build.instances);+ expect(snapshot.props).toEqual(build.props);+});++test("serializes builder state into a JSON-safe persisted snapshot shape", () => {+ const state = createBuilderStateFromSnapshot(build);+ const snapshot = createSerializedBuilderStateSnapshotFromState(state);++ expect(snapshot.pages).toEqual(serializePages(state.pages!));+ expect(snapshot.instances).toEqual(build.instances);+});diff --git a/packages/project-build/src/state/adapters.ts b/packages/project-build/src/state/adapters.tsnew file mode 100644index 0000000000..56126ce656--- /dev/null+++ b/packages/project-build/src/state/adapters.ts@@ -0,0 +1,276 @@+import {+ migratePages,+ serializePages,+} from "@webstudio-is/project-migrations/pages";+import {+ type BuilderState,+ type BuilderStateValueByNamespace,+} from "./builder-state";+import {+ builderNamespaces,+ type BuilderNamespace,+} from "../contracts/namespaces";+import {+ getStyleDeclKey,+ type Asset,+ type Breakpoint,+ type DataSource,+ type Instance,+ type Pages,+ type Prop,+ type Resource,+ type StyleDecl,+ type StyleSource,+ type StyleSourceSelection,+} from "@webstudio-is/sdk";+import type { MarketplaceProduct } from "../shared/marketplace";+import type { CompactBuild } from "../types";++type SnapshotValue<Namespace extends BuilderNamespace> =+ BuilderStateValueByNamespace[Namespace] extends Map<infer Key, infer Value>+ ? readonly (readonly [Key, Value])[]+ : BuilderStateValueByNamespace[Namespace];++export type BuilderStateSnapshot = Partial<{+ [Namespace in BuilderNamespace]: SnapshotValue<Namespace>;+}>;++export type SerializedBuilderStateSnapshot = Omit<+ BuilderStateSnapshot,+ "pages"+> & {+ pages?: unknown;+};++export type BuilderBuildDataSnapshot = Partial<{+ pages: Pages;+ instances: Instance[];+ props: Prop[];+ styles: StyleDecl[];+ styleSources: StyleSource[];+ styleSourceSelections: StyleSourceSelection[];+ dataSources: DataSource[];+ resources: Resource[];+ assets: Asset[];+ breakpoints: Breakpoint[];+ marketplaceProduct: MarketplaceProduct;+}>;++export type BuilderCompactBuildDataSnapshot = Pick<+ CompactBuild,+ | "pages"+ | "breakpoints"+ | "styles"+ | "styleSources"+ | "styleSourceSelections"+ | "props"+ | "dataSources"+ | "resources"+ | "instances"+ | "marketplaceProduct"+> & {+ assets?: Asset[];+};++export type BuilderStateStore<Namespace extends BuilderNamespace> = {+ get: () => BuilderStateValueByNamespace[Namespace] | undefined;+};++export type BuilderStateStoreMap = Partial<{+ [Namespace in BuilderNamespace]: BuilderStateStore<Namespace>;+}>;++const cloneMapEntries = <Key, Value>(+ entries: readonly (readonly [Key, Value])[]+) => {+ return new Map(entries.map(([key, value]) => [key, structuredClone(value)]));+};++const cloneMap = <Key, Value>(map: Map<Key, Value>) => {+ return cloneMapEntries(Array.from(map.entries()));+};++const mapEntriesById = <Item extends { id: string }>(items: Item[]) =>+ items.map((item) => [item.id, item] as const);++const setClonedBuilderStateValue = <Namespace extends BuilderNamespace>(+ state: BuilderState,+ namespace: Namespace,+ value: BuilderStateValueByNamespace[Namespace]+) => {+ if (namespace === "pages") {+ state.pages = migratePages(serializePages(value as Pages));+ return;+ }+ if (namespace === "marketplaceProduct") {+ state.marketplaceProduct = structuredClone(value as MarketplaceProduct);+ return;+ }+ (state as Record<string, unknown>)[namespace] = cloneMap(+ value as Map<unknown, unknown>+ );+};++const setClonedBuilderStateSnapshotValue = <Namespace extends BuilderNamespace>(+ state: BuilderState,+ namespace: Namespace,+ value: SnapshotValue<Namespace>+) => {+ if (namespace === "pages") {+ state.pages = migratePages(serializePages(value as Pages));+ return;+ }+ if (namespace === "marketplaceProduct") {+ state.marketplaceProduct = structuredClone(value as MarketplaceProduct);+ return;+ }+ (state as Record<string, unknown>)[namespace] = cloneMapEntries(+ value as readonly (readonly [unknown, unknown])[]+ );+};++export const createBuilderStateFromStores = (+ stores: BuilderStateStoreMap,+ namespaces: readonly BuilderNamespace[] = builderNamespaces+): BuilderState => {+ const state: BuilderState = {};++ for (const namespace of namespaces) {+ const value = stores[namespace]?.get();+ if (value !== undefined) {+ setClonedBuilderStateValue(state, namespace, value);+ }+ }++ return state;+};++export const createBuilderStateFromSnapshot = (+ build: BuilderStateSnapshot+): BuilderState => {+ const state: BuilderState = {};++ for (const namespace of builderNamespaces) {+ const value = build[namespace];+ if (value !== undefined) {+ setClonedBuilderStateSnapshotValue(+ state,+ namespace,+ value as SnapshotValue<typeof namespace>+ );+ }+ }++ return state;+};++export const createBuilderStateFromSerializedSnapshot = (+ build: SerializedBuilderStateSnapshot+): BuilderState => {+ const { pages, ...snapshot } = build;+ const state = createBuilderStateFromSnapshot(snapshot);++ if (pages !== undefined) {+ setClonedBuilderStateValue(state, "pages", migratePages(pages));+ }++ return state;+};++export const createBuilderStateFromBuildData = (+ build: BuilderBuildDataSnapshot+): BuilderState => {+ const snapshot: BuilderStateSnapshot = {};++ if (build.pages !== undefined) {+ snapshot.pages = build.pages;+ }+ if (build.instances !== undefined) {+ snapshot.instances = mapEntriesById(build.instances);+ }+ if (build.props !== undefined) {+ snapshot.props = mapEntriesById(build.props);+ }+ if (build.styles !== undefined) {+ snapshot.styles = build.styles.map((styleDecl) => [+ getStyleDeclKey(styleDecl),+ styleDecl,+ ]);+ }+ if (build.styleSources !== undefined) {+ snapshot.styleSources = mapEntriesById(build.styleSources);+ }+ if (build.styleSourceSelections !== undefined) {+ snapshot.styleSourceSelections = build.styleSourceSelections.map(+ (selection) => [selection.instanceId, selection] as const+ );+ }+ if (build.dataSources !== undefined) {+ snapshot.dataSources = mapEntriesById(build.dataSources);+ }+ if (build.resources !== undefined) {+ snapshot.resources = mapEntriesById(build.resources);+ }+ if (build.assets !== undefined) {+ snapshot.assets = mapEntriesById(build.assets);+ }+ if (build.breakpoints !== undefined) {+ snapshot.breakpoints = mapEntriesById(build.breakpoints);+ }+ if (build.marketplaceProduct !== undefined) {+ snapshot.marketplaceProduct = build.marketplaceProduct;+ }++ return createBuilderStateFromSnapshot(snapshot);+};++export const createBuilderStateFromCompactBuild = (+ build: BuilderCompactBuildDataSnapshot+): BuilderState =>+ createBuilderStateFromBuildData({+ pages: build.pages,+ breakpoints: build.breakpoints,+ styles: build.styles,+ styleSources: build.styleSources,+ styleSourceSelections: build.styleSourceSelections,+ props: build.props,+ dataSources: build.dataSources,+ resources: build.resources,+ instances: build.instances,+ assets: build.assets,+ marketplaceProduct: build.marketplaceProduct,+ });++export const createBuilderStateSnapshotFromState = (+ state: BuilderState+): BuilderStateSnapshot => {+ const snapshot: BuilderStateSnapshot = {};++ for (const namespace of builderNamespaces) {+ const value = state[namespace];+ if (value === undefined) {+ continue;+ }+ if (namespace === "pages" || namespace === "marketplaceProduct") {+ (snapshot as Record<string, unknown>)[namespace] = structuredClone(value);+ continue;+ }+ (snapshot as Record<string, unknown>)[namespace] = Array.from(+ (value as Map<unknown, unknown>).entries()+ ).map(([key, entry]) => [key, structuredClone(entry)]);+ }++ return snapshot;+};++export const createSerializedBuilderStateSnapshotFromState = (+ state: BuilderState+): SerializedBuilderStateSnapshot => {+ const snapshot = createBuilderStateSnapshotFromState(+ state+ ) as SerializedBuilderStateSnapshot;+ if (state.pages !== undefined) {+ snapshot.pages = serializePages(state.pages);+ }+ return snapshot;+};diff --git a/packages/project-build/src/state/builder-state.test.ts b/packages/project-build/src/state/builder-state.test.tsnew file mode 100644index 0000000000..67a129694f--- /dev/null+++ b/packages/project-build/src/state/builder-state.test.ts@@ -0,0 +1,32 @@+import { expect, test } from "vitest";+import { build, pages } from "./fixtures.test-utils";+import {+ getLoadedBuilderStateNamespaces,+ getMissingBuilderStateNamespaces,+ hasBuilderStateNamespaces,+ type BuilderState,+} from "./builder-state";++test("reports loaded builder state namespaces", () => {+ expect(+ getLoadedBuilderStateNamespaces({+ pages,+ instances: new Map(build.instances),+ })+ ).toEqual(["pages", "instances"]);+});++test("reports missing builder state namespaces", () => {+ const state: BuilderState = { pages, instances: new Map(build.instances) };++ expect(getMissingBuilderStateNamespaces(state, ["pages", "props"])).toEqual([+ "props",+ ]);+});++test("detects when required builder state namespaces are loaded", () => {+ const state: BuilderState = { pages, instances: new Map(build.instances) };++ expect(hasBuilderStateNamespaces(state, ["pages", "instances"])).toBe(true);+ expect(hasBuilderStateNamespaces(state, ["pages", "props"])).toBe(false);+});diff --git a/packages/project-build/src/state/builder-state.ts b/packages/project-build/src/state/builder-state.tsnew file mode 100644index 0000000000..7636c341bd--- /dev/null+++ b/packages/project-build/src/state/builder-state.ts@@ -0,0 +1,59 @@+import type {+ Assets,+ Breakpoints,+ DataSources,+ Instances,+ Pages,+ Props,+ Resources,+ Styles,+ StyleSources,+ StyleSourceSelections,+} from "@webstudio-is/sdk";+import {+ builderNamespaces,+ type BuilderNamespace,+} from "../contracts/namespaces";+import type { MarketplaceProduct } from "../shared/marketplace";++export type BuilderStateValueByNamespace = {+ pages: Pages;+ instances: Instances;+ props: Props;+ styles: Styles;+ styleSources: StyleSources;+ styleSourceSelections: StyleSourceSelections;+ dataSources: DataSources;+ resources: Resources;+ assets: Assets;+ breakpoints: Breakpoints;+ marketplaceProduct: MarketplaceProduct;+};++export type BuilderState = Partial<BuilderStateValueByNamespace>;++export const getLoadedBuilderStateNamespaces = (+ state: BuilderState+): BuilderNamespace[] => {+ return builderNamespaces.filter(+ (namespace) => state[namespace] !== undefined+ );+};++export const getMissingBuilderStateNamespaces = (+ state: BuilderState,+ requiredNamespaces: readonly BuilderNamespace[] = builderNamespaces+): BuilderNamespace[] => {+ return requiredNamespaces.filter(+ (namespace) => state[namespace] === undefined+ );+};++export const hasBuilderStateNamespaces = (+ state: BuilderState,+ requiredNamespaces: readonly BuilderNamespace[]+) => {+ return (+ getMissingBuilderStateNamespaces(state, requiredNamespaces).length === 0+ );+};diff --git a/packages/project-build/src/state/fixtures.test-utils.ts b/packages/project-build/src/state/fixtures.test-utils.tsnew file mode 100644index 0000000000..07abd321dd--- /dev/null+++ b/packages/project-build/src/state/fixtures.test-utils.ts@@ -0,0 +1,74 @@+import type { BuilderStateSnapshot } from "./adapters";++export const pages = {+ homePageId: "page-home",+ rootFolderId: "folder-root",+ pages: new Map([+ [+ "page-home",+ {+ id: "page-home",+ name: "Home",+ title: "Home",+ path: "",+ rootInstanceId: "instance-root",+ meta: {},+ },+ ],+ ]),+ folders: new Map([+ [+ "folder-root",+ {+ id: "folder-root",+ name: "Root",+ slug: "",+ children: ["page-home"],+ },+ ],+ ]),+};++export const build = {+ pages,+ instances: [+ [+ "instance-root",+ {+ type: "instance",+ id: "instance-root",+ component: "Body",+ children: [],+ },+ ],+ ],+ props: [+ [+ "prop-title",+ {+ id: "prop-title",+ instanceId: "instance-root",+ name: "Title",+ type: "string",+ value: "Title",+ },+ ],+ ],+ styles: [],+ styleSources: [],+ styleSourceSelections: [],+ dataSources: [],+ resources: [],+ assets: [],+ breakpoints: [],+ marketplaceProduct: {+ category: "sectionTemplates",+ name: "Example section",+ thumbnailAssetId: "asset-thumbnail",+ author: "Webstudio",+ email: "[email protected]",+ website: "",+ issues: "",+ description: "Example marketplace product",+ },+} as const satisfies BuilderStateSnapshot;diff --git a/packages/project-build/src/state/freshness.test.ts b/packages/project-build/src/state/freshness.test.tsnew file mode 100644index 0000000000..ad991a37ae--- /dev/null+++ b/packages/project-build/src/state/freshness.test.ts@@ -0,0 +1,77 @@+import { expect, test } from "vitest";+import { build, pages } from "./fixtures.test-utils";+import type { BuilderState } from "./builder-state";+import {+ createBuilderStateFreshness,+ getBuilderStateNamespacesByStatus,+ getBuilderStateNamespaceFreshness,+ markBuilderStateNamespacesInvalidated,+ markBuilderStateNamespacesStale,+} from "./freshness";++test("reports missing, fresh, stale, and invalidated namespaces", () => {+ const state: BuilderState = { pages, instances: new Map(build.instances) };+ const freshness = createBuilderStateFreshness({+ state,+ version: 3,+ staleNamespaces: ["instances"],+ });++ expect(getBuilderStateNamespacesByStatus(freshness, "fresh")).toEqual([+ "pages",+ ]);+ expect(getBuilderStateNamespacesByStatus(freshness, "stale")).toEqual([+ "instances",+ ]);+ expect(getBuilderStateNamespacesByStatus(freshness, "missing")).toContain(+ "props"+ );++ const stale = markBuilderStateNamespacesStale(freshness, ["pages"]);+ expect(getBuilderStateNamespacesByStatus(stale, "stale")).toEqual([+ "pages",+ "instances",+ ]);+ expect(markBuilderStateNamespacesStale(stale, ["props"]).props).toEqual({+ status: "missing",+ });++ const invalidated = markBuilderStateNamespacesInvalidated(+ stale,+ ["pages"],+ "tx-1"+ );+ expect(invalidated.pages).toEqual({+ status: "invalidated",+ version: 3,+ invalidatedBy: "tx-1",+ });+ expect(+ markBuilderStateNamespacesInvalidated(invalidated, ["props"], "tx-1").props+ ).toEqual({ status: "missing" });++ expect(markBuilderStateNamespacesStale(invalidated, ["pages"]).pages).toEqual(+ {+ status: "stale",+ version: 3,+ }+ );+ expect(markBuilderStateNamespacesInvalidated(stale, ["pages"]).pages).toEqual(+ {+ status: "invalidated",+ version: 3,+ }+ );+});++test("does not share mutable missing freshness objects", () => {+ const first = getBuilderStateNamespaceFreshness({}, "pages");+ first.status = "fresh";++ expect(getBuilderStateNamespaceFreshness({}, "pages")).toEqual({+ status: "missing",+ });++ const freshness = createBuilderStateFreshness({ state: {} });+ expect(freshness.pages).not.toBe(freshness.instances);+});diff --git a/packages/project-build/src/state/freshness.ts b/packages/project-build/src/state/freshness.tsnew file mode 100644index 0000000000..e772766616--- /dev/null+++ b/packages/project-build/src/state/freshness.ts@@ -0,0 +1,120 @@+import type { BuilderState } from "./builder-state";+import {+ builderNamespaces,+ type BuilderNamespace,+} from "../contracts/namespaces";++export type BuilderStateNamespaceStatus =+ | "missing"+ | "fresh"+ | "stale"+ | "invalidated";++export type BuilderStateNamespaceFreshness = {+ status: BuilderStateNamespaceStatus;+ version?: number;+ invalidatedBy?: string;+};++export type BuilderStateFreshness = Partial<+ Record<BuilderNamespace, BuilderStateNamespaceFreshness>+>;++const createMissingBuilderStateNamespaceFreshness =+ (): BuilderStateNamespaceFreshness => ({+ status: "missing",+ });++export const getBuilderStateNamespaceFreshness = (+ freshness: BuilderStateFreshness,+ namespace: BuilderNamespace+): BuilderStateNamespaceFreshness => {+ return freshness[namespace] ?? createMissingBuilderStateNamespaceFreshness();+};++export const createBuilderStateFreshness = ({+ state,+ version,+ staleNamespaces = [],+ invalidatedNamespaces = [],+ invalidatedBy,+}: {+ state: BuilderState;+ version?: number;+ staleNamespaces?: readonly BuilderNamespace[];+ invalidatedNamespaces?: readonly BuilderNamespace[];+ invalidatedBy?: string;+}): BuilderStateFreshness => {+ const stale = new Set(staleNamespaces);+ const invalidated = new Set(invalidatedNamespaces);+ const freshness: BuilderStateFreshness = {};++ for (const namespace of builderNamespaces) {+ if (state[namespace] === undefined) {+ freshness[namespace] = createMissingBuilderStateNamespaceFreshness();+ continue;+ }+ if (invalidated.has(namespace)) {+ freshness[namespace] =+ invalidatedBy === undefined+ ? { status: "invalidated", version }+ : { status: "invalidated", version, invalidatedBy };+ continue;+ }+ if (stale.has(namespace)) {+ freshness[namespace] = { status: "stale", version };+ continue;+ }+ freshness[namespace] = { status: "fresh", version };+ }++ return freshness;+};++export const getBuilderStateNamespacesByStatus = (+ freshness: BuilderStateFreshness,+ status: BuilderStateNamespaceStatus+): BuilderNamespace[] => {+ return builderNamespaces.filter(+ (namespace) =>+ getBuilderStateNamespaceFreshness(freshness, namespace).status === status+ );+};++export const markBuilderStateNamespacesStale = (+ freshness: BuilderStateFreshness,+ namespaces: readonly BuilderNamespace[]+): BuilderStateFreshness => {+ const next = { ...freshness };+ for (const namespace of namespaces) {+ const current = getBuilderStateNamespaceFreshness(freshness, namespace);+ if (current.status === "missing") {+ continue;+ }+ next[namespace] = { status: "stale", version: current.version };+ }+ return next;+};++export const markBuilderStateNamespacesInvalidated = (+ freshness: BuilderStateFreshness,+ namespaces: readonly BuilderNamespace[],+ invalidatedBy?: string+): BuilderStateFreshness => {+ const next = { ...freshness };+ for (const namespace of namespaces) {+ const current = getBuilderStateNamespaceFreshness(freshness, namespace);+ if (current.status === "missing") {+ continue;+ }+ next[namespace] =+ invalidatedBy === undefined+ ? { status: "invalidated", version: current.version }+ : {+ status: "invalidated",+ version: current.version,+ invalidatedBy,+ };+ }+ return next;+};diff --git a/packages/project-build/src/state/package-boundary.test.ts b/packages/project-build/src/state/package-boundary.test.tsnew file mode 100644index 0000000000..6acec4759a--- /dev/null+++ b/packages/project-build/src/state/package-boundary.test.ts@@ -0,0 +1,69 @@+import { readdir, readFile } from "node:fs/promises";+import { dirname, join } from "node:path";+import { fileURLToPath } from "node:url";+import { describe, expect, test } from "vitest";++const currentDirectory = dirname(fileURLToPath(import.meta.url));+const sourceDirectory = join(currentDirectory, "..");+const checkedDirectories = [+ join(sourceDirectory, "contracts"),+ join(sourceDirectory, "runtime"),+ join(sourceDirectory, "state"),+];+const checkedFiles = [join(sourceDirectory, "project-session.ts")];++const forbiddenImports = [+ "@webstudio-is/protocol",+ "@webstudio-is/http-client",+ "@webstudio-is/authorization-token",+ 'from "@webstudio-is/project"',+ "from '@webstudio-is/project'",+ 'from "@webstudio-is/project/',+ "from '@webstudio-is/project/",+ "@webstudio-is/domain",+ "apps/builder",+ "/app/",+ "../db/",+ "../index.server",+ "deployment",+];++const readTypeScriptFiles = async (directory: string): Promise<string[]> => {+ const entries = await readdir(directory, { withFileTypes: true });+ const files: string[] = [];++ for (const entry of entries) {+ const path = join(directory, entry.name);+ if (entry.isDirectory()) {+ files.push(...(await readTypeScriptFiles(path)));+ continue;+ }+ if (+ entry.name.endsWith(".ts") &&+ entry.name.endsWith(".test.ts") === false+ ) {+ files.push(path);+ }+ }++ return files;+};++describe("project-build state entry point boundaries", () => {+ test("does not import transport, builder app, db, auth, or deployment code", async () => {+ const files = (+ await Promise.all(checkedDirectories.map(readTypeScriptFiles))+ )+ .flat()+ .concat(checkedFiles);++ for (const file of files) {+ const source = await readFile(file, "utf8");+ for (const forbiddenImport of forbiddenImports) {+ expect(source, `${file} imports ${forbiddenImport}`).not.toContain(+ forbiddenImport+ );+ }+ }+ });+});diff --git a/packages/project-build/src/state/patch.test.ts b/packages/project-build/src/state/patch.test.tsnew file mode 100644index 0000000000..08e15bdd5f--- /dev/null+++ b/packages/project-build/src/state/patch.test.ts@@ -0,0 +1,157 @@+import { expect, test } from "vitest";+import { build } from "./fixtures.test-utils";+import type { BuilderState } from "./builder-state";+import type { Props } from "@webstudio-is/sdk";+import {+ applyBuilderNamespacePatches,+ applyBuilderPatchPayloadMutable,+ applyBuilderPatchTransactions,+ MissingBuilderStateNamespaceError,+} from "./patch";++test("applies namespace patches", () => {+ const nextProps = applyBuilderNamespacePatches<Props>(new Map(build.props), [+ {+ op: "add",+ path: ["prop-subtitle"],+ value: {+ id: "prop-subtitle",+ instanceId: "instance-root",+ name: "Subtitle",+ type: "string",+ value: "Subtitle",+ },+ },+ ]);++ expect(nextProps.get("prop-subtitle")).toEqual({+ id: "prop-subtitle",+ instanceId: "instance-root",+ name: "Subtitle",+ type: "string",+ value: "Subtitle",+ });+});++test("applies patch payloads mutably through namespace resolver", () => {+ const props = new Map<string, unknown>(build.props);+ applyBuilderPatchPayloadMutable(+ (namespace) => {+ if (namespace !== "props") {+ throw new Error("Unexpected namespace");+ }+ return props;+ },+ [+ {+ namespace: "props",+ patches: [+ {+ op: "add",+ path: ["prop-subtitle"],+ value: {+ id: "prop-subtitle",+ instanceId: "instance-root",+ name: "Subtitle",+ type: "string",+ value: "Subtitle",+ },+ },+ {+ op: "replace",+ path: ["prop-subtitle", "value"],+ value: "Updated subtitle",+ },+ ],+ },+ ]+ );++ expect(props.get("prop-subtitle")).toEqual({+ id: "prop-subtitle",+ instanceId: "instance-root",+ name: "Subtitle",+ type: "string",+ value: "Updated subtitle",+ });+});++test("applies transactions without mutating the input state object", () => {+ const state: BuilderState = {+ props: new Map(build.props),+ };+ const { state: nextState, changedNamespaces } = applyBuilderPatchTransactions(+ state,+ [+ {+ id: "tx-1",+ payload: [+ {+ namespace: "props",+ patches: [+ {+ op: "add",+ path: ["prop-subtitle"],+ value: {+ id: "prop-subtitle",+ instanceId: "instance-root",+ name: "Subtitle",+ type: "string",+ value: "Subtitle",+ },+ },+ ],+ },+ ],+ },+ ]+ );++ expect(changedNamespaces).toEqual(["props"]);+ expect(nextState).not.toBe(state);+ expect(nextState.props).not.toBe(state.props);+ expect(state.props?.has("prop-subtitle")).toBe(false);+ expect(nextState.props?.get("prop-subtitle")).toEqual({+ id: "prop-subtitle",+ instanceId: "instance-root",+ name: "Subtitle",+ type: "string",+ value: "Subtitle",+ });+});++test("ignores empty patch changes", () => {+ const { state: nextState, changedNamespaces } = applyBuilderPatchTransactions(+ {},+ [+ {+ id: "tx-1",+ payload: [{ namespace: "props", patches: [] }],+ },+ ]+ );++ expect(nextState).toEqual({});+ expect(changedNamespaces).toEqual([]);+});++test("fails when a transaction targets a missing namespace", () => {+ expect(() =>+ applyBuilderPatchTransactions({}, [+ {+ id: "tx-1",+ payload: [+ {+ namespace: "props",+ patches: [+ {+ op: "remove",+ path: ["prop-title"],+ },+ ],+ },+ ],+ },+ ])+ ).toThrow(MissingBuilderStateNamespaceError);+});diff --git a/packages/project-build/src/state/patch.ts b/packages/project-build/src/state/patch.tsnew file mode 100644index 0000000000..f7c67408ac--- /dev/null+++ b/packages/project-build/src/state/patch.ts@@ -0,0 +1,153 @@+import { applyPatches, enableMapSet, enablePatches, type Patch } from "immer";+import type {+ BuilderPatch,+ BuilderPatchChange,+ BuilderPatchTransaction,+} from "../contracts/patch";+import type { BuilderState } from "./builder-state";+import type { BuilderNamespace } from "../contracts/namespaces";++export class MissingBuilderStateNamespaceError extends Error {+ constructor(namespace: BuilderNamespace) {+ super(`Builder state namespace "${namespace}" is missing.`);+ this.name = "MissingBuilderStateNamespaceError";+ }+}++export type ApplyBuilderPatchTransactionsResult = {+ state: BuilderState;+ changedNamespaces: BuilderNamespace[];+};++let areImmerPatchPluginsEnabled = false;++const enableImmerPatchPlugins = () => {+ if (areImmerPatchPluginsEnabled) {+ return;+ }+ enableMapSet();+ enablePatches();+ areImmerPatchPluginsEnabled = true;+};++export const applyBuilderNamespacePatches = <State>(+ state: State,+ patches: readonly BuilderPatch[]+): State => {+ enableImmerPatchPlugins();+ return applyPatches(state as never, patches as Patch[]) as State;+};++const getPathValue = (target: unknown, segment: string | number): unknown => {+ if (target instanceof Map) {+ return target.get(segment);+ }+ if (Array.isArray(target)) {+ return target[Number(segment)];+ }+ if (typeof target === "object" && target !== null) {+ return (target as Record<string, unknown>)[String(segment)];+ }+};++const setPathValue = (+ target: unknown,+ segment: string | number,+ value: unknown,+ operation: "add" | "replace"+) => {+ if (target instanceof Map) {+ target.set(segment, value);+ return;+ }+ if (Array.isArray(target)) {+ const index = Number(segment);+ if (operation === "add") {+ target.splice(index, 0, value);+ return;+ }+ target[index] = value;+ return;+ }+ if (typeof target === "object" && target !== null) {+ (target as Record<string, unknown>)[String(segment)] = value;+ return;+ }+ throw Error("Cannot set patch value on non-container target");+};++const removePathValue = (target: unknown, segment: string | number) => {+ if (target instanceof Map) {+ target.delete(segment);+ return;+ }+ if (Array.isArray(target)) {+ target.splice(Number(segment), 1);+ return;+ }+ if (typeof target === "object" && target !== null) {+ delete (target as Record<string, unknown>)[String(segment)];+ return;+ }+ throw Error("Cannot remove patch value from non-container target");+};++const getPatchParent = (+ namespaceData: unknown,+ patch: BuilderPatch+): { parent: unknown; key: string | number } => {+ const key = patch.path.at(-1);+ if (key === undefined) {+ throw Error("Cannot apply patch with empty path");+ }+ let parent = namespaceData;+ for (const segment of patch.path.slice(0, -1)) {+ parent = getPathValue(parent, segment);+ if (parent === undefined) {+ throw Error(`Cannot apply patch through missing path "${segment}"`);+ }+ }+ return { parent, key };+};++export const applyBuilderPatchPayloadMutable = (+ getNamespaceData: (namespace: BuilderNamespace) => unknown,+ payload: readonly BuilderPatchChange[]+) => {+ for (const change of payload) {+ const namespaceData = getNamespaceData(change.namespace);+ for (const patch of change.patches) {+ const { parent, key } = getPatchParent(namespaceData, patch);+ if (patch.op === "remove") {+ removePathValue(parent, key);+ continue;+ }+ setPathValue(parent, key, patch.value, patch.op);+ }+ }+};++export const applyBuilderPatchTransactions = (+ state: BuilderState,+ transactions: readonly BuilderPatchTransaction[]+): ApplyBuilderPatchTransactionsResult => {+ const nextState: BuilderState = { ...state };+ const changedNamespaces = new Set<BuilderNamespace>();++ for (const transaction of transactions) {+ for (const change of transaction.payload) {+ if (change.patches.length === 0) {+ continue;+ }+ const namespaceState = nextState[change.namespace];+ if (namespaceState === undefined) {+ throw new MissingBuilderStateNamespaceError(change.namespace);+ }+ (nextState as Record<string, unknown>)[change.namespace] =+ applyBuilderNamespacePatches(namespaceState, change.patches);+ changedNamespaces.add(change.namespace);+ }+ }++ return { state: nextState, changedNamespaces: [...changedNamespaces] };+};diff --git a/packages/project-build/src/visual/screenshot-browser.test.ts b/packages/project-build/src/visual/screenshot-browser.test.tsnew file mode 100644index 0000000000..280171d5d5--- /dev/null+++ b/packages/project-build/src/visual/screenshot-browser.test.ts@@ -0,0 +1,36 @@+import { expect, test } from "vitest";+import {+ defaultScreenshotTimeout,+ defaultScreenshotWaitForTimeout,+ defaultScreenshotWaitUntil,+ isScreenshotWaitUntil,+ screenshotBrowserChoices,+ screenshotWaitUntilValues,+} from "./screenshot-browser";++test("defines supported screenshot browser choices in preference order", () => {+ expect(screenshotBrowserChoices).toEqual([+ "auto",+ "chromium",+ "chrome",+ "edge",+ "brave",+ ]);+});++test("defines supported screenshot readiness events in lifecycle order", () => {+ expect(screenshotWaitUntilValues).toEqual([+ "commit",+ "domcontentloaded",+ "load",+ "networkidle",+ ]);+ expect(isScreenshotWaitUntil("load")).toBe(true);+ expect(isScreenshotWaitUntil("interactive")).toBe(false);+});++test("defines screenshot readiness defaults", () => {+ expect(defaultScreenshotWaitUntil).toBe("load");+ expect(defaultScreenshotWaitForTimeout).toBe(250);+ expect(defaultScreenshotTimeout).toBe(30000);+});diff --git a/packages/project-build/src/visual/screenshot-browser.ts b/packages/project-build/src/visual/screenshot-browser.tsnew file mode 100644index 0000000000..50630ba8af--- /dev/null+++ b/packages/project-build/src/visual/screenshot-browser.ts@@ -0,0 +1,30 @@+export const screenshotBrowserChoices = [+ "auto",+ "chromium",+ "chrome",+ "edge",+ "brave",+] as const;++export type ScreenshotBrowser = (typeof screenshotBrowserChoices)[number];++export const screenshotWaitUntilValues = [+ "commit",+ "domcontentloaded",+ "load",+ "networkidle",+] as const;++export type ScreenshotWaitUntil = (typeof screenshotWaitUntilValues)[number];++export const defaultScreenshotWaitUntil: ScreenshotWaitUntil = "load";++export const defaultScreenshotWaitForTimeout = 250;++export const defaultScreenshotTimeout = 30000;++export const isScreenshotWaitUntil = (+ value: unknown+): value is ScreenshotWaitUntil =>+ typeof value === "string" &&+ screenshotWaitUntilValues.includes(value as ScreenshotWaitUntil);diff --git a/packages/project-build/src/visual/screenshot-diff.test.ts b/packages/project-build/src/visual/screenshot-diff.test.tsnew file mode 100644index 0000000000..a8b6a72786--- /dev/null+++ b/packages/project-build/src/visual/screenshot-diff.test.ts@@ -0,0 +1,134 @@+import { mkdtemp, readFile, rm } from "node:fs/promises";+import { tmpdir } from "node:os";+import path from "node:path";+import { afterEach, beforeEach, expect, test } from "vitest";+import { diffPngFiles } from "./screenshot-diff";+import { createPng, paintRect, writePng } from "./screenshot.test-utils";++let tempDir: string;++beforeEach(async () => {+ tempDir = await mkdtemp(path.join(tmpdir(), "webstudio-screenshot-diff-"));+});++afterEach(async () => {+ await rm(tempDir, { recursive: true, force: true });+});++test("detects pixel differences, regions, color deltas, and writes artifacts", async () => {+ const baselinePath = path.join(tempDir, "baseline.png");+ const currentPath = path.join(tempDir, "current.png");+ const outputDir = path.join(tempDir, "diff");++ await writePng(baselinePath, createPng(10, 10, { r: 255, g: 255, b: 255 }));+ const current = createPng(10, 10, { r: 255, g: 255, b: 255 });+ paintRect(current, { x: 2, y: 3, width: 3, height: 2 }, { r: 0, g: 0, b: 0 });+ await writePng(currentPath, current);++ const result = await diffPngFiles({+ baselinePath,+ currentPath,+ outputDir,+ ignoreTopNormalizedY: 0,+ });++ expect(result.totalPixels).toBe(100);+ expect(result.differentPixels).toBe(6);+ expect(result.mismatchPercentage).toBe(6);+ expect(result.imageSize).toEqual({ width: 10, height: 10 });+ expect(result.regions).toEqual([+ expect.objectContaining({+ bounds: { x: 2, y: 3, width: 3, height: 2 },+ pixelCount: 6,+ averageColor: expect.objectContaining({+ delta: { r: -255, g: -255, b: -255 },+ dominantChange: {+ channel: "luminance",+ direction: "decrease",+ magnitude: 255,+ },+ }),+ }),+ ]);+ expect(result.summary).toContain("status: changed");+ expect(result.summary).toContain("pixel_mismatch: 6.00%");+ expect(result.summary).toContain("Region 1");+ await expect(readFile(result.diffPath ?? "")).resolves.toBeInstanceOf(Buffer);+ await expect(readFile(result.contextDiffPath ?? "")).resolves.toBeInstanceOf(+ Buffer+ );+});++test("normalizes same-aspect screenshots before comparing", async () => {+ const baselinePath = path.join(tempDir, "baseline.png");+ const currentPath = path.join(tempDir, "current.png");++ await writePng(baselinePath, createPng(2, 2, { r: 20, g: 20, b: 20 }));+ await writePng(currentPath, createPng(4, 4, { r: 20, g: 20, b: 20 }));++ const result = await diffPngFiles({+ baselinePath,+ currentPath,+ outputDir: path.join(tempDir, "diff"),+ });++ expect(result.dimensionMismatch).toBeUndefined();+ expect(result.imageSize).toEqual({ width: 2, height: 2 });+ expect(result.differentPixels).toBe(0);+ expect(result.textAnalysis.status).toBe("skipped");+ expect(result.warnings).toEqual(["ocr_skipped_size_normalized"]);+ expect(result.summary).toContain("status: unchanged");+});++test("reports dimension mismatch for different aspect ratios", async () => {+ const baselinePath = path.join(tempDir, "baseline.png");+ const currentPath = path.join(tempDir, "current.png");++ await writePng(baselinePath, createPng(2, 2, { r: 20, g: 20, b: 20 }));+ await writePng(currentPath, createPng(3, 2, { r: 20, g: 20, b: 20 }));++ const result = await diffPngFiles({+ baselinePath,+ currentPath,+ outputDir: path.join(tempDir, "diff"),+ });++ expect(result.dimensionMismatch).toEqual({+ expected: { width: 2, height: 2 },+ actual: { width: 3, height: 2 },+ });+ expect(result.diffPath).toBeUndefined();+ expect(result.regions).toEqual([]);+ expect(result.textAnalysis.status).toBe("skipped");+ expect(result.summary).toContain("status: dimension_mismatch");+});++test("can ignore a normalized top band", async () => {+ const baselinePath = path.join(tempDir, "baseline.png");+ const currentPath = path.join(tempDir, "current.png");++ await writePng(baselinePath, createPng(10, 10, { r: 255, g: 255, b: 255 }));+ const current = createPng(10, 10, { r: 255, g: 255, b: 255 });+ paintRect(+ current,+ { x: 0, y: 0, width: 10, height: 1 },+ { r: 0, g: 0, b: 0 }+ );+ paintRect(current, { x: 0, y: 5, width: 2, height: 1 }, { r: 0, g: 0, b: 0 });+ await writePng(currentPath, current);++ const result = await diffPngFiles({+ baselinePath,+ currentPath,+ outputDir: path.join(tempDir, "diff"),+ ignoreTopNormalizedY: 0.1,+ });++ expect(result.differentPixels).toBe(2);+ expect(result.regions).toEqual([+ expect.objectContaining({+ bounds: { x: 0, y: 5, width: 2, height: 1 },+ pixelCount: 2,+ }),+ ]);+});diff --git a/packages/project-build/src/visual/screenshot-diff.ts b/packages/project-build/src/visual/screenshot-diff.tsnew file mode 100644index 0000000000..4a4380303c--- /dev/null+++ b/packages/project-build/src/visual/screenshot-diff.ts@@ -0,0 +1,953 @@+/**+ * Adapted from Software Mansion Argent's screenshot-diff implementation.+ * Source: https://github.com/software-mansion/argent/tree/main/packages/tool-server/src/tools/screenshot-diff+ * License: Apache-2.0+ */++import fs from "node:fs/promises";+import path from "node:path";+import { decode, encode, type DecodedPng, type ImageData } from "fast-png";+import {+ normalizeToCommonSize,+ resizeDecodedRgbaImage,+ type DecodedRgbaImage,+} from "./screenshot-resize";+import {+ analyzeScreenshotTextChanges,+ type ScreenshotTextAnalysis,+} from "./screenshot-text-diff";++export type ScreenshotDiffSize = {+ width: number;+ height: number;+};++export type ScreenshotDiffRgb = {+ r: number;+ g: number;+ b: number;+};++export type ScreenshotDiffBounds = {+ x: number;+ y: number;+ width: number;+ height: number;+};++export type ScreenshotDiffDominantColorChange = {+ channel: "red" | "green" | "blue" | "luminance" | "none";+ direction: "increase" | "decrease" | "none";+ magnitude: number;+};++export type ScreenshotDiffRegion = {+ bounds: ScreenshotDiffBounds;+ pixelCount: number;+ averageColor: {+ delta: ScreenshotDiffRgb;+ dominantChange: ScreenshotDiffDominantColorChange;+ };+};++export type ScreenshotDiffResult = {+ totalPixels: number;+ differentPixels: number;+ mismatchPercentage: number;+ imageSize?: ScreenshotDiffSize;+ summary: string;+ diffPath?: string;+ contextDiffPath?: string;+ dimensionMismatch?: {+ expected: ScreenshotDiffSize;+ actual: ScreenshotDiffSize;+ };+ regions: ScreenshotDiffRegion[];+ textAnalysis: ScreenshotTextAnalysis;+ warnings: readonly string[];+};++type ChangeRegion = {+ minX: number;+ minY: number;+ maxX: number;+ maxY: number;+ pixelCount: number;+ baselineSum: ScreenshotDiffRgb;+ currentSum: ScreenshotDiffRgb;+};++type DiffMask = {+ mask: Uint8Array;+ differentPixels: number;+};++const MAX_RGB_DISTANCE_SQUARED = 255 * 255 * 3;+const DEFAULT_THRESHOLD = 0.1;+const DEFAULT_IGNORE_TOP_NORMALIZED_Y = 0;+const DEFAULT_REGION_MERGE_DISTANCE = 8;+const DEFAULT_CONTEXT_DIFF_SCALE = 0.3;+const MIN_REGION_PIXEL_COUNT = 2;+const MAX_REGIONS_FOR_JOIN = 5000;+const MAX_REGIONS_WITHOUT_JOIN = 64;+const REGION_RECTANGLE_STROKE_WIDTH = 4;+const REGION_RECTANGLE_COLOR: ScreenshotDiffRgb = { r: 255, g: 220, b: 0 };+const DIFF_BRIGHTER_COLOR: ScreenshotDiffRgb = { r: 0, g: 200, b: 0 };+const DIFF_DARKER_COLOR: ScreenshotDiffRgb = { r: 255, g: 0, b: 0 };+const HORIZONTAL_TEXT_MERGE_HEIGHT_MULTIPLIER = 3;+const HORIZONTAL_TEXT_MERGE_MIN_GAP = 32;+const HORIZONTAL_TEXT_MERGE_MAX_GAP = 120;+const UNIFORM_BRIGHTNESS_DELTA_TOLERANCE = 4;+const MAX_SUMMARY_REGIONS = 8;++export const diffPngFiles = async ({+ baselinePath,+ currentPath,+ outputDir,+ threshold = DEFAULT_THRESHOLD,+ ignoreTopNormalizedY = DEFAULT_IGNORE_TOP_NORMALIZED_Y,+}: {+ baselinePath: string;+ currentPath: string;+ outputDir: string;+ threshold?: number;+ ignoreTopNormalizedY?: number;+}): Promise<ScreenshotDiffResult> => {+ const [decodedBaseline, decodedCurrent] = await Promise.all([+ decodePngFile(baselinePath),+ decodePngFile(currentPath),+ ]);++ const normalized = normalizeToCommonSize(decodedBaseline, decodedCurrent);+ if (normalized === undefined) {+ return summarizeResult({+ totalPixels: decodedBaseline.width * decodedBaseline.height,+ differentPixels: 0,+ mismatchPercentage: 0,+ dimensionMismatch: {+ expected: {+ width: decodedBaseline.width,+ height: decodedBaseline.height,+ },+ actual: {+ width: decodedCurrent.width,+ height: decodedCurrent.height,+ },+ },+ regions: [],+ textAnalysis: {+ status: "skipped",+ provider: "tesseract",+ changes: [],+ },+ warnings: ["dimension_mismatch"],+ });+ }++ const baseline = normalized.baseline;+ const current = normalized.current;+ const pixelDiff = markChangedPixels({+ baseline,+ current,+ thresholdSquared: threshold * threshold * MAX_RGB_DISTANCE_SQUARED,+ ignoreTopNormalizedY,+ });+ const regions = getChangedRegions({+ mask: pixelDiff.mask,+ baseline,+ current,+ joinGapPixels: DEFAULT_REGION_MERGE_DISTANCE,+ });+ const totalPixels = baseline.width * baseline.height;+ const artifactPaths = getDiffArtifactPaths({ currentPath, outputDir });+ await writeDiffArtifacts({+ baseline,+ current,+ mask: pixelDiff.mask,+ regions,+ paths: artifactPaths,+ contextDiffScale: DEFAULT_CONTEXT_DIFF_SCALE,+ });+ const canAnalyzeText =+ decodedBaseline.width === decodedCurrent.width &&+ decodedBaseline.height === decodedCurrent.height;+ const textAnalysis: ScreenshotTextAnalysis = canAnalyzeText+ ? await analyzeScreenshotTextChanges({+ baselinePath,+ currentPath,+ hasPixelDiff: pixelDiff.differentPixels > 0,+ baselineImage: baseline,+ currentImage: current,+ ignoreTopPixels: Math.ceil(baseline.height * ignoreTopNormalizedY),+ })+ : createSkippedTextAnalysis();++ return summarizeResult({+ totalPixels,+ differentPixels: pixelDiff.differentPixels,+ mismatchPercentage:+ totalPixels === 0 ? 0 : (pixelDiff.differentPixels / totalPixels) * 100,+ imageSize: { width: baseline.width, height: baseline.height },+ diffPath: artifactPaths.diffPath,+ contextDiffPath: artifactPaths.contextDiffPath,+ regions,+ textAnalysis,+ warnings: getTextAnalysisWarnings({ canAnalyzeText, textAnalysis }),+ });+};++const getTextAnalysisWarnings = ({+ canAnalyzeText,+ textAnalysis,+}: {+ canAnalyzeText: boolean;+ textAnalysis: ScreenshotTextAnalysis;+}) => {+ if (canAnalyzeText === false) {+ return ["ocr_skipped_size_normalized"];+ }+ if (textAnalysis.status === "unavailable") {+ return ["ocr_unavailable_tesseract_not_found_or_failed"];+ }+ return [];+};++const createSkippedTextAnalysis = (): ScreenshotTextAnalysis => ({+ status: "skipped",+ provider: "tesseract",+ changes: [],+});++const summarizeResult = (+ result: Omit<ScreenshotDiffResult, "summary">+): ScreenshotDiffResult => ({+ ...result,+ summary: formatScreenshotDiffSummary(result),+});++const decodePngFile = async (filePath: string): Promise<DecodedRgbaImage> => {+ const buffer = await fs.readFile(filePath);+ const png = decode(buffer);+ return { width: png.width, height: png.height, data: toRgbaData(png) };+};++const toRgbaData = (png: DecodedPng): Uint8Array => {+ if (png.depth !== 8 || png.data instanceof Uint8Array === false) {+ throw new Error("Only 8-bit PNG screenshots are supported.");+ }+ if (png.channels === 4) {+ return Uint8Array.from(png.data);+ }+ const output = new Uint8Array(png.width * png.height * 4);+ for (let pixelIndex = 0; pixelIndex < png.width * png.height; pixelIndex++) {+ const sourceOffset = pixelIndex * png.channels;+ const outputOffset = pixelIndex * 4;+ if (png.channels === 3) {+ output[outputOffset] = png.data[sourceOffset];+ output[outputOffset + 1] = png.data[sourceOffset + 1];+ output[outputOffset + 2] = png.data[sourceOffset + 2];+ output[outputOffset + 3] = 255;+ continue;+ }+ if (png.channels === 2) {+ output[outputOffset] = png.data[sourceOffset];+ output[outputOffset + 1] = png.data[sourceOffset];+ output[outputOffset + 2] = png.data[sourceOffset];+ output[outputOffset + 3] = png.data[sourceOffset + 1];+ continue;+ }+ if (png.channels === 1) {+ output[outputOffset] = png.data[sourceOffset];+ output[outputOffset + 1] = png.data[sourceOffset];+ output[outputOffset + 2] = png.data[sourceOffset];+ output[outputOffset + 3] = 255;+ continue;+ }+ throw new Error(`Unsupported PNG channel count: ${png.channels}.`);+ }+ return output;+};++const markChangedPixels = ({+ baseline,+ current,+ thresholdSquared,+ ignoreTopNormalizedY,+}: {+ baseline: DecodedRgbaImage;+ current: DecodedRgbaImage;+ thresholdSquared: number;+ ignoreTopNormalizedY: number;+}): DiffMask => {+ const totalPixels = baseline.width * baseline.height;+ const mask = new Uint8Array(totalPixels);+ const ignoredTopRows = Math.min(+ baseline.height,+ Math.ceil(baseline.height * ignoreTopNormalizedY)+ );+ let differentPixels = 0;++ for (let y = ignoredTopRows; y < baseline.height; y++) {+ for (let x = 0; x < baseline.width; x++) {+ const pixelIndex = y * baseline.width + x;+ const offset = pixelIndex * 4;+ const redDelta = current.data[offset] - baseline.data[offset];+ const greenDelta = current.data[offset + 1] - baseline.data[offset + 1];+ const blueDelta = current.data[offset + 2] - baseline.data[offset + 2];+ const rgbDistanceSquared =+ redDelta * redDelta + greenDelta * greenDelta + blueDelta * blueDelta;+ if (rgbDistanceSquared > thresholdSquared) {+ mask[pixelIndex] = 1;+ differentPixels++;+ }+ }+ }++ return { mask, differentPixels };+};++const getChangedRegions = ({+ mask,+ baseline,+ current,+ joinGapPixels,+}: {+ mask: Uint8Array;+ baseline: DecodedRgbaImage;+ current: DecodedRgbaImage;+ joinGapPixels: number;+}): ScreenshotDiffRegion[] => {+ const rawRegions = traceChangeRegions({+ mask,+ width: baseline.width,+ height: baseline.height,+ baselineData: baseline.data,+ currentData: current.data,+ });+ const significantRegions = rawRegions.filter(+ (region) => region.pixelCount >= MIN_REGION_PIXEL_COUNT+ );+ const finalRegions =+ significantRegions.length > MAX_REGIONS_FOR_JOIN+ ? topRegionsByPixelCount(significantRegions, MAX_REGIONS_WITHOUT_JOIN)+ : joinChangeRegions(significantRegions, joinGapPixels);+ return finalRegions+ .map(toDiffRegion)+ .sort(+ (left, right) =>+ left.bounds.y - right.bounds.y || left.bounds.x - right.bounds.x+ );+};++const traceChangeRegions = ({+ mask,+ width,+ height,+ baselineData,+ currentData,+}: {+ mask: Uint8Array;+ width: number;+ height: number;+ baselineData: Uint8Array;+ currentData: Uint8Array;+}) => {+ const visited = new Uint8Array(mask.length);+ const queue = new Int32Array(mask.length);+ const regions: ChangeRegion[] = [];++ for (let startIndex = 0; startIndex < mask.length; startIndex++) {+ if (mask[startIndex] === 0 || visited[startIndex] === 1) {+ continue;+ }+ let queueStart = 0;+ let queueEnd = 0;+ queue[queueEnd++] = startIndex;+ visited[startIndex] = 1;++ const startX = startIndex % width;+ const startY = Math.floor(startIndex / width);+ const region: ChangeRegion = {+ minX: startX,+ minY: startY,+ maxX: startX,+ maxY: startY,+ pixelCount: 0,+ baselineSum: { r: 0, g: 0, b: 0 },+ currentSum: { r: 0, g: 0, b: 0 },+ };++ while (queueStart < queueEnd) {+ const pixelIndex = queue[queueStart++];+ const x = pixelIndex % width;+ const y = Math.floor(pixelIndex / width);+ absorbChangedPixel(+ region,+ x,+ y,+ baselineData,+ currentData,+ pixelIndex * 4+ );++ for (let yOffset = -1; yOffset <= 1; yOffset++) {+ const nextY = y + yOffset;+ if (nextY < 0 || nextY >= height) {+ continue;+ }+ for (let xOffset = -1; xOffset <= 1; xOffset++) {+ if (xOffset === 0 && yOffset === 0) {+ continue;+ }+ const nextX = x + xOffset;+ if (nextX < 0 || nextX >= width) {+ continue;+ }+ const nextIndex = nextY * width + nextX;+ if (mask[nextIndex] === 0 || visited[nextIndex] === 1) {+ continue;+ }+ visited[nextIndex] = 1;+ queue[queueEnd++] = nextIndex;+ }+ }+ }+ regions.push(region);+ }++ return regions;+};++const absorbChangedPixel = (+ region: ChangeRegion,+ x: number,+ y: number,+ baselineData: Uint8Array,+ currentData: Uint8Array,+ offset: number+) => {+ region.minX = Math.min(region.minX, x);+ region.minY = Math.min(region.minY, y);+ region.maxX = Math.max(region.maxX, x);+ region.maxY = Math.max(region.maxY, y);+ region.pixelCount++;+ region.baselineSum.r += baselineData[offset];+ region.baselineSum.g += baselineData[offset + 1];+ region.baselineSum.b += baselineData[offset + 2];+ region.currentSum.r += currentData[offset];+ region.currentSum.g += currentData[offset + 1];+ region.currentSum.b += currentData[offset + 2];+};++const joinChangeRegions = (+ sourceRegions: ChangeRegion[],+ joinGapPixels: number+) => {+ const regions = sourceRegions.map(copyRegion);+ if (regions.length <= 1) {+ return regions;+ }++ for (let index = 0; index < regions.length; index++) {+ let candidateIndex = 0;+ while (candidateIndex < regions.length) {+ if (index === candidateIndex) {+ candidateIndex++;+ continue;+ }+ if (+ shouldJoinRegions(+ regions[index],+ regions[candidateIndex],+ joinGapPixels+ )+ ) {+ regions[index] = combineRegions(+ regions[index],+ regions[candidateIndex]+ );+ regions.splice(candidateIndex, 1);+ if (candidateIndex < index) {+ index--;+ }+ candidateIndex = 0;+ continue;+ }+ candidateIndex++;+ }+ }+ return regions;+};++const shouldJoinRegions = (+ left: ChangeRegion,+ right: ChangeRegion,+ joinGapPixels: number+) => {+ const deltaX =+ left.maxX < right.minX+ ? right.minX - left.maxX - 1+ : right.maxX < left.minX+ ? left.minX - right.maxX - 1+ : 0;+ const deltaY =+ left.maxY < right.minY+ ? right.minY - left.maxY - 1+ : right.maxY < left.minY+ ? left.minY - right.maxY - 1+ : 0;+ if (Math.sqrt(deltaX * deltaX + deltaY * deltaY) <= joinGapPixels) {+ return true;+ }+ return joinGapPixels > 0 && seemsLikeOneTextRow(left, right);+};++const seemsLikeOneTextRow = (left: ChangeRegion, right: ChangeRegion) => {+ const horizontalGap = regionHorizontalGap(left, right);+ if (horizontalGap <= 0) {+ return false;+ }+ const heightLeft = regionHeight(left);+ const heightRight = regionHeight(right);+ const maxHeight = Math.max(heightLeft, heightRight);+ const minHeight = Math.min(heightLeft, heightRight);+ const allowedGap = Math.min(+ HORIZONTAL_TEXT_MERGE_MAX_GAP,+ Math.max(+ HORIZONTAL_TEXT_MERGE_MIN_GAP,+ maxHeight * HORIZONTAL_TEXT_MERGE_HEIGHT_MULTIPLIER+ )+ );+ if (horizontalGap > allowedGap) {+ return false;+ }+ const verticalOverlap =+ Math.min(left.maxY, right.maxY) - Math.max(left.minY, right.minY) + 1;+ if (verticalOverlap > 0 && verticalOverlap / minHeight >= 0.5) {+ return true;+ }+ return (+ Math.abs(regionCenterY(left) - regionCenterY(right)) <=+ Math.max(4, minHeight * 0.6)+ );+};++const copyRegion = (region: ChangeRegion): ChangeRegion => ({+ minX: region.minX,+ minY: region.minY,+ maxX: region.maxX,+ maxY: region.maxY,+ pixelCount: region.pixelCount,+ baselineSum: { ...region.baselineSum },+ currentSum: { ...region.currentSum },+});++const topRegionsByPixelCount = (regions: ChangeRegion[], limit: number) =>+ regions.length <= limit+ ? regions+ : [...regions]+ .sort((left, right) => right.pixelCount - left.pixelCount)+ .slice(0, limit);++const combineRegions = (+ left: ChangeRegion,+ right: ChangeRegion+): ChangeRegion => ({+ minX: Math.min(left.minX, right.minX),+ minY: Math.min(left.minY, right.minY),+ maxX: Math.max(left.maxX, right.maxX),+ maxY: Math.max(left.maxY, right.maxY),+ pixelCount: left.pixelCount + right.pixelCount,+ baselineSum: {+ r: left.baselineSum.r + right.baselineSum.r,+ g: left.baselineSum.g + right.baselineSum.g,+ b: left.baselineSum.b + right.baselineSum.b,+ },+ currentSum: {+ r: left.currentSum.r + right.currentSum.r,+ g: left.currentSum.g + right.currentSum.g,+ b: left.currentSum.b + right.currentSum.b,+ },+});++const toDiffRegion = (region: ChangeRegion): ScreenshotDiffRegion => {+ const baseline = averageRgb(region.baselineSum, region.pixelCount);+ const current = averageRgb(region.currentSum, region.pixelCount);+ const delta = {+ r: current.r - baseline.r,+ g: current.g - baseline.g,+ b: current.b - baseline.b,+ };+ const luminanceDelta = roundToOne(luminance(current) - luminance(baseline));+ return {+ bounds: {+ x: region.minX,+ y: region.minY,+ width: region.maxX - region.minX + 1,+ height: region.maxY - region.minY + 1,+ },+ pixelCount: region.pixelCount,+ averageColor: {+ delta,+ dominantChange: dominantChange(delta, luminanceDelta),+ },+ };+};++const getDiffArtifactPaths = ({+ currentPath,+ outputDir,+}: {+ currentPath: string;+ outputDir: string;+}) => {+ const currentName = path.parse(path.basename(currentPath)).name;+ return {+ diffPath: path.join(outputDir, `${currentName}-diff.png`),+ contextDiffPath: path.join(outputDir, `${currentName}-context-diff.png`),+ };+};++const writeDiffArtifacts = async ({+ baseline,+ current,+ mask,+ regions,+ paths,+ contextDiffScale,+}: {+ baseline: DecodedRgbaImage;+ current: DecodedRgbaImage;+ mask: Uint8Array;+ regions: ScreenshotDiffRegion[];+ paths: { diffPath: string; contextDiffPath: string };+ contextDiffScale: number;+}) => {+ const diffImage = buildContextDiff({ baseline, current, mask });+ drawRegionRectangles(diffImage, regions);+ await writePngFile(paths.diffPath, diffImage);+ await writePngFile(+ paths.contextDiffPath,+ downscalePng(diffImage, contextDiffScale)+ );+};++const buildContextDiff = ({+ baseline,+ current,+ mask,+}: {+ baseline: DecodedRgbaImage;+ current: DecodedRgbaImage;+ mask: Uint8Array;+}) => {+ const output = createPngImage(current.width, current.height);+ for (let pixelIndex = 0; pixelIndex < mask.length; pixelIndex++) {+ const offset = pixelIndex * 4;+ if (mask[pixelIndex] === 1) {+ const baselineLuminance = luminanceFromOffset(baseline.data, offset);+ const currentLuminance = luminanceFromOffset(current.data, offset);+ const color =+ currentLuminance >= baselineLuminance+ ? DIFF_BRIGHTER_COLOR+ : DIFF_DARKER_COLOR;+ writeRgbOffset(output, offset, color);+ continue;+ }+ output.data[offset] = lighten(current.data[offset]);+ output.data[offset + 1] = lighten(current.data[offset + 1]);+ output.data[offset + 2] = lighten(current.data[offset + 2]);+ output.data[offset + 3] = 255;+ }+ return output;+};++const downscalePng = (source: ImageData, scale: number) => {+ const resized = resizeDecodedRgbaImage(+ {+ width: source.width,+ height: source.height,+ data: Uint8Array.from(source.data),+ },+ source.width * scale,+ source.height * scale+ );+ const target = createPngImage(resized.width, resized.height);+ target.data.set(resized.data);+ return target;+};++const drawRegionRectangles = (+ png: ImageData,+ regions: ScreenshotDiffRegion[]+) => {+ for (const region of regions) {+ drawRectangle(+ png,+ region.bounds,+ REGION_RECTANGLE_STROKE_WIDTH,+ REGION_RECTANGLE_COLOR+ );+ }+};++const drawRectangle = (+ png: ImageData,+ bounds: ScreenshotDiffBounds,+ strokeWidth: number,+ color: ScreenshotDiffRgb+) => {+ const minX = Math.max(0, bounds.x);+ const minY = Math.max(0, bounds.y);+ const maxX = Math.min(png.width - 1, bounds.x + bounds.width - 1);+ const maxY = Math.min(png.height - 1, bounds.y + bounds.height - 1);+ if (minX > maxX || minY > maxY) {+ return;+ }+ for (let strokeOffset = 0; strokeOffset < strokeWidth; strokeOffset++) {+ const left = Math.max(0, minX - strokeOffset);+ const right = Math.min(png.width - 1, maxX + strokeOffset);+ const top = Math.max(0, minY - strokeOffset);+ const bottom = Math.min(png.height - 1, maxY + strokeOffset);+ for (let x = left; x <= right; x++) {+ writeRgb(png, x, top, color);+ writeRgb(png, x, bottom, color);+ }+ for (let y = top; y <= bottom; y++) {+ writeRgb(png, left, y, color);+ writeRgb(png, right, y, color);+ }+ }+};++const writePngFile = async (filePath: string, png: ImageData) => {+ await fs.mkdir(path.dirname(filePath), { recursive: true });+ await fs.writeFile(filePath, encode(png));+};++const createPngImage = (width: number, height: number): ImageData => ({+ width,+ height,+ data: new Uint8Array(width * height * 4),+ depth: 8,+ channels: 4,+});++const writeRgb = (+ png: ImageData,+ x: number,+ y: number,+ color: ScreenshotDiffRgb+) => {+ writeRgbOffset(png, (png.width * y + x) * 4, color);+};++const writeRgbOffset = (+ png: ImageData,+ offset: number,+ color: ScreenshotDiffRgb+) => {+ png.data[offset] = color.r;+ png.data[offset + 1] = color.g;+ png.data[offset + 2] = color.b;+ png.data[offset + 3] = 255;+};++const formatScreenshotDiffSummary = (+ result: Omit<ScreenshotDiffResult, "summary">+) => {+ const lines = ["Screenshot diff summary", "", "Overall:"];+ if (result.dimensionMismatch !== undefined) {+ lines.push("- status: dimension_mismatch");+ lines.push(+ `- dimension_mismatch: expected=${formatSize(result.dimensionMismatch.expected)} actual=${formatSize(result.dimensionMismatch.actual)}`+ );+ } else {+ lines.push(+ `- status: ${result.differentPixels > 0 ? "changed" : "unchanged"}`+ );+ lines.push(+ `- pixel_mismatch: ${formatPercentage(result.mismatchPercentage)} - ${describeMismatch(result)}`+ );+ }+ lines.push(+ `- changed_areas: shown=${Math.min(result.regions.length, MAX_SUMMARY_REGIONS)} total=${result.regions.length} omitted=${Math.max(0, result.regions.length - MAX_SUMMARY_REGIONS)}`+ );+ if (result.diffPath !== undefined || result.contextDiffPath !== undefined) {+ lines.push(+ "- diff_images: see diffPath and contextDiffPath in this result"+ );+ lines.push(+ " - legend: green=pixel brighter in current, red=pixel darker in current, yellow rectangles outline changed regions"+ );+ }+ lines.push("", "Regions:");+ for (const [index, region] of result.regions+ .slice(0, MAX_SUMMARY_REGIONS)+ .entries()) {+ lines.push(+ `- Region ${index + 1}: ${formatBounds(region.bounds, result.imageSize)} - changed_pixels=${region.pixelCount}`+ );+ }+ if (result.regions.length === 0) {+ lines.push("- None detected.");+ }+ lines.push("", "Text OCR:");+ lines.push(`- status: ${result.textAnalysis.status}`);+ lines.push(`- provider: ${result.textAnalysis.provider}`);+ lines.push(`- changes: ${result.textAnalysis.changes.length}`);+ for (const [index, change] of result.textAnalysis.changes.entries()) {+ lines.push(+ `- Text ${index + 1}: ${change.kind} confidence=${formatNormalized(change.confidence)}${formatTextChange(change)}`+ );+ }+ if (result.warnings.length > 0) {+ lines.push("", `Warnings: ${result.warnings.join(", ")}`);+ }+ return lines.join("\n");+};++const formatTextChange = (+ change: ScreenshotTextAnalysis["changes"][number]+) => {+ const text =+ change.text ??+ (change.baselineText === undefined || change.currentText === undefined+ ? undefined+ : `${change.baselineText} -> ${change.currentText}`);+ const bounds = change.currentBounds ?? change.baselineBounds;+ return [+ text === undefined ? "" : ` text=${JSON.stringify(text)}`,+ bounds === undefined ? "" : ` bounds=${formatBounds(bounds, undefined)}`,+ change.reasonCodes.length === 0+ ? ""+ : ` reasons=${change.reasonCodes.join(",")}`,+ ].join("");+};++const describeMismatch = ({+ differentPixels,+ mismatchPercentage,+ regions,+}: Pick<+ ScreenshotDiffResult,+ "differentPixels" | "mismatchPercentage" | "regions"+>) => {+ if (differentPixels === 0) {+ return "no pixel change";+ }+ const severity =+ mismatchPercentage < 5+ ? "minor"+ : mismatchPercentage < 10+ ? "moderate"+ : mismatchPercentage < 20+ ? "significant"+ : "large";+ return `${severity} ${regions.length <= 5 ? "localized" : "broad"} visual change`;+};++const formatBounds = (+ bounds: ScreenshotDiffBounds,+ imageSize: ScreenshotDiffSize | undefined+) => {+ if (imageSize === undefined) {+ return `x=${bounds.x} y=${bounds.y} w=${bounds.width} h=${bounds.height}`;+ }+ return [+ `x=${formatNormalized(bounds.x / imageSize.width)}`,+ `y=${formatNormalized(bounds.y / imageSize.height)}`,+ `w=${formatNormalized(bounds.width / imageSize.width)}`,+ `h=${formatNormalized(bounds.height / imageSize.height)}`,+ ].join(" ");+};++const averageRgb = (+ sum: ScreenshotDiffRgb,+ pixelCount: number+): ScreenshotDiffRgb => ({+ r: Math.round(sum.r / pixelCount),+ g: Math.round(sum.g / pixelCount),+ b: Math.round(sum.b / pixelCount),+});++const dominantChange = (+ delta: ScreenshotDiffRgb,+ luminanceDelta: number+): ScreenshotDiffDominantColorChange => {+ if (isUniformBrightnessDelta(delta)) {+ if (luminanceDelta === 0) {+ return { channel: "none", direction: "none", magnitude: 0 };+ }+ return {+ channel: "luminance",+ direction: luminanceDelta > 0 ? "increase" : "decrease",+ magnitude: roundToOne(Math.abs(luminanceDelta)),+ };+ }+ const candidates = [+ { channel: "red" as const, value: delta.r },+ { channel: "green" as const, value: delta.g },+ { channel: "blue" as const, value: delta.b },+ { channel: "luminance" as const, value: luminanceDelta },+ ];+ const winner = candidates.reduce((best, candidate) =>+ Math.abs(candidate.value) > Math.abs(best.value) ? candidate : best+ );+ if (winner.value === 0) {+ return { channel: "none", direction: "none", magnitude: 0 };+ }+ return {+ channel: winner.channel,+ direction: winner.value > 0 ? "increase" : "decrease",+ magnitude: roundToOne(Math.abs(winner.value)),+ };+};++const isUniformBrightnessDelta = (delta: ScreenshotDiffRgb) => {+ if (delta.r === 0 && delta.g === 0 && delta.b === 0) {+ return false;+ }+ const allIncreasing = delta.r > 0 && delta.g > 0 && delta.b > 0;+ const allDecreasing = delta.r < 0 && delta.g < 0 && delta.b < 0;+ if (allIncreasing === false && allDecreasing === false) {+ return false;+ }+ const magnitudes = [Math.abs(delta.r), Math.abs(delta.g), Math.abs(delta.b)];+ return (+ Math.max(...magnitudes) - Math.min(...magnitudes) <=+ UNIFORM_BRIGHTNESS_DELTA_TOLERANCE+ );+};++const regionHorizontalGap = (left: ChangeRegion, right: ChangeRegion) => {+ if (left.maxX < right.minX) {+ return right.minX - left.maxX - 1;+ }+ if (right.maxX < left.minX) {+ return left.minX - right.maxX - 1;+ }+ return 0;+};++const regionHeight = (region: ChangeRegion) => region.maxY - region.minY + 1;++const regionCenterY = (region: ChangeRegion) => (region.minY + region.maxY) / 2;++const luminance = (rgb: ScreenshotDiffRgb) =>+ 0.2126 * rgb.r + 0.7152 * rgb.g + 0.0722 * rgb.b;++const luminanceFromOffset = (data: Uint8Array, offset: number) =>+ 0.2126 * data[offset] + 0.7152 * data[offset + 1] + 0.0722 * data[offset + 2];++const lighten = (value: number) => Math.round(value * 0.55 + 255 * 0.45);++const roundToOne = (value: number) => Math.round(value * 10) / 10;++const formatSize = ({ width, height }: ScreenshotDiffSize) =>+ `${width}x${height}`;++const formatPercentage = (value: number) => `${value.toFixed(2)}%`;++const formatNormalized = (value: number) =>+ Math.min(1, Math.max(0, value)).toFixed(3);diff --git a/packages/project-build/src/visual/screenshot-ocr.test.ts b/packages/project-build/src/visual/screenshot-ocr.test.tsnew file mode 100644index 0000000000..ba91628560--- /dev/null+++ b/packages/project-build/src/visual/screenshot-ocr.test.ts@@ -0,0 +1,76 @@+import { expect, test } from "vitest";+import { parseTesseractTsv } from "./screenshot-ocr";++const header = [+ "level",+ "page_num",+ "block_num",+ "par_num",+ "line_num",+ "word_num",+ "left",+ "top",+ "width",+ "height",+ "conf",+ "text",+].join("\t");++test("parses tesseract TSV words into text blocks", () => {+ const blocks = parseTesseractTsv(+ [+ header,+ "5\t1\t1\t1\t1\t1\t10\t20\t40\t12\t96\tHello",+ "5\t1\t1\t1\t1\t2\t56\t20\t32\t12\t92\tworld",+ "5\t1\t1\t1\t2\t1\t10\t44\t36\t12\t90\tAgain",+ ].join("\n")+ );++ expect(blocks).toEqual([+ {+ text: "Hello world",+ confidence: 0.94,+ bounds: { x: 10, y: 20, width: 78, height: 12 },+ words: [+ expect.objectContaining({ text: "Hello" }),+ expect.objectContaining({ text: "world" }),+ ],+ },+ {+ text: "Again",+ confidence: 0.9,+ bounds: { x: 10, y: 44, width: 36, height: 12 },+ words: [expect.objectContaining({ text: "Again" })],+ },+ ]);+});++test("parses headerless tesseract TSV data", () => {+ const blocks = parseTesseractTsv(+ "5\t1\t1\t1\t1\t1\t10\t20\t40\t12\t96\tHello"+ );++ expect(blocks).toEqual([+ expect.objectContaining({+ text: "Hello",+ bounds: { x: 10, y: 20, width: 40, height: 12 },+ }),+ ]);+});++test("ignores non-word and empty OCR rows", () => {+ const blocks = parseTesseractTsv(+ [+ header,+ "4\t1\t1\t1\t1\t0\t10\t20\t40\t12\t-1\t",+ "5\t1\t1\t1\t1\t1\t10\t20\t40\t12\t96\t...",+ "5\t1\t1\t1\t1\t2\t10\t20\t40\t12\t96\tText",+ ].join("\n")+ );++ expect(blocks).toEqual([+ expect.objectContaining({+ text: "Text",+ }),+ ]);+});diff --git a/packages/project-build/src/visual/screenshot-ocr.ts b/packages/project-build/src/visual/screenshot-ocr.tsnew file mode 100644index 0000000000..7d67caaf49--- /dev/null+++ b/packages/project-build/src/visual/screenshot-ocr.ts@@ -0,0 +1,224 @@+/**+ * Adapted from Software Mansion Argent's screenshot-diff OCR implementation.+ * Source: https://github.com/software-mansion/argent/tree/main/packages/tool-server/src/tools/screenshot-diff+ * License: Apache-2.0+ */++import { execFile } from "node:child_process";+import { promisify } from "node:util";+import type { ScreenshotDiffBounds } from "./screenshot-diff";++const execFileAsync = promisify(execFile);++const OCR_TIMEOUT_MS = 10_000;+const OCR_MAX_BUFFER_BYTES = 32 * 1024 * 1024;+const TESSERACT_BINARY = "tesseract";+const TESSERACT_LANGUAGE = "eng";+const TESSERACT_PSM_SPARSE_TEXT = "11";+const TESSERACT_OEM_LSTM_ONLY = "1";+const REQUIRED_TSV_HEADERS = [+ "level",+ "page_num",+ "block_num",+ "par_num",+ "line_num",+ "word_num",+ "left",+ "top",+ "width",+ "height",+ "conf",+ "text",+] as const;++type TsvHeader = (typeof REQUIRED_TSV_HEADERS)[number];++type OcrWord = {+ text: string;+ confidence: number;+ bounds: ScreenshotDiffBounds;+ blockNum: number;+ parNum: number;+ lineNum: number;+ wordNum: number;+};++export type OcrTextBlock = {+ text: string;+ confidence: number;+ bounds: ScreenshotDiffBounds;+ words: OcrWord[];+};++export type OcrExtractionResult = {+ status: "ok" | "unavailable";+ provider: "tesseract";+ blocks: OcrTextBlock[];+};++export const extractOcrTextBlocks = async (+ imagePath: string+): Promise<OcrExtractionResult> => {+ try {+ const tsv = await recognizeTsv(imagePath);+ return {+ status: "ok",+ provider: "tesseract",+ blocks: parseTesseractTsv(tsv),+ };+ } catch {+ return {+ status: "unavailable",+ provider: "tesseract",+ blocks: [],+ };+ }+};++export const parseTesseractTsv = (tsv: string): OcrTextBlock[] => {+ const [headerLine, ...lines] = tsv.split(/\r?\n/);+ if (headerLine === undefined) {+ return [];+ }++ const normalizedHeaderLine = headerLine.replace(/^\uFEFF/u, "");+ const hasHeader = isHeaderlessTsvDataRow(normalizedHeaderLine) === false;+ const headers = hasHeader+ ? normalizedHeaderLine.split("\t")+ : [...REQUIRED_TSV_HEADERS];+ const dataLines = hasHeader ? lines : [normalizedHeaderLine, ...lines];+ const indexByName = new Map(headers.map((header, index) => [header, index]));+ validateTsvHeaders(indexByName);++ const wordsByLine = new Map<string, OcrWord[]>();+ for (const line of dataLines) {+ if (line.trim() === "") {+ continue;+ }+ const values = line.split("\t");+ const level = readTsvNumber(values, indexByName, "level");+ const text = readTsvString(values, indexByName, "text").trim();+ const confidence = readTsvNumber(values, indexByName, "conf");+ if (level !== 5 || confidence < 0 || isMeaningfulText(text) === false) {+ continue;+ }++ const bounds = {+ x: readTsvNumber(values, indexByName, "left"),+ y: readTsvNumber(values, indexByName, "top"),+ width: readTsvNumber(values, indexByName, "width"),+ height: readTsvNumber(values, indexByName, "height"),+ };+ if (bounds.width <= 0 || bounds.height <= 0) {+ continue;+ }++ const blockNum = readTsvNumber(values, indexByName, "block_num");+ const parNum = readTsvNumber(values, indexByName, "par_num");+ const lineNum = readTsvNumber(values, indexByName, "line_num");+ const wordNum = readTsvNumber(values, indexByName, "word_num");+ const key = [blockNum, parNum, lineNum].join(":");+ const word = {+ text,+ confidence: confidence / 100,+ bounds,+ blockNum,+ parNum,+ lineNum,+ wordNum,+ };+ const existing = wordsByLine.get(key);+ if (existing === undefined) {+ wordsByLine.set(key, [word]);+ } else {+ existing.push(word);+ }+ }++ return Array.from(wordsByLine.values()).map(toTextBlock);+};++const recognizeTsv = async (imagePath: string): Promise<string> => {+ const { stdout } = await execFileAsync(+ TESSERACT_BINARY,+ [+ imagePath,+ "stdout",+ "-l",+ TESSERACT_LANGUAGE,+ "--oem",+ TESSERACT_OEM_LSTM_ONLY,+ "--psm",+ TESSERACT_PSM_SPARSE_TEXT,+ "tsv",+ ],+ { timeout: OCR_TIMEOUT_MS, maxBuffer: OCR_MAX_BUFFER_BYTES }+ );+ return stdout;+};++const toTextBlock = (words: OcrWord[]): OcrTextBlock => {+ const sortedWords = [...words].sort(+ (left, right) => left.wordNum - right.wordNum+ );+ return {+ text: sortedWords.map((word) => word.text).join(" "),+ confidence: average(sortedWords.map((word) => word.confidence)),+ bounds: unionBounds(sortedWords.map((word) => word.bounds)),+ words: sortedWords,+ };+};++const validateTsvHeaders = (indexByName: Map<string, number>) => {+ for (const header of REQUIRED_TSV_HEADERS) {+ if (indexByName.has(header) === false) {+ throw new Error(`Tesseract TSV output is missing "${header}".`);+ }+ }+};++const readTsvNumber = (+ values: string[],+ indexByName: Map<string, number>,+ name: TsvHeader+) => {+ const value = Number(values[indexByName.get(name) ?? -1]);+ if (Number.isFinite(value) === false) {+ throw new Error(`Tesseract TSV field "${name}" is not a finite number.`);+ }+ return value;+};++const readTsvString = (+ values: string[],+ indexByName: Map<string, number>,+ name: TsvHeader+) => values[indexByName.get(name) ?? -1] ?? "";++const isHeaderlessTsvDataRow = (line: string) => {+ const [level, pageNum] = line.split("\t", 2);+ return isFiniteTsvNumber(level) && isFiniteTsvNumber(pageNum);+};++const isFiniteTsvNumber = (value: string | undefined) =>+ value !== undefined && value.trim() !== "" && Number.isFinite(Number(value));++const isMeaningfulText = (text: string) => /[\p{L}\p{N}]/u.test(text);++const unionBounds = (bounds: ScreenshotDiffBounds[]): ScreenshotDiffBounds => {+ const minX = Math.min(...bounds.map((bound) => bound.x));+ const minY = Math.min(...bounds.map((bound) => bound.y));+ const maxX = Math.max(...bounds.map((bound) => bound.x + bound.width));+ const maxY = Math.max(...bounds.map((bound) => bound.y + bound.height));+ return {+ x: minX,+ y: minY,+ width: maxX - minX,+ height: maxY - minY,+ };+};++const average = (values: number[]) =>+ values.length === 0+ ? 0+ : values.reduce((sum, value) => sum + value, 0) / values.length;diff --git a/packages/project-build/src/visual/screenshot-resize.test.ts b/packages/project-build/src/visual/screenshot-resize.test.tsnew file mode 100644index 0000000000..a2a71633eb--- /dev/null+++ b/packages/project-build/src/visual/screenshot-resize.test.ts@@ -0,0 +1,43 @@+import { expect, test } from "vitest";+import {+ normalizeToCommonSize,+ resizeDecodedRgbaImage,+} from "./screenshot-resize";++const createImage = (width: number, height: number) => ({+ width,+ height,+ data: new Uint8Array(width * height * 4).fill(255),+});++test("returns existing images when sizes already match", () => {+ const baseline = createImage(2, 2);+ const current = createImage(2, 2);++ expect(normalizeToCommonSize(baseline, current)).toEqual({+ baseline,+ current,+ });+});++test("normalizes same-aspect images to the smaller size", () => {+ const baseline = createImage(2, 2);+ const current = createImage(4, 4);++ expect(normalizeToCommonSize(baseline, current)).toEqual({+ baseline,+ current: expect.objectContaining({ width: 2, height: 2 }),+ });+});++test("does not normalize different aspect ratios", () => {+ expect(normalizeToCommonSize(createImage(2, 2), createImage(3, 2))).toBe(+ undefined+ );+});++test("resizes to at least one pixel", () => {+ expect(resizeDecodedRgbaImage(createImage(2, 2), 0, 0)).toEqual(+ expect.objectContaining({ width: 1, height: 1 })+ );+});diff --git a/packages/project-build/src/visual/screenshot-resize.ts b/packages/project-build/src/visual/screenshot-resize.tsnew file mode 100644index 0000000000..b1bca1ac62--- /dev/null+++ b/packages/project-build/src/visual/screenshot-resize.ts@@ -0,0 +1,206 @@+/**+ * Adapted from Software Mansion Argent's screenshot-diff resize helpers.+ * Source: https://github.com/software-mansion/argent/tree/main/packages/tool-server/src/tools/screenshot-diff+ * License: Apache-2.0+ */++export type DecodedRgbaImage = {+ width: number;+ height: number;+ data: Uint8Array;+};++const ASPECT_RATIO_TOLERANCE = 0.01;+const LANCZOS3_RADIUS = 3;+const LANCZOS3_EPSILON = 1e-9;++export const normalizeToCommonSize = (+ baseline: DecodedRgbaImage,+ current: DecodedRgbaImage+): { baseline: DecodedRgbaImage; current: DecodedRgbaImage } | undefined => {+ if (baseline.width === current.width && baseline.height === current.height) {+ return { baseline, current };+ }++ if (aspectRatiosMatch(baseline, current) === false) {+ return undefined;+ }++ const baselineArea = baseline.width * baseline.height;+ const currentArea = current.width * current.height;++ if (baselineArea <= currentArea) {+ return {+ baseline,+ current: resizeDecodedRgbaImage(current, baseline.width, baseline.height),+ };+ }++ return {+ baseline: resizeDecodedRgbaImage(baseline, current.width, current.height),+ current,+ };+};++export const resizeDecodedRgbaImage = (+ source: DecodedRgbaImage,+ width: number,+ height: number+): DecodedRgbaImage => {+ const targetWidth = Math.max(1, Math.round(width));+ const targetHeight = Math.max(1, Math.round(height));+ if (targetWidth === source.width && targetHeight === source.height) {+ return {+ width: source.width,+ height: source.height,+ data: Uint8Array.from(source.data),+ };+ }++ const horizontal = buildLanczos3AxisWeights(source.width, targetWidth);+ const vertical = buildLanczos3AxisWeights(source.height, targetHeight);+ const intermediate = new Float32Array(targetWidth * source.height * 4);++ for (let y = 0; y < source.height; y++) {+ const rowOffset = y * source.width * 4;+ const targetRowOffset = y * targetWidth * 4;+ for (let x = 0; x < targetWidth; x++) {+ const { start, weights } = horizontal[x];+ let r = 0;+ let g = 0;+ let b = 0;+ let a = 0;+ const baseOffset = rowOffset + start * 4;+ for (let index = 0; index < weights.length; index++) {+ const sampleOffset = baseOffset + index * 4;+ const weight = weights[index];+ r += source.data[sampleOffset] * weight;+ g += source.data[sampleOffset + 1] * weight;+ b += source.data[sampleOffset + 2] * weight;+ a += source.data[sampleOffset + 3] * weight;+ }+ const targetOffset = targetRowOffset + x * 4;+ intermediate[targetOffset] = r;+ intermediate[targetOffset + 1] = g;+ intermediate[targetOffset + 2] = b;+ intermediate[targetOffset + 3] = a;+ }+ }++ const output = new Uint8Array(targetWidth * targetHeight * 4);+ const rowStride = targetWidth * 4;+ for (let y = 0; y < targetHeight; y++) {+ const { start, weights } = vertical[y];+ const targetRowOffset = y * rowStride;+ for (let x = 0; x < targetWidth; x++) {+ let r = 0;+ let g = 0;+ let b = 0;+ let a = 0;+ const columnOffset = start * rowStride + x * 4;+ for (let index = 0; index < weights.length; index++) {+ const sampleOffset = columnOffset + index * rowStride;+ const weight = weights[index];+ r += intermediate[sampleOffset] * weight;+ g += intermediate[sampleOffset + 1] * weight;+ b += intermediate[sampleOffset + 2] * weight;+ a += intermediate[sampleOffset + 3] * weight;+ }+ const targetOffset = targetRowOffset + x * 4;+ output[targetOffset] = clampToByte(r);+ output[targetOffset + 1] = clampToByte(g);+ output[targetOffset + 2] = clampToByte(b);+ output[targetOffset + 3] = clampToByte(a);+ }+ }++ return { width: targetWidth, height: targetHeight, data: output };+};++type ResampleAxisWeights = {+ start: number;+ weights: Float32Array;+};++const aspectRatiosMatch = (left: DecodedRgbaImage, right: DecodedRgbaImage) => {+ if (+ left.width <= 0 ||+ left.height <= 0 ||+ right.width <= 0 ||+ right.height <= 0+ ) {+ return false;+ }+ const leftAspect = left.width / left.height;+ const rightAspect = right.width / right.height;+ const largest = Math.max(leftAspect, rightAspect);+ if (largest === 0) {+ return false;+ }+ return Math.abs(leftAspect - rightAspect) / largest <= ASPECT_RATIO_TOLERANCE;+};++const buildLanczos3AxisWeights = (+ sourceSize: number,+ targetSize: number+): ResampleAxisWeights[] => {+ const scale = targetSize / sourceSize;+ const filterScale = scale < 1 ? scale : 1;+ const supportInSource = LANCZOS3_RADIUS / filterScale;+ const axis: ResampleAxisWeights[] = new Array(targetSize);++ for (let index = 0; index < targetSize; index++) {+ const center = (index + 0.5) / scale - 0.5;+ const start = Math.max(+ 0,+ Math.ceil(center - supportInSource - LANCZOS3_EPSILON)+ );+ const end = Math.min(+ sourceSize - 1,+ Math.floor(center + supportInSource + LANCZOS3_EPSILON)+ );+ const length = Math.max(1, end - start + 1);+ const weights = new Float32Array(length);+ let sum = 0;+ for (let offset = 0; offset < length; offset++) {+ const sampleIndex = start + offset;+ const weight = lanczos3Kernel((sampleIndex - center) * filterScale);+ weights[offset] = weight;+ sum += weight;+ }+ if (sum !== 0) {+ const inverseSum = 1 / sum;+ for (let offset = 0; offset < length; offset++) {+ weights[offset] *= inverseSum;+ }+ }+ axis[index] = { start, weights };+ }+ return axis;+};++const lanczos3Kernel = (value: number) => {+ if (value === 0) {+ return 1;+ }+ if (value <= -LANCZOS3_RADIUS || value >= LANCZOS3_RADIUS) {+ return 0;+ }+ const piValue = Math.PI * value;+ return (+ (LANCZOS3_RADIUS *+ Math.sin(piValue) *+ Math.sin(piValue / LANCZOS3_RADIUS)) /+ (piValue * piValue)+ );+};++const clampToByte = (value: number) => {+ if (value <= 0) {+ return 0;+ }+ if (value >= 255) {+ return 255;+ }+ return Math.round(value);+};diff --git a/packages/project-build/src/visual/screenshot-text-diff.test.ts b/packages/project-build/src/visual/screenshot-text-diff.test.tsnew file mode 100644index 0000000000..31a052c285--- /dev/null+++ b/packages/project-build/src/visual/screenshot-text-diff.test.ts@@ -0,0 +1,134 @@+import { expect, test } from "vitest";+import {+ analyzeTextRegions,+ normalizeTextForDiff,+} from "./screenshot-text-diff";+import { createPng, paintRect } from "./screenshot.test-utils";+import type { DecodedRgbaImage } from "./screenshot-resize";++const textBlock = ({+ text,+ x,+ y,+ width = 60,+ height = 12,+ confidence = 0.98,+}: {+ text: string;+ x: number;+ y: number;+ width?: number;+ height?: number;+ confidence?: number;+}) => ({+ text,+ confidence,+ bounds: { x, y, width, height },+ words: [+ {+ text,+ confidence,+ bounds: { x, y, width, height },+ blockNum: 1,+ parNum: 1,+ lineNum: 1,+ wordNum: 1,+ },+ ],+});++const toDecodedImage = (+ image: ReturnType<typeof createPng>+): DecodedRgbaImage => ({+ width: image.width,+ height: image.height,+ data: Uint8Array.from(image.data),+});++test("normalizes OCR text for stable matching", () => {+ expect(normalizeTextForDiff("Save 25% & Launch")).toBe("save 25% and launch");+ expect(normalizeTextForDiff("“Hello”—World")).toBe("hello world");+});++test("detects moved text", () => {+ const result = analyzeTextRegions({+ baselineRegions: [textBlock({ text: "Launch faster", x: 10, y: 20 })],+ currentRegions: [textBlock({ text: "Launch faster", x: 38, y: 56 })],+ });++ expect(result.status).toBe("ok");+ expect(result.changes).toEqual([+ expect.objectContaining({+ kind: "moved",+ text: "Launch faster",+ delta: { x: 28, y: 36, width: 0, height: 0 },+ reasonCodes: ["exact_normalized_match", "position_delta"],+ }),+ ]);+});++test("detects appeared, disappeared, and changed text", () => {+ const result = analyzeTextRegions({+ baselineRegions: [+ textBlock({ text: "Old heading", x: 10, y: 20 }),+ textBlock({ text: "Remove me", x: 10, y: 48 }),+ ],+ currentRegions: [+ textBlock({ text: "New heading", x: 10, y: 20 }),+ textBlock({ text: "Add me", x: 10, y: 80 }),+ ],+ });++ expect(result.changes).toEqual([+ expect.objectContaining({+ kind: "content_changed",+ baselineText: "Old heading",+ currentText: "New heading",+ }),+ expect.objectContaining({+ kind: "disappeared",+ text: "Remove me",+ }),+ expect.objectContaining({+ kind: "appeared",+ text: "Add me",+ }),+ ]);+});++test("detects font-style geometry changes for matched text", () => {+ const baseline = createPng(120, 60, { r: 255, g: 255, b: 255 });+ const current = createPng(120, 60, { r: 255, g: 255, b: 255 });+ paintRect(+ baseline,+ { x: 14, y: 23, width: 42, height: 4 },+ { r: 0, g: 0, b: 0 }+ );+ paintRect(+ current,+ { x: 14, y: 23, width: 62, height: 8 },+ { r: 200, g: 40, b: 40 }+ );++ const result = analyzeTextRegions({+ baselineRegions: [+ textBlock({ text: "Button", x: 10, y: 20, width: 50, height: 10 }),+ ],+ currentRegions: [+ textBlock({ text: "Button", x: 10, y: 20, width: 70, height: 14 }),+ ],+ baselineImage: toDecodedImage(baseline),+ currentImage: toDecodedImage(current),+ });++ expect(result.changes).toEqual([+ expect.objectContaining({+ kind: "font_changed",+ text: "Button",+ reasonCodes: expect.arrayContaining([+ "bbox_geometry_delta",+ "text_color_delta",+ ]),+ }),+ ]);+});diff --git a/packages/project-build/src/visual/screenshot-text-diff.ts b/packages/project-build/src/visual/screenshot-text-diff.tsnew file mode 100644index 0000000000..451d185fb1--- /dev/null+++ b/packages/project-build/src/visual/screenshot-text-diff.ts@@ -0,0 +1,775 @@+/**+ * Adapted from Software Mansion Argent's screenshot-diff text checks.+ * Source: https://github.com/software-mansion/argent/tree/main/packages/tool-server/src/tools/screenshot-diff+ * License: Apache-2.0+ */++import { extractOcrTextBlocks, type OcrTextBlock } from "./screenshot-ocr";+import type {+ ScreenshotDiffBounds,+ ScreenshotDiffRgb,+} from "./screenshot-diff";+import type { DecodedRgbaImage } from "./screenshot-resize";++export type ScreenshotTextChangeKind =+ | "moved"+ | "appeared"+ | "disappeared"+ | "content_changed"+ | "font_changed";++export type ScreenshotTextReasonCode =+ | "exact_normalized_match"+ | "ocr_noise_tolerated"+ | "position_delta"+ | "missing_in_current"+ | "missing_in_baseline"+ | "same_location"+ | "text_similarity"+ | "normalized_text_changed"+ | "bbox_geometry_delta"+ | "glyph_density_delta"+ | "text_color_delta"+ | "text_contrast_delta";++export type ScreenshotTextChange = {+ kind: ScreenshotTextChangeKind;+ text?: string;+ baselineText?: string;+ currentText?: string;+ normalizedText?: string;+ baselineBounds?: ScreenshotDiffBounds;+ currentBounds?: ScreenshotDiffBounds;+ delta?: {+ x: number;+ y: number;+ width: number;+ height: number;+ };+ font?: {+ confidence: number;+ reasonCodes: readonly ScreenshotTextReasonCode[];+ metrics: {+ widthRatio: number;+ heightRatio: number;+ glyphDensityDelta: number;+ textColorDelta: ScreenshotDiffRgb;+ textColorDistance: number;+ textContrastDelta: number;+ };+ };+ confidence: number;+ source: "ocr";+ reasonCodes: readonly ScreenshotTextReasonCode[];+};++export type ScreenshotTextAnalysis = {+ status: "ok" | "unavailable" | "skipped";+ provider: "tesseract";+ changes: readonly ScreenshotTextChange[];+};++type NormalizedTextRegion = OcrTextBlock & {+ normalizedText: string;+ matchKey: string;+};++type PairCandidate = {+ baselineIndex: number;+ currentIndex: number;+ score: number;+ exact: boolean;+};++type ContentCandidate = {+ baselineIndex: number;+ currentIndex: number;+ score: number;+ reasonCodes: ScreenshotTextReasonCode[];+};++type FontFeatures = {+ glyphDensity: number;+ textColor: ScreenshotDiffRgb;+ textContrast: number;+};++const MOVE_THRESHOLD_PX = 3;+const LOCATION_OVERLAP_THRESHOLD = 0.45;+const LOCATION_CENTER_DISTANCE_PX = 18;+const FUZZY_SAME_TEXT_CENTER_DISTANCE_PX = 60;+const MAX_TEXT_CHANGES = 10;+const DEFAULT_TEXT_CHANGE_MIN_CONFIDENCE = 0.7;++export const analyzeScreenshotTextChanges = async ({+ baselinePath,+ currentPath,+ hasPixelDiff,+ baselineImage,+ currentImage,+ ignoreTopPixels,+ textChangeMinConfidence = DEFAULT_TEXT_CHANGE_MIN_CONFIDENCE,+}: {+ baselinePath: string;+ currentPath: string;+ hasPixelDiff: boolean;+ baselineImage: DecodedRgbaImage;+ currentImage: DecodedRgbaImage;+ ignoreTopPixels: number;+ textChangeMinConfidence?: number;+}): Promise<ScreenshotTextAnalysis> => {+ if (hasPixelDiff === false) {+ return {+ status: "skipped",+ provider: "tesseract",+ changes: [],+ };+ }++ const [baselineOcr, currentOcr] = await Promise.all([+ extractOcrTextBlocks(baselinePath),+ extractOcrTextBlocks(currentPath),+ ]);+ if (baselineOcr.status !== "ok" || currentOcr.status !== "ok") {+ return {+ status: "unavailable",+ provider: "tesseract",+ changes: [],+ };+ }++ return analyzeTextRegions({+ baselineRegions: baselineOcr.blocks,+ currentRegions: currentOcr.blocks,+ baselineImage,+ currentImage,+ ignoreTopPixels,+ textChangeMinConfidence,+ });+};++export const analyzeTextRegions = ({+ baselineRegions,+ currentRegions,+ baselineImage,+ currentImage,+ ignoreTopPixels = 0,+ textChangeMinConfidence = DEFAULT_TEXT_CHANGE_MIN_CONFIDENCE,+}: {+ baselineRegions: readonly OcrTextBlock[];+ currentRegions: readonly OcrTextBlock[];+ baselineImage?: DecodedRgbaImage;+ currentImage?: DecodedRgbaImage;+ ignoreTopPixels?: number;+ textChangeMinConfidence?: number;+}): ScreenshotTextAnalysis => {+ validateTextChangeMinConfidence(textChangeMinConfidence);++ const baseline = normalizeRegions(+ filterRegionsByTopCutoff(baselineRegions, ignoreTopPixels)+ );+ const current = normalizeRegions(+ filterRegionsByTopCutoff(currentRegions, ignoreTopPixels)+ );+ const usedBaseline = new Set<number>();+ const usedCurrent = new Set<number>();+ const changes: ScreenshotTextChange[] = [];++ for (const pair of pairSameTextRegions(baseline, current)) {+ if (+ usedBaseline.has(pair.baselineIndex) ||+ usedCurrent.has(pair.currentIndex)+ ) {+ continue;+ }+ usedBaseline.add(pair.baselineIndex);+ usedCurrent.add(pair.currentIndex);++ const baselineRegion = baseline[pair.baselineIndex];+ const currentRegion = current[pair.currentIndex];+ const delta = boundsDelta(baselineRegion.bounds, currentRegion.bounds);+ const reasonCodes: ScreenshotTextReasonCode[] = [+ pair.exact ? "exact_normalized_match" : "ocr_noise_tolerated",+ ];++ if (isMeaningfulMove(delta)) {+ changes.push({+ kind: "moved",+ text: baselineRegion.text,+ normalizedText: baselineRegion.normalizedText,+ baselineBounds: baselineRegion.bounds,+ currentBounds: currentRegion.bounds,+ delta,+ confidence: clampConfidence(+ Math.min(baselineRegion.confidence, currentRegion.confidence) *+ (pair.exact ? 0.96 : 0.78)+ ),+ source: "ocr",+ reasonCodes: [...reasonCodes, "position_delta"],+ });+ }++ const font = detectFontChange({+ baselineImage,+ currentImage,+ baselineRegion,+ currentRegion,+ });+ if (font !== undefined) {+ changes.push({+ kind: "font_changed",+ text: baselineRegion.text,+ normalizedText: baselineRegion.normalizedText,+ baselineBounds: baselineRegion.bounds,+ currentBounds: currentRegion.bounds,+ delta,+ font,+ confidence: font.confidence,+ source: "ocr",+ reasonCodes: [...reasonCodes, ...font.reasonCodes],+ });+ }+ }++ for (const pair of pairChangedTextRegions(+ baseline,+ current,+ usedBaseline,+ usedCurrent+ )) {+ if (+ usedBaseline.has(pair.baselineIndex) ||+ usedCurrent.has(pair.currentIndex)+ ) {+ continue;+ }+ usedBaseline.add(pair.baselineIndex);+ usedCurrent.add(pair.currentIndex);+ const baselineRegion = baseline[pair.baselineIndex];+ const currentRegion = current[pair.currentIndex];+ changes.push({+ kind: "content_changed",+ baselineText: baselineRegion.text,+ currentText: currentRegion.text,+ baselineBounds: baselineRegion.bounds,+ currentBounds: currentRegion.bounds,+ delta: boundsDelta(baselineRegion.bounds, currentRegion.bounds),+ confidence: clampConfidence(+ Math.min(baselineRegion.confidence, currentRegion.confidence) *+ pair.score+ ),+ source: "ocr",+ reasonCodes: pair.reasonCodes,+ });+ }++ for (let index = 0; index < baseline.length; index++) {+ if (usedBaseline.has(index)) {+ continue;+ }+ const region = baseline[index];+ changes.push({+ kind: "disappeared",+ text: region.text,+ normalizedText: region.normalizedText,+ baselineBounds: region.bounds,+ confidence: clampConfidence(region.confidence * 0.78),+ source: "ocr",+ reasonCodes: ["missing_in_current"],+ });+ }++ for (let index = 0; index < current.length; index++) {+ if (usedCurrent.has(index)) {+ continue;+ }+ const region = current[index];+ changes.push({+ kind: "appeared",+ text: region.text,+ normalizedText: region.normalizedText,+ currentBounds: region.bounds,+ confidence: clampConfidence(region.confidence * 0.78),+ source: "ocr",+ reasonCodes: ["missing_in_baseline"],+ });+ }++ return {+ status: "ok",+ provider: "tesseract",+ changes: changes+ .filter((change) => change.confidence >= textChangeMinConfidence)+ .sort(+ (left, right) =>+ changeTop(left) - changeTop(right) ||+ changeLeft(left) - changeLeft(right)+ )+ .slice(0, MAX_TEXT_CHANGES),+ };+};++export const normalizeTextForDiff = (text: string) => {+ const normalized = text+ .normalize("NFKC")+ .replace(/[\u2018\u2019\u201A\u201B]/g, "'")+ .replace(/[\u201C\u201D\u201E\u201F]/g, '"')+ .replace(/[\u2010-\u2015]/g, "-")+ .toLocaleLowerCase("en-US")+ .replace(/&/g, " and ");++ return restoreValueSymbols(+ protectValueSymbols(normalized)+ .replace(/[^\p{L}\p{N}]+/gu, " ")+ .replace(/\s+/g, " ")+ .trim()+ );+};++const normalizeRegions = (+ regions: readonly OcrTextBlock[]+): NormalizedTextRegion[] =>+ regions+ .map((region) => {+ const normalizedText = normalizeTextForDiff(region.text);+ return {+ ...region,+ confidence: clampConfidence(region.confidence),+ normalizedText,+ matchKey: ocrNoiseKey(normalizedText),+ };+ })+ .filter((region) => region.normalizedText.length > 0);++const filterRegionsByTopCutoff = (+ regions: readonly OcrTextBlock[],+ ignoreTopPixels: number+) =>+ ignoreTopPixels <= 0+ ? regions+ : regions.filter(+ (region) => region.bounds.y + region.bounds.height > ignoreTopPixels+ );++const pairSameTextRegions = (+ baseline: readonly NormalizedTextRegion[],+ current: readonly NormalizedTextRegion[]+): PairCandidate[] => {+ const candidates: PairCandidate[] = [];+ for (+ let baselineIndex = 0;+ baselineIndex < baseline.length;+ baselineIndex+++ ) {+ for (let currentIndex = 0; currentIndex < current.length; currentIndex++) {+ const left = baseline[baselineIndex];+ const right = current[currentIndex];+ const exact = left.normalizedText === right.normalizedText;+ const similarity = normalizedTextSimilarity(+ left.matchKey,+ right.matchKey+ );+ const distance = centerDistance(left.bounds, right.bounds);+ const fuzzy =+ exact === false &&+ valueTokensCompatible(left.normalizedText, right.normalizedText) &&+ distance <= FUZZY_SAME_TEXT_CENTER_DISTANCE_PX &&+ similarity >= fuzzyThreshold(left.matchKey, right.matchKey);+ if (exact === false && fuzzy === false) {+ continue;+ }+ candidates.push({+ baselineIndex,+ currentIndex,+ exact,+ score:+ (exact ? 100 : 70 + similarity * 10) - Math.min(25, distance / 8),+ });+ }+ }+ return candidates.sort((left, right) => right.score - left.score);+};++const pairChangedTextRegions = (+ baseline: readonly NormalizedTextRegion[],+ current: readonly NormalizedTextRegion[],+ usedBaseline: Set<number>,+ usedCurrent: Set<number>+): ContentCandidate[] => {+ const candidates: ContentCandidate[] = [];+ for (+ let baselineIndex = 0;+ baselineIndex < baseline.length;+ baselineIndex+++ ) {+ if (usedBaseline.has(baselineIndex)) {+ continue;+ }+ for (let currentIndex = 0; currentIndex < current.length; currentIndex++) {+ if (usedCurrent.has(currentIndex)) {+ continue;+ }+ const left = baseline[baselineIndex];+ const right = current[currentIndex];+ if (left.normalizedText === right.normalizedText) {+ continue;+ }++ const reasonCodes: ScreenshotTextReasonCode[] = [+ "normalized_text_changed",+ ];+ const overlap = intersectionOverUnion(left.bounds, right.bounds);+ const distance = centerDistance(left.bounds, right.bounds);+ const similarity = normalizedTextSimilarity(+ left.matchKey,+ right.matchKey+ );+ let score = 0;+ if (overlap >= LOCATION_OVERLAP_THRESHOLD) {+ score = 0.84 + overlap * 0.1;+ reasonCodes.push("same_location");+ } else if (distance <= LOCATION_CENTER_DISTANCE_PX) {+ score = 0.74;+ reasonCodes.push("same_location");+ } else if (similarity >= 0.65 && distance <= 60) {+ score = 0.64 + similarity * 0.1;+ reasonCodes.push("text_similarity");+ }+ if (score === 0) {+ continue;+ }+ candidates.push({ baselineIndex, currentIndex, score, reasonCodes });+ }+ }+ return candidates.sort((left, right) => right.score - left.score);+};++const detectFontChange = ({+ baselineImage,+ currentImage,+ baselineRegion,+ currentRegion,+}: {+ baselineImage: DecodedRgbaImage | undefined;+ currentImage: DecodedRgbaImage | undefined;+ baselineRegion: OcrTextBlock;+ currentRegion: OcrTextBlock;+}): ScreenshotTextChange["font"] | undefined => {+ if (baselineImage === undefined || currentImage === undefined) {+ return undefined;+ }+ const baselineFeatures = extractFontFeatures(+ baselineImage,+ baselineRegion.bounds+ );+ const currentFeatures = extractFontFeatures(+ currentImage,+ currentRegion.bounds+ );+ if (baselineFeatures === undefined || currentFeatures === undefined) {+ return undefined;+ }++ const widthRatio = relativeDelta(+ baselineRegion.bounds.width,+ currentRegion.bounds.width+ );+ const heightRatio = relativeDelta(+ baselineRegion.bounds.height,+ currentRegion.bounds.height+ );+ const glyphDensityDelta = Math.abs(+ currentFeatures.glyphDensity - baselineFeatures.glyphDensity+ );+ const textColorDelta = {+ r: currentFeatures.textColor.r - baselineFeatures.textColor.r,+ g: currentFeatures.textColor.g - baselineFeatures.textColor.g,+ b: currentFeatures.textColor.b - baselineFeatures.textColor.b,+ };+ const textColorDistance = colorDistance(textColorDelta);+ const textContrastDelta = Math.abs(+ currentFeatures.textContrast - baselineFeatures.textContrast+ );+ const reasonCodes: ScreenshotTextReasonCode[] = [];+ if (widthRatio > 0.08 || heightRatio > 0.08) {+ reasonCodes.push("bbox_geometry_delta");+ }+ if (glyphDensityDelta > 0.045) {+ reasonCodes.push("glyph_density_delta");+ }+ if (textColorDistance > 32) {+ reasonCodes.push("text_color_delta");+ }+ if (textContrastDelta > 24) {+ reasonCodes.push("text_contrast_delta");+ }+ if (reasonCodes.length === 0) {+ return undefined;+ }++ const rawScore =+ Math.min(1, Math.max(widthRatio, heightRatio) / 0.18) * 0.25 ++ Math.min(1, glyphDensityDelta / 0.09) * 0.3 ++ Math.min(1, textColorDistance / 96) * 0.25 ++ Math.min(1, textContrastDelta / 64) * 0.2;+ return {+ confidence: clampConfidence(Math.max(0.72, rawScore)),+ reasonCodes,+ metrics: {+ widthRatio: round(widthRatio),+ heightRatio: round(heightRatio),+ glyphDensityDelta: round(glyphDensityDelta),+ textColorDelta,+ textColorDistance: round(textColorDistance),+ textContrastDelta: round(textContrastDelta),+ },+ };+};++const extractFontFeatures = (+ image: DecodedRgbaImage,+ bounds: ScreenshotDiffBounds+): FontFeatures | undefined => {+ const clamped = clampBounds(bounds, image.width, image.height);+ if (clamped.width <= 0 || clamped.height <= 0) {+ return undefined;+ }++ const borderLuminance: number[] = [];+ for (let y = clamped.y; y < clamped.y + clamped.height; y++) {+ for (let x = clamped.x; x < clamped.x + clamped.width; x++) {+ if (+ x === clamped.x ||+ y === clamped.y ||+ x === clamped.x + clamped.width - 1 ||+ y === clamped.y + clamped.height - 1+ ) {+ borderLuminance.push(readLuminance(image, x, y));+ }+ }+ }+ const background = median(borderLuminance);+ const inkThreshold = 24;+ let glyphPixels = 0;+ let maxContrast = 0;+ const colorSum = { r: 0, g: 0, b: 0 };+ for (let y = clamped.y; y < clamped.y + clamped.height; y++) {+ for (let x = clamped.x; x < clamped.x + clamped.width; x++) {+ const luminance = readLuminance(image, x, y);+ const contrast = Math.abs(luminance - background);+ if (contrast < inkThreshold) {+ continue;+ }+ const color = readRgb(image, x, y);+ glyphPixels++;+ maxContrast = Math.max(maxContrast, contrast);+ colorSum.r += color.r;+ colorSum.g += color.g;+ colorSum.b += color.b;+ }+ }+ if (glyphPixels === 0) {+ return undefined;+ }+ return {+ glyphDensity: glyphPixels / (clamped.width * clamped.height),+ textColor: {+ r: Math.round(colorSum.r / glyphPixels),+ g: Math.round(colorSum.g / glyphPixels),+ b: Math.round(colorSum.b / glyphPixels),+ },+ textContrast: maxContrast,+ };+};++const protectValueSymbols = (text: string) =>+ text+ .replace(/(\p{N})\s*%/gu, "$1ARGENTPERCENTTOKEN")+ .replace(/([$\u20ac\u00a3])\s*(\p{N})/gu, "$1$2");++const restoreValueSymbols = (text: string) =>+ text.replace(/ARGENTPERCENTTOKEN/g, "%");++const ocrNoiseKey = (text: string) =>+ text+ .replace(/[0]/g, "o")+ .replace(/[1|]/g, "l")+ .replace(/[3]/g, "e")+ .replace(/[5]/g, "s")+ .replace(/[8]/g, "b")+ .replace(/\brn/g, "m");++const fuzzyThreshold = (left: string, right: string) => {+ const length = Math.max(left.length, right.length);+ if (length <= 4) {+ return Number.POSITIVE_INFINITY;+ }+ return length <= 8 ? 0.86 : 0.82;+};++const valueTokensCompatible = (left: string, right: string) => {+ const leftTokens = valueTokens(left);+ const rightTokens = valueTokens(right);+ return (+ (leftTokens.length === 0 && rightTokens.length === 0) ||+ (leftTokens.length === rightTokens.length &&+ leftTokens.every((token, index) => token === rightTokens[index]))+ );+};++const valueTokens = (text: string) =>+ text.match(/(?<!\p{L})(?:[$€£+\-/])?\p{N}+(?:[.,]\p{N}+)?%?(?!\p{L})/gu) ??+ [];++const normalizedTextSimilarity = (left: string, right: string) =>+ left === right+ ? 1+ : 1 -+ levenshteinDistance(left, right) / Math.max(left.length, right.length, 1);++const levenshteinDistance = (left: string, right: string) => {+ const previous = new Array<number>(right.length + 1);+ const current = new Array<number>(right.length + 1);+ for (let index = 0; index <= right.length; index++) {+ previous[index] = index;+ }++ for (let leftIndex = 1; leftIndex <= left.length; leftIndex++) {+ current[0] = leftIndex;+ for (let rightIndex = 1; rightIndex <= right.length; rightIndex++) {+ const cost = left[leftIndex - 1] === right[rightIndex - 1] ? 0 : 1;+ current[rightIndex] = Math.min(+ current[rightIndex - 1] + 1,+ previous[rightIndex] + 1,+ previous[rightIndex - 1] + cost+ );+ }+ for (let index = 0; index <= right.length; index++) {+ previous[index] = current[index];+ }+ }+ return previous[right.length];+};++const boundsDelta = (+ baseline: ScreenshotDiffBounds,+ current: ScreenshotDiffBounds+) => ({+ x: current.x - baseline.x,+ y: current.y - baseline.y,+ width: current.width - baseline.width,+ height: current.height - baseline.height,+});++const isMeaningfulMove = (delta: ReturnType<typeof boundsDelta>) =>+ Math.abs(delta.x) >= MOVE_THRESHOLD_PX ||+ Math.abs(delta.y) >= MOVE_THRESHOLD_PX;++const intersectionOverUnion = (+ left: ScreenshotDiffBounds,+ right: ScreenshotDiffBounds+) => {+ const x1 = Math.max(left.x, right.x);+ const y1 = Math.max(left.y, right.y);+ const x2 = Math.min(left.x + left.width, right.x + right.width);+ const y2 = Math.min(left.y + left.height, right.y + right.height);+ const intersection = Math.max(0, x2 - x1) * Math.max(0, y2 - y1);+ if (intersection === 0) {+ return 0;+ }+ return (+ intersection /+ (left.width * left.height + right.width * right.height - intersection)+ );+};++const centerDistance = (+ left: ScreenshotDiffBounds,+ right: ScreenshotDiffBounds+) => {+ const leftCenter = {+ x: left.x + left.width / 2,+ y: left.y + left.height / 2,+ };+ const rightCenter = {+ x: right.x + right.width / 2,+ y: right.y + right.height / 2,+ };+ return Math.sqrt(+ (leftCenter.x - rightCenter.x) ** 2 + (leftCenter.y - rightCenter.y) ** 2+ );+};++const changeTop = (change: ScreenshotTextChange) =>+ (change.baselineBounds ?? change.currentBounds)?.y ?? 0;++const changeLeft = (change: ScreenshotTextChange) =>+ (change.baselineBounds ?? change.currentBounds)?.x ?? 0;++const validateTextChangeMinConfidence = (minConfidence: number) => {+ if (+ Number.isFinite(minConfidence) === false ||+ minConfidence < 0 ||+ minConfidence > 1+ ) {+ throw new Error(+ `textChangeMinConfidence must be a finite number between 0 and 1, received ${minConfidence}`+ );+ }+};++const clampBounds = (+ bounds: ScreenshotDiffBounds,+ width: number,+ height: number+): ScreenshotDiffBounds => {+ const x = Math.max(0, Math.min(width, bounds.x));+ const y = Math.max(0, Math.min(height, bounds.y));+ return {+ x,+ y,+ width: Math.max(0, Math.min(width - x, bounds.width)),+ height: Math.max(0, Math.min(height - y, bounds.height)),+ };+};++const readRgb = (+ image: DecodedRgbaImage,+ x: number,+ y: number+): ScreenshotDiffRgb => {+ const offset = (image.width * y + x) * 4;+ const alpha = image.data[offset + 3] / 255;+ return {+ r: Math.round(image.data[offset] * alpha + 255 * (1 - alpha)),+ g: Math.round(image.data[offset + 1] * alpha + 255 * (1 - alpha)),+ b: Math.round(image.data[offset + 2] * alpha + 255 * (1 - alpha)),+ };+};++const readLuminance = (image: DecodedRgbaImage, x: number, y: number) =>+ luminance(readRgb(image, x, y));++const luminance = (rgb: ScreenshotDiffRgb) =>+ 0.2126 * rgb.r + 0.7152 * rgb.g + 0.0722 * rgb.b;++const median = (values: number[]) => {+ if (values.length === 0) {+ return 255;+ }+ const sorted = [...values].sort((left, right) => left - right);+ return sorted[Math.floor(sorted.length / 2)];+};++const relativeDelta = (left: number, right: number) =>+ left === 0 && right === 0+ ? 0+ : Math.abs(right - left) / Math.max(Math.abs(left), Math.abs(right), 1);++const colorDistance = (delta: ScreenshotDiffRgb) =>+ Math.sqrt(delta.r * delta.r + delta.g * delta.g + delta.b * delta.b);++const clampConfidence = (value: number) =>+ Math.round(Math.min(1, Math.max(0, value)) * 100) / 100;++const round = (value: number) => Math.round(value * 1000) / 1000;diff --git a/packages/project-build/src/visual/screenshot.test-utils.ts b/packages/project-build/src/visual/screenshot.test-utils.tsnew file mode 100644index 0000000000..b36f80695a--- /dev/null+++ b/packages/project-build/src/visual/screenshot.test-utils.ts@@ -0,0 +1,39 @@+import { writeFile } from "node:fs/promises";+import { encode, type ImageData } from "fast-png";+import type { ScreenshotDiffRgb } from "./screenshot-diff";++export const createPng = (+ width: number,+ height: number,+ color: ScreenshotDiffRgb+) => {+ const png: ImageData = {+ width,+ height,+ data: new Uint8Array(width * height * 4),+ depth: 8,+ channels: 4,+ };+ paintRect(png, { x: 0, y: 0, width, height }, color);+ return png;+};++export const paintRect = (+ png: ImageData,+ rect: { x: number; y: number; width: number; height: number },+ color: ScreenshotDiffRgb+) => {+ for (let y = rect.y; y < rect.y + rect.height; y++) {+ for (let x = rect.x; x < rect.x + rect.width; x++) {+ const offset = (png.width * y + x) * 4;+ png.data[offset] = color.r;+ png.data[offset + 1] = color.g;+ png.data[offset + 2] = color.b;+ png.data[offset + 3] = 255;+ }+ }+};++export const writePng = async (filePath: string, png: ImageData) => {+ await writeFile(filePath, encode(png));+};diff --git a/packages/project/src/db/build-patch-core.ts b/packages/project/src/db/build-patch-core.tsindex dee6661f71..14f286234d 100644--- a/packages/project/src/db/build-patch-core.ts+++ b/packages/project/src/db/build-patch-core.ts@@ -1,4 +1,4 @@-import { applyPatches, enableMapSet, enablePatches, type Patch } from "immer";+import type { Patch } from "immer";import {type Breakpoints,breakpoints,@@ -42,11 +42,13 @@ import {serializeConfig,serializeData,} from "@webstudio-is/project-build";+import type {+ BuilderPatch,+ BuilderPatchTransaction,+} from "@webstudio-is/project-build/contracts/patch";+import { applyBuilderNamespacePatches } from "@webstudio-is/project-build/state/patch";import type { Database } from "@webstudio-is/postgrest/index.server";-enableMapSet();-enablePatches();-type TouchedKeys = {keys: Set<string>;wholeMap: boolean;@@ -96,11 +98,10 @@ const validateTouchedMap = <Value>(export type BuildPatchChange = {namespace: string;- patches: Array<Patch>;+ patches: BuilderPatch[];};-export type BuildPatchTransaction = {- id: string;+export type BuildPatchTransaction = Omit<BuilderPatchTransaction, "payload"> & {payload: BuildPatchChange[];};@@ -185,7 +186,7 @@ export const createBuildPatchUpdate = async ({const pages = buildData.pages ?? parsePages(build.pages);const currentSocialImageAssetId =getHomePage(pages).meta.socialImageAssetId;- buildData.pages = applyPatches(pages, patches);+ buildData.pages = applyBuilderNamespacePatches(pages, patches);const newSocialImageAssetId = getHomePage(buildData.pages).meta.socialImageAssetId;if (currentSocialImageAssetId !== newSocialImageAssetId) {@@ -199,7 +200,7 @@ export const createBuildPatchUpdate = async ({const instances =buildData.instances ?? parseInstanceData(build.instances);- buildData.instances = applyPatches(instances, patches);+ buildData.instances = applyBuilderNamespacePatches(instances, patches);const cycles = findCycles(buildData.instances?.values() ?? []);if (cycles.length > 0) {@@ -220,7 +221,7 @@ export const createBuildPatchUpdate = async ({if (namespace === "props") {addTouchedPatchKeys(touchedProps, patches);const props = buildData.props ?? parseData<Prop>(build.props);- buildData.props = applyPatches(props, patches);+ buildData.props = applyBuilderNamespacePatches(props, patches);continue;}@@ -234,7 +235,7 @@ export const createBuildPatchUpdate = async ({const styleSourceSelections =buildData.styleSourceSelections ??parseStyleSourceSelections(build.styleSourceSelections);- buildData.styleSourceSelections = applyPatches(+ buildData.styleSourceSelections = applyBuilderNamespacePatches(styleSourceSelections,patches);@@ -245,7 +246,10 @@ export const createBuildPatchUpdate = async ({addTouchedPatchKeys(touchedStyleSources, patches);const styleSources =buildData.styleSources ?? parseData<StyleSource>(build.styleSources);- buildData.styleSources = applyPatches(styleSources, patches);+ buildData.styleSources = applyBuilderNamespacePatches(+ styleSources,+ patches+ );continue;}@@ -253,7 +257,7 @@ export const createBuildPatchUpdate = async ({addTouchedPatchKeys(touchedStyles, patches);const styles = buildData.styles ?? parseStyles(build.styles);- buildData.styles = applyPatches(styles, patches);+ buildData.styles = applyBuilderNamespacePatches(styles, patches);continue;}@@ -261,7 +265,10 @@ export const createBuildPatchUpdate = async ({addTouchedPatchKeys(touchedDataSources, patches);const dataSources =buildData.dataSources ?? parseData<DataSource>(build.dataSources);- buildData.dataSources = applyPatches(dataSources, patches);+ buildData.dataSources = applyBuilderNamespacePatches(+ dataSources,+ patches+ );continue;}@@ -269,7 +276,7 @@ export const createBuildPatchUpdate = async ({addTouchedPatchKeys(touchedResources, patches);const resources =buildData.resources ?? parseData<Resource>(build.resources);- buildData.resources = applyPatches(resources, patches);+ buildData.resources = applyBuilderNamespacePatches(resources, patches);continue;}@@ -277,7 +284,10 @@ export const createBuildPatchUpdate = async ({addTouchedPatchKeys(touchedBreakpoints, patches);const breakpoints =buildData.breakpoints ?? parseData<Breakpoint>(build.breakpoints);- buildData.breakpoints = applyPatches(breakpoints, patches);+ buildData.breakpoints = applyBuilderNamespacePatches(+ breakpoints,+ patches+ );continue;}@@ -286,7 +296,7 @@ export const createBuildPatchUpdate = async ({buildData.marketplaceProduct ??parseConfig<MarketplaceProduct>(build.marketplaceProduct);- buildData.marketplaceProduct = applyPatches(+ buildData.marketplaceProduct = applyBuilderNamespacePatches(marketplaceProduct,patches);diff --git a/packages/project/src/db/build-patch.test.ts b/packages/project/src/db/build-patch.test.tsindex ff5378ce10..3058c4a9cd 100644--- a/packages/project/src/db/build-patch.test.ts+++ b/packages/project/src/db/build-patch.test.ts@@ -7,7 +7,6 @@ import {testContext,} from "@webstudio-is/postgrest/testing";import type { AppContext } from "@webstudio-is/trpc-interface/index.server";-import type { Patch } from "immer";import {patchBuild,patchLoadedBuild,@@ -649,7 +648,7 @@ describe("patchBuild", () => {});test("core patch helper is decoupled from asset app logic", async () => {- const assetPatch: Patch = { op: "add", path: ["asset-1"], value: {} };+ const assetPatch = { op: "add" as const, path: ["asset-1"], value: {} };const result = await createBuildPatchUpdate({build: buildRow,clientVersion: 3,diff --git a/packages/protocol/src/builder-api/errors.test.ts b/packages/protocol/src/builder-api/errors.test.tsnew file mode 100644index 0000000000..a0a3648c04--- /dev/null+++ b/packages/protocol/src/builder-api/errors.test.ts@@ -0,0 +1,17 @@+import { expect, test } from "vitest";+import { isPublicApiRemoteErrorCode } from "./errors";++test("recognizes public API remote error codes", () => {+ for (const code of [+ "BAD_REQUEST",+ "CONFLICT",+ "FORBIDDEN",+ "INTERNAL_SERVER_ERROR",+ "NOT_FOUND",+ "UNAUTHORIZED",+ ]) {+ expect(isPublicApiRemoteErrorCode(code)).toBe(true);+ }++ expect(isPublicApiRemoteErrorCode("UNKNOWN")).toBe(false);+});diff --git a/packages/protocol/src/builder-api/errors.ts b/packages/protocol/src/builder-api/errors.tsnew file mode 100644index 0000000000..a90f8c558c--- /dev/null+++ b/packages/protocol/src/builder-api/errors.ts@@ -0,0 +1,17 @@+const publicApiRemoteErrorCodes = [+ "BAD_REQUEST",+ "CONFLICT",+ "FORBIDDEN",+ "INTERNAL_SERVER_ERROR",+ "NOT_FOUND",+ "UNAUTHORIZED",+] as const;++export type PublicApiRemoteErrorCode =+ (typeof publicApiRemoteErrorCodes)[number];++const publicApiRemoteErrorCodeSet = new Set<string>(publicApiRemoteErrorCodes);++export const isPublicApiRemoteErrorCode = (+ code: string+): code is PublicApiRemoteErrorCode => publicApiRemoteErrorCodeSet.has(code);diff --git a/packages/protocol/src/builder-api/operation-docs.test.ts b/packages/protocol/src/builder-api/operation-docs.test.tsnew file mode 100644index 0000000000..5bdb2ff045--- /dev/null+++ b/packages/protocol/src/builder-api/operation-docs.test.ts@@ -0,0 +1,14 @@+import { expect, test } from "vitest";+import { publicApiOperations } from "./operations";+import { publicApiOperationDocumentation } from "./operation-docs";++test("documents every public API command with examples", () => {+ expect(publicApiOperationDocumentation.map(({ command }) => command)).toEqual(+ publicApiOperations.map(({ command }) => command)+ );++ for (const item of publicApiOperationDocumentation) {+ expect(item.description).not.toBe("");+ expect(item.examples.length).toBeGreaterThan(0);+ }+});diff --git a/packages/protocol/src/builder-api/operation-docs.ts b/packages/protocol/src/builder-api/operation-docs.tsnew file mode 100644index 0000000000..e4c92dd5e1--- /dev/null+++ b/packages/protocol/src/builder-api/operation-docs.ts@@ -0,0 +1,547 @@+export type PublicApiOperationDocumentation = {+ command: string;+ description: string;+ requiredOptions?: readonly string[];+ examples: readonly string[];+};++export const publicApiOperationDocumentation: readonly PublicApiOperationDocumentation[] =+ [+ {+ command: "whoami",+ description: "Identify the configured API share-link token",+ examples: ["webstudio whoami --json"],+ },+ {+ command: "permissions",+ description:+ "Show API, role, publish, and domain capabilities for the configured share-link token",+ examples: ["webstudio permissions --json"],+ },+ {+ command: "inspect",+ description: "Show project metadata and latest dev build version",+ examples: ["webstudio inspect --json"],+ },+ {+ command: "snapshot",+ description: "Read selected raw build namespaces",+ examples: [+ "webstudio snapshot --include pages,instances,props,styles --json",+ ],+ },+ {+ command: "apply-patch",+ description:+ "Apply Builder build patch transactions to the configured project",+ requiredOptions: ["base-version", "input", "json"],+ examples: [+ "webstudio apply-patch --base-version 42 --input patch.json --json",+ ],+ },+ {+ command: "list-pages",+ description: "List site pages",+ examples: [+ "webstudio list-pages --json",+ "webstudio list-pages --include-folders --json",+ ],+ },+ {+ command: "get-page",+ description: "Show one page by page id",+ requiredOptions: ["page", "json"],+ examples: ["webstudio get-page --page page-id --json"],+ },+ {+ command: "get-page-by-path",+ description: "Show one page by URL path",+ requiredOptions: ["path", "json"],+ examples: ["webstudio get-page-by-path --path /pricing --json"],+ },+ {+ command: "create-page",+ description: "Create a page in the configured project",+ requiredOptions: ["name", "path", "json"],+ examples: ["webstudio create-page --name Pricing --path /pricing --json"],+ },+ {+ command: "update-page",+ description: "Update page settings and metadata",+ requiredOptions: ["page", "json"],+ examples: [+ 'webstudio update-page --page page-id --title Pricing --description "Pricing plans" --json',+ ],+ },+ {+ command: "get-project-settings",+ description:+ "Show project site metadata, compiler settings, and redirects",+ examples: ["webstudio get-project-settings --json"],+ },+ {+ command: "update-project-settings",+ description:+ "Update project site metadata and compiler settings from JSON",+ requiredOptions: ["input", "json"],+ examples: [+ "webstudio update-project-settings --input project-settings.json --json",+ ],+ },+ {+ command: "list-redirects",+ description: "List project redirects",+ examples: ["webstudio list-redirects --json"],+ },+ {+ command: "create-redirect",+ description: "Create a project redirect",+ requiredOptions: ["old", "new", "json"],+ examples: [+ "webstudio create-redirect --old /old --new /new --status 301 --json",+ ],+ },+ {+ command: "update-redirect",+ description: "Update a project redirect selected by its old path",+ requiredOptions: ["old", "json"],+ examples: [+ "webstudio update-redirect --old /old --new /newer --status 302 --json",+ "webstudio update-redirect --old /old --clear-status --json",+ ],+ },+ {+ command: "delete-redirect",+ description: "Delete a project redirect selected by its old path",+ requiredOptions: ["old", "json"],+ examples: ["webstudio delete-redirect --old /old --json"],+ },+ {+ command: "list-breakpoints",+ description: "List responsive and custom-condition breakpoints",+ examples: ["webstudio list-breakpoints --json"],+ },+ {+ command: "create-breakpoint",+ description:+ "Create a breakpoint with width limits or a custom media condition",+ requiredOptions: ["breakpoint", "label", "json"],+ examples: [+ "webstudio create-breakpoint --breakpoint tablet --label Tablet --max-width 991 --json",+ ],+ },+ {+ command: "update-breakpoint",+ description: "Update breakpoint label, width limits, or media condition",+ requiredOptions: ["breakpoint", "json"],+ examples: [+ "webstudio update-breakpoint --breakpoint tablet --label Tablet --max-width 1023 --json",+ "webstudio update-breakpoint --breakpoint tablet --clear-condition --min-width 768 --json",+ "webstudio update-breakpoint --breakpoint tablet --clear-min-width --clear-max-width --condition '(hover: hover)' --json",+ ],+ },+ {+ command: "delete-breakpoint",+ description:+ "Delete a breakpoint and all style declarations assigned to it",+ requiredOptions: ["breakpoint", "confirm", "json"],+ examples: [+ "webstudio delete-breakpoint --breakpoint tablet --confirm --json",+ ],+ },+ {+ command: "delete-page",+ description: "Delete a page and its page content",+ requiredOptions: ["page", "json"],+ examples: ["webstudio delete-page --page page-id --json"],+ },+ {+ command: "duplicate-page",+ description: "Duplicate a page and its page content",+ requiredOptions: ["page", "json"],+ examples: [+ 'webstudio duplicate-page --page page-id --name "Pricing Copy" --path /pricing-copy --json',+ ],+ },+ {+ command: "list-page-templates",+ description: "List reusable page templates in the configured project",+ examples: ["webstudio list-page-templates --json"],+ },+ {+ command: "create-page-from-template",+ description: "Create a page by copying a reusable page template",+ requiredOptions: ["template", "name", "path", "json"],+ examples: [+ 'webstudio create-page-from-template --template template-id --name "Landing" --path /landing --json',+ ],+ },+ {+ command: "list-folders",+ description: "List page folders",+ examples: [+ "webstudio list-folders --json",+ "webstudio list-folders --include-pages --json",+ ],+ },+ {+ command: "create-folder",+ description: "Create a page folder in the configured project",+ requiredOptions: ["name", "slug", "json"],+ examples: ["webstudio create-folder --name Blog --slug blog --json"],+ },+ {+ command: "update-folder",+ description: "Update page folder settings",+ requiredOptions: ["folder", "json"],+ examples: [+ "webstudio update-folder --folder folder-id --name Blog --slug blog --json",+ ],+ },+ {+ command: "delete-folder",+ description: "Delete a folder with its child folders and pages",+ requiredOptions: ["folder", "json"],+ examples: ["webstudio delete-folder --folder folder-id --json"],+ },+ {+ command: "list-instances",+ description: "List element instances in the build tree",+ examples: ["webstudio list-instances --path / --max-depth 2 --json"],+ },+ {+ command: "inspect-instance",+ description: "Show details for one element instance",+ requiredOptions: ["instance", "json"],+ examples: [+ "webstudio inspect-instance --instance instance-id --include props,styles,children --json",+ ],+ },+ {+ command: "append-instance",+ description: "Append, prepend, or replace child element instances",+ requiredOptions: ["parent", "input", "json"],+ examples: [+ "webstudio append-instance --parent parent-id --input children.json --json",+ ],+ },+ {+ command: "move-instance",+ description: "Move element instances to another parent or position",+ requiredOptions: ["input", "json"],+ examples: ["webstudio move-instance --input moves.json --json"],+ },+ {+ command: "clone-instance",+ description: "Clone an element instance subtree",+ requiredOptions: ["source", "json"],+ examples: [+ "webstudio clone-instance --source instance-id --parent parent-id --json",+ ],+ },+ {+ command: "delete-instance",+ description: "Delete element instance subtrees",+ requiredOptions: ["instance", "json"],+ examples: ["webstudio delete-instance --instance instance-id --json"],+ },+ {+ command: "update-props",+ description:+ "Create or update element props; editor tokens are limited to content-mode props",+ requiredOptions: ["input", "json"],+ examples: ["webstudio update-props --input props.json --json"],+ },+ {+ command: "delete-props",+ description:+ "Delete element props by instance and prop name; editor tokens are limited to content-mode props",+ requiredOptions: ["input", "json"],+ examples: ["webstudio delete-props --input props.json --json"],+ },+ {+ command: "bind-props",+ description:+ "Bind element props to expressions, parameters, resources, or actions",+ requiredOptions: ["input", "json"],+ examples: ["webstudio bind-props --input bindings.json --json"],+ },+ {+ command: "list-texts",+ description: "List text and expression children",+ examples: ["webstudio list-texts --contains headline --json"],+ },+ {+ command: "update-text",+ description:+ "Update a text or expression child on an element instance; editor tokens are limited to content-mode text",+ requiredOptions: ["instance", "child-index", "text", "json"],+ examples: [+ 'webstudio update-text --instance instance-id --child-index 0 --text "Launch faster" --json',+ ],+ },+ {+ command: "get-styles",+ description: "List style declarations",+ examples: ["webstudio get-styles --instance instance-id --json"],+ },+ {+ command: "update-styles",+ description: "Create or update local style declarations",+ requiredOptions: ["input", "json"],+ examples: ["webstudio update-styles --input styles.json --json"],+ },+ {+ command: "delete-styles",+ description: "Delete local style declarations",+ requiredOptions: ["input", "json"],+ examples: ["webstudio delete-styles --input styles.json --json"],+ },+ {+ command: "replace-styles",+ description: "Replace matching local style values",+ requiredOptions: ["input", "json"],+ examples: ["webstudio replace-styles --input replace.json --json"],+ },+ {+ command: "list-design-tokens",+ description: "List reusable style tokens",+ examples: ["webstudio list-design-tokens --with-usage --json"],+ },+ {+ command: "create-design-token",+ description: "Create reusable style tokens",+ requiredOptions: ["input", "json"],+ examples: ["webstudio create-design-token --input tokens.json --json"],+ },+ {+ command: "update-design-token-styles",+ description: "Create or update declarations on a reusable style token",+ requiredOptions: ["design-token", "input", "json"],+ examples: [+ "webstudio update-design-token-styles --design-token token-id --input styles.json --json",+ ],+ },+ {+ command: "delete-design-token-styles",+ description: "Delete declarations from a reusable style token",+ requiredOptions: ["design-token", "input", "json"],+ examples: [+ "webstudio delete-design-token-styles --design-token token-id --input styles.json --json",+ ],+ },+ {+ command: "attach-design-token",+ description: "Attach a reusable style token to element instances",+ requiredOptions: ["design-token", "input", "json"],+ examples: [+ "webstudio attach-design-token --design-token token-id --input instances.json --json",+ ],+ },+ {+ command: "detach-design-token",+ description: "Detach a reusable style token from element instances",+ requiredOptions: ["design-token", "input", "json"],+ examples: [+ "webstudio detach-design-token --design-token token-id --input instances.json --json",+ ],+ },+ {+ command: "extract-design-token",+ description: "Create a reusable style token from local instance styles",+ requiredOptions: ["input", "json"],+ examples: ["webstudio extract-design-token --input token.json --json"],+ },+ {+ command: "list-css-variables",+ description: "List CSS custom property definitions",+ examples: ["webstudio list-css-variables --with-usage --json"],+ },+ {+ command: "define-css-variable",+ description: "Define project-level CSS custom properties",+ requiredOptions: ["input", "json"],+ examples: ["webstudio define-css-variable --input vars.json --json"],+ },+ {+ command: "delete-css-variable",+ description: "Delete CSS custom property definitions",+ requiredOptions: ["input", "confirm", "json"],+ examples: [+ "webstudio delete-css-variable --input names.json --confirm --json",+ ],+ },+ {+ command: "rewrite-css-variable-refs",+ description: "Rewrite var() references to CSS custom properties",+ requiredOptions: ["input", "json"],+ examples: [+ "webstudio rewrite-css-variable-refs --input variables.json --json",+ ],+ },+ {+ command: "list-variables",+ description: "List data variables",+ examples: ["webstudio list-variables --json"],+ },+ {+ command: "create-variable",+ description: "Create a data variable scoped to an element instance",+ requiredOptions: [+ "scope-instance",+ "name",+ "value-type",+ "value",+ "json",+ ],+ examples: [+ 'webstudio create-variable --scope-instance body-id --name title --value-type string --value "Hello" --json',+ ],+ },+ {+ command: "update-variable",+ description: "Update a data variable name, value, or scope",+ requiredOptions: ["variable", "json"],+ examples: [+ "webstudio update-variable --variable variable-id --value-type json --value '{\"count\":1}' --json",+ ],+ },+ {+ command: "delete-variable",+ description: "Delete a data variable",+ requiredOptions: ["variable", "json"],+ examples: ["webstudio delete-variable --variable variable-id --json"],+ },+ {+ command: "list-resources",+ description: "List data resources",+ examples: ["webstudio list-resources --json"],+ },+ {+ command: "create-resource",+ description:+ "Create a data resource and optionally expose it as a variable",+ requiredOptions: ["name", "method", "url", "json"],+ examples: [+ 'webstudio create-resource --name Posts --method get --url "\\"https://api.example.com/posts\\"" --json',+ ],+ },+ {+ command: "update-resource",+ description: "Update data resource request fields",+ requiredOptions: ["resource", "json"],+ examples: [+ 'webstudio update-resource --resource resource-id --url "\\"https://api.example.com/posts\\"" --json',+ ],+ },+ {+ command: "delete-resource",+ description: "Delete a data resource and its exposed data variable",+ requiredOptions: ["resource", "json"],+ examples: ["webstudio delete-resource --resource resource-id --json"],+ },+ {+ command: "publish",+ description:+ "Publish the configured project to staging or production. Uses the project domain by default and, for production, active verified custom domains. If local development cannot contact the deployment backend, the JSON response includes warning while still returning the local publish job id.",+ requiredOptions: ["target", "json"],+ examples: [+ "webstudio publish --target production --json",+ "webstudio publish --target production --domain example.com --json",+ ],+ },+ {+ command: "list-publishes",+ description: "List production publish builds for the configured project",+ examples: ["webstudio list-publishes --json"],+ },+ {+ command: "get-publish-job",+ description:+ "Show the status and domains for a publish job returned by publish",+ requiredOptions: ["job", "json"],+ examples: ["webstudio get-publish-job --job build-id --json"],+ },+ {+ command: "unpublish",+ description:+ "Remove staging or production deployment records for selected domains",+ requiredOptions: ["target", "confirm", "json"],+ examples: ["webstudio unpublish --target production --confirm --json"],+ },+ {+ command: "list-domains",+ description: "List custom domains linked to the configured project",+ examples: ["webstudio list-domains --json"],+ },+ {+ command: "create-domain",+ description: "Create and link a custom domain to the configured project",+ requiredOptions: ["domain", "json"],+ examples: ["webstudio create-domain --domain example.com --json"],+ },+ {+ command: "update-domain",+ description: "Update a linked custom domain",+ requiredOptions: ["domain-id", "json"],+ examples: [+ "webstudio update-domain --domain-id domain-id --domain www.example.com --json",+ "webstudio update-domain --domain-id domain-id --input domain.json --json",+ ],+ },+ {+ command: "delete-domain",+ description: "Remove a custom domain from the configured project",+ requiredOptions: ["domain-id", "confirm", "json"],+ examples: [+ "webstudio delete-domain --domain-id domain-id --confirm --json",+ ],+ },+ {+ command: "verify-domain",+ description: "Verify a linked custom domain after DNS records are set",+ requiredOptions: ["domain-id", "json"],+ examples: ["webstudio verify-domain --domain-id domain-id --json"],+ },+ {+ command: "list-assets",+ description: "List project assets",+ examples: ["webstudio list-assets --type image --with-usage --json"],+ },+ {+ command: "upload-asset",+ description: "Upload one local asset file from an asset descriptor",+ requiredOptions: ["input", "json"],+ examples: [+ "webstudio upload-asset --input asset.json --assets-dir .webstudio/assets --json",+ ],+ },+ {+ command: "upload-assets",+ description: "Upload local asset files from asset descriptors",+ requiredOptions: ["input", "json"],+ examples: [+ "webstudio upload-assets --input assets.json --assets-dir .webstudio/assets --json",+ ],+ },+ {+ command: "find-asset-usage",+ description: "Find where an asset is referenced in the project",+ requiredOptions: ["asset", "json"],+ examples: ["webstudio find-asset-usage --asset asset-id --json"],+ },+ {+ command: "replace-asset",+ description: "Replace asset references and delete the old asset",+ requiredOptions: ["from", "to", "confirm", "json"],+ examples: [+ "webstudio replace-asset --from old-asset-id --to new-asset-id --confirm --json",+ ],+ },+ {+ command: "delete-asset",+ description: "Delete asset records by id or id prefix",+ requiredOptions: ["asset", "confirm", "json"],+ examples: ["webstudio delete-asset --asset asset-id --confirm --json"],+ },+ ] as const;diff --git a/packages/protocol/src/builder-api/operations.test.ts b/packages/protocol/src/builder-api/operations.test.tsnew file mode 100644index 0000000000..5a3baf381a--- /dev/null+++ b/packages/protocol/src/builder-api/operations.test.ts@@ -0,0 +1,110 @@+import { describe, expect, test } from "vitest";+import {+ getPublicApiOperation,+ getPublicApiOperationPath,+ publicApiOperations,+} from "./operations";+import { publicApiOperationNamespaces } from "./runtime-contracts";+import { publicRuntimeOperationContracts } from "./runtime-contracts";++describe("public api operation catalog", () => {+ test("has stable unique command and operation ids", () => {+ const commands = publicApiOperations.map((operation) => operation.command);+ const ids = publicApiOperations.map((operation) => operation.id);++ expect(new Set(commands).size).toBe(commands.length);+ expect(new Set(ids).size).toBe(ids.length);+ });++ test("owns documentation metadata for every command", () => {+ for (const operation of publicApiOperations) {+ expect(operation.description).not.toBe("");+ expect(operation.examples.length).toBeGreaterThan(0);+ expect(Array.isArray(operation.inputFields)).toBe(true);+ }+ });++ test("documents public API input field names", () => {+ expect(getPublicApiOperation("create-page").inputFields).toEqual([+ "pageId",+ "name",+ "path",+ "title",+ "parentFolderId",+ "meta",+ ]);+ expect(getPublicApiOperation("create-resource").inputFields).toEqual([+ "resourceId",+ "resource",+ "dataSourceId",+ "scopeInstanceId",+ "dataSourceName",+ ]);+ expect(getPublicApiOperation("create-domain").inputFields).toEqual([+ "domain",+ ]);+ expect(getPublicApiOperation("whoami").inputFields).toEqual([]);+ });++ test("derives local-capable namespace metadata from runtime contracts", () => {+ const runtimeContractsById = new Map(+ publicRuntimeOperationContracts.map((contract) => [contract.id, contract])+ );+ const localCapableOperations: string[] = [];+ const serverOnlyOperations: string[] = [];++ for (const operation of publicApiOperations) {+ const contract =+ operation.runtimeOperationId === undefined+ ? undefined+ : runtimeContractsById.get(operation.runtimeOperationId);+ if (operation.localCapable) {+ localCapableOperations.push(operation.id);+ }+ if (operation.serverOnly) {+ serverOnlyOperations.push(operation.id);+ }++ expect(operation.localCapable).toBe(contract !== undefined);+ expect(operation.serverOnly).toBe(contract === undefined);+ expect(operation.runtimeOperationId).toBe(contract?.id);+ expect(operation.readNamespaces).toEqual(contract?.readNamespaces ?? []);+ expect(operation.writeNamespaces).toEqual(+ contract?.writeNamespaces ?? []+ );+ expect(operation.retryOnConflict).toBe(+ contract?.retryOnConflict ?? false+ );+ if (contract !== undefined) {+ expect(operation.invalidatesNamespaces).toEqual(+ contract.invalidatesNamespaces+ );+ }+ }++ expect(localCapableOperations.length).toBeGreaterThan(0);+ expect(serverOnlyOperations.length).toBeGreaterThan(0);+ });++ test("documents server-only namespace invalidation", () => {+ expect(getPublicApiOperation("apply-patch").serverOnly).toBe(true);+ expect(getPublicApiOperation("apply-patch").invalidatesNamespaces).toBe(+ publicApiOperationNamespaces+ );+ expect(getPublicApiOperation("upload-asset").serverOnly).toBe(true);+ expect(getPublicApiOperation("upload-asset").invalidatesNamespaces).toEqual(+ ["assets"]+ );+ expect(+ getPublicApiOperation("upload-assets").invalidatesNamespaces+ ).toEqual(["assets"]);+ });++ test("keeps operation lookup and tRPC path lookup strict", () => {+ expect(getPublicApiOperation("list-pages").id).toBe("pages.list");+ expect(getPublicApiOperationPath("list-pages")).toBe("api.pages.list");+ expect(() => getPublicApiOperationPath("upload-asset")).toThrow(+ 'Public API operation "upload-asset" has no tRPC path.'+ );+ });+});diff --git a/packages/protocol/src/builder-api/operations.ts b/packages/protocol/src/builder-api/operations.tsnew file mode 100644index 0000000000..98c13ba635--- /dev/null+++ b/packages/protocol/src/builder-api/operations.ts@@ -0,0 +1,786 @@+import { publicApiOperationDocumentation } from "./operation-docs";+import {+ publicApiOperationNamespaces,+ publicRuntimeOperationContracts,+ type PublicApiOperationNamespace,+ type PublicRuntimeOperationId,+} from "./runtime-contracts";+export type { PublicApiOperationNamespace } from "./runtime-contracts";++export type PublicApiOperationMethod = "query" | "mutation";+export type PublicApiOperationPermit =+ | "api"+ | "view"+ | "build"+ | "edit"+ | "admin";++type PublicApiOperationInput = {+ command: string;+ id: string;+ method: PublicApiOperationMethod;+ path?: string;+ client: string;+ permit?: PublicApiOperationPermit;+ invalidatesNamespaces?: readonly PublicApiOperationNamespace[];+};++export type PublicApiOperation<Command extends string = string> = Omit<+ PublicApiOperationInput,+ "command" | "permit"+> & {+ command: Command;+ permit: PublicApiOperationPermit;+ description: string;+ inputFields: readonly string[];+ requiredOptions?: readonly string[];+ examples: readonly string[];+ localCapable: boolean;+ serverOnly: boolean;+ runtimeOperationId?: PublicRuntimeOperationId;+ readNamespaces: readonly PublicApiOperationNamespace[];+ writeNamespaces: readonly PublicApiOperationNamespace[];+ invalidatesNamespaces: readonly PublicApiOperationNamespace[];+ retryOnConflict: boolean;+};++const runtimeOperationById = new Map(+ publicRuntimeOperationContracts.map((contract) => [contract.id, contract])+);+const documentationByCommand = new Map(+ publicApiOperationDocumentation.map((documentation) => [+ documentation.command,+ documentation,+ ])+);++const inputFieldsByCommand = {+ snapshot: ["include", "version"],+ "list-pages": ["includeFolders"],+ "get-page": ["pageId"],+ "get-page-by-path": ["path"],+ "create-page": ["pageId", "name", "path", "title", "parentFolderId", "meta"],+ "update-page": ["pageId", "values"],+ "update-project-settings": ["meta", "compiler"],+ "create-redirect": ["old", "new", "status"],+ "update-redirect": ["old", "values"],+ "delete-redirect": ["old"],+ "create-breakpoint": ["id", "label", "minWidth", "maxWidth", "condition"],+ "update-breakpoint": ["breakpointId", "values"],+ "delete-breakpoint": ["breakpointId"],+ "delete-page": ["pageId"],+ "duplicate-page": ["pageId", "parentFolderId", "name", "path"],+ "create-page-from-template": ["templateId", "parentFolderId", "name", "path"],+ "list-folders": ["includePages"],+ "create-folder": ["folderId", "name", "slug", "parentFolderId"],+ "update-folder": ["folderId", "values"],+ "delete-folder": ["folderId"],+ "list-instances": [+ "pageId",+ "pagePath",+ "rootInstanceId",+ "maxDepth",+ "topLevelOnly",+ "component",+ "tag",+ "labelContains",+ ],+ "inspect-instance": ["instanceId", "include", "childDepth"],+ "append-instance": ["parentInstanceId", "mode", "insertIndex", "children"],+ "move-instance": ["moves"],+ "clone-instance": [+ "sourceInstanceId",+ "targetParentInstanceId",+ "insertIndex",+ ],+ "delete-instance": ["instanceIds"],+ "update-props": ["updates"],+ "delete-props": ["deletions"],+ "bind-props": ["bindings"],+ "list-texts": [+ "pageId",+ "pagePath",+ "instanceId",+ "mode",+ "contains",+ "maxValueLength",+ ],+ "update-text": ["instanceId", "childIndex", "text", "mode"],+ "get-styles": [+ "instanceIds",+ "pageId",+ "pagePath",+ "breakpoint",+ "state",+ "property",+ "propertyFilter",+ "includeTokens",+ ],+ "update-styles": ["updates"],+ "delete-styles": ["deletions"],+ "replace-styles": ["property", "fromValue", "toValue", "pageId", "pagePath"],+ "list-design-tokens": ["filter", "withUsage", "sort"],+ "create-design-token": ["tokens"],+ "update-design-token-styles": ["designTokenId", "updates"],+ "delete-design-token-styles": ["designTokenId", "deletions"],+ "attach-design-token": ["designTokenId", "instanceIds", "position"],+ "detach-design-token": ["designTokenId", "instanceIds"],+ "extract-design-token": ["instanceIds", "name", "removeLocalProps"],+ "list-css-variables": ["filter", "withUsage"],+ "define-css-variable": ["vars", "overwrite"],+ "delete-css-variable": ["names", "force"],+ "rewrite-css-variable-refs": ["map", "scopeRegex"],+ "list-variables": ["scopeInstanceId"],+ "create-variable": ["dataSourceId", "scopeInstanceId", "name", "value"],+ "update-variable": ["dataSourceId", "values"],+ "delete-variable": ["dataSourceId"],+ "list-resources": ["scopeInstanceId"],+ "create-resource": [+ "resourceId",+ "resource",+ "dataSourceId",+ "scopeInstanceId",+ "dataSourceName",+ ],+ "update-resource": [+ "resourceId",+ "values",+ "dataSourceName",+ "scopeInstanceId",+ ],+ "delete-resource": ["resourceId", "force"],+ publish: ["target", "domains", "message", "idempotencyKey"],+ "get-publish-job": ["jobId"],+ unpublish: ["target", "domains", "message", "idempotencyKey"],+ "create-domain": ["domain"],+ "update-domain": ["domainId", "updates"],+ "delete-domain": ["domainId"],+ "verify-domain": ["domainId"],+ "list-assets": ["type", "sort", "withUsage", "cursor", "limit"],+ "find-asset-usage": ["assetId"],+ "replace-asset": ["fromAssetId", "toAssetId"],+ "delete-asset": ["assetIdsOrPrefixes", "force"],+} as const satisfies Partial<Record<string, readonly string[]>>;++const inputFieldsLookup: Partial<Record<string, readonly string[]>> =+ inputFieldsByCommand;++const isRuntimeOperationId = (id: string): id is PublicRuntimeOperationId =>+ runtimeOperationById.has(id as PublicRuntimeOperationId);++const withDefaultPermit = <Operation extends PublicApiOperationInput>(+ operation: Operation+): PublicApiOperation<Operation["command"]> => {+ const documentation = documentationByCommand.get(operation.command);+ if (documentation === undefined) {+ throw new Error(+ `Missing public API operation documentation for "${operation.command}".`+ );+ }+ const runtimeOperationId = isRuntimeOperationId(operation.id)+ ? operation.id+ : undefined;+ const runtimeOperation =+ runtimeOperationId === undefined+ ? undefined+ : runtimeOperationById.get(runtimeOperationId);+ return {+ ...operation,+ permit:+ operation.permit ?? (operation.method === "query" ? "view" : "build"),+ description: documentation.description,+ inputFields: inputFieldsLookup[operation.command] ?? [],+ requiredOptions: documentation.requiredOptions,+ examples: documentation.examples,+ localCapable: runtimeOperation !== undefined,+ serverOnly: runtimeOperation === undefined,+ runtimeOperationId,+ readNamespaces: runtimeOperation?.readNamespaces ?? [],+ writeNamespaces: runtimeOperation?.writeNamespaces ?? [],+ invalidatesNamespaces:+ runtimeOperation?.invalidatesNamespaces ??+ operation.invalidatesNamespaces ??+ [],+ retryOnConflict: runtimeOperation?.retryOnConflict ?? false,+ };+};++const publicApiOperationInputs = [+ {+ command: "whoami",+ id: "auth.me",+ method: "query",+ path: "api.auth.me",+ client: "getApiTokenInfo",+ permit: "view",+ },+ {+ command: "permissions",+ id: "projects.permissions",+ method: "query",+ path: "api.projects.permissions",+ client: "getProjectPermissions",+ },+ {+ command: "inspect",+ id: "projects.get",+ method: "query",+ path: "api.projects.get",+ client: "getProjectInfo",+ },+ {+ command: "snapshot",+ id: "build.get",+ method: "query",+ path: "api.build.get",+ client: "getBuildSnapshot",+ },+ {+ command: "apply-patch",+ id: "build.patch",+ method: "mutation",+ path: "api.build.patch",+ client: "applyBuildPatch",+ invalidatesNamespaces: publicApiOperationNamespaces,+ },+ {+ command: "list-pages",+ id: "pages.list",+ method: "query",+ path: "api.pages.list",+ client: "listPages",+ },+ {+ command: "get-page",+ id: "pages.get",+ method: "query",+ path: "api.pages.get",+ client: "getPage",+ },+ {+ command: "get-page-by-path",+ id: "pages.getByPath",+ method: "query",+ path: "api.pages.getByPath",+ client: "getPageByPath",+ },+ {+ command: "create-page",+ id: "pages.create",+ method: "mutation",+ path: "api.pages.create",+ client: "createPage",+ },+ {+ command: "update-page",+ id: "pages.update",+ method: "mutation",+ path: "api.pages.update",+ client: "updatePage",+ },+ {+ command: "get-project-settings",+ id: "projectSettings.get",+ method: "query",+ path: "api.projectSettings.get",+ client: "getProjectSettings",+ },+ {+ command: "update-project-settings",+ id: "projectSettings.update",+ method: "mutation",+ path: "api.projectSettings.update",+ client: "updateProjectSettings",+ },+ {+ command: "list-redirects",+ id: "redirects.list",+ method: "query",+ path: "api.redirects.list",+ client: "listRedirects",+ },+ {+ command: "create-redirect",+ id: "redirects.create",+ method: "mutation",+ path: "api.redirects.create",+ client: "createRedirect",+ },+ {+ command: "update-redirect",+ id: "redirects.update",+ method: "mutation",+ path: "api.redirects.update",+ client: "updateRedirect",+ },+ {+ command: "delete-redirect",+ id: "redirects.delete",+ method: "mutation",+ path: "api.redirects.delete",+ client: "deleteRedirect",+ },+ {+ command: "list-breakpoints",+ id: "breakpoints.list",+ method: "query",+ path: "api.breakpoints.list",+ client: "listBreakpoints",+ },+ {+ command: "create-breakpoint",+ id: "breakpoints.create",+ method: "mutation",+ path: "api.breakpoints.create",+ client: "createBreakpoint",+ },+ {+ command: "update-breakpoint",+ id: "breakpoints.update",+ method: "mutation",+ path: "api.breakpoints.update",+ client: "updateBreakpoint",+ },+ {+ command: "delete-breakpoint",+ id: "breakpoints.delete",+ method: "mutation",+ path: "api.breakpoints.delete",+ client: "deleteBreakpoint",+ },+ {+ command: "delete-page",+ id: "pages.delete",+ method: "mutation",+ path: "api.pages.delete",+ client: "deletePage",+ },+ {+ command: "duplicate-page",+ id: "pages.duplicate",+ method: "mutation",+ path: "api.pages.duplicate",+ client: "duplicatePage",+ },+ {+ command: "list-page-templates",+ id: "pageTemplates.list",+ method: "query",+ path: "api.pageTemplates.list",+ client: "listPageTemplates",+ },+ {+ command: "create-page-from-template",+ id: "pageTemplates.createPage",+ method: "mutation",+ path: "api.pageTemplates.createPage",+ client: "createPageFromTemplate",+ },+ {+ command: "list-folders",+ id: "folders.list",+ method: "query",+ path: "api.folders.list",+ client: "listFolders",+ },+ {+ command: "create-folder",+ id: "folders.create",+ method: "mutation",+ path: "api.folders.create",+ client: "createFolder",+ },+ {+ command: "update-folder",+ id: "folders.update",+ method: "mutation",+ path: "api.folders.update",+ client: "updateFolder",+ },+ {+ command: "delete-folder",+ id: "folders.delete",+ method: "mutation",+ path: "api.folders.delete",+ client: "deleteFolder",+ },+ {+ command: "list-instances",+ id: "instances.list",+ method: "query",+ path: "api.instances.list",+ client: "listInstances",+ },+ {+ command: "inspect-instance",+ id: "instances.inspect",+ method: "query",+ path: "api.instances.inspect",+ client: "inspectInstance",+ },+ {+ command: "append-instance",+ id: "instances.append",+ method: "mutation",+ path: "api.instances.append",+ client: "appendInstance",+ },+ {+ command: "move-instance",+ id: "instances.move",+ method: "mutation",+ path: "api.instances.move",+ client: "moveInstance",+ },+ {+ command: "clone-instance",+ id: "instances.clone",+ method: "mutation",+ path: "api.instances.clone",+ client: "cloneInstance",+ },+ {+ command: "delete-instance",+ id: "instances.delete",+ method: "mutation",+ path: "api.instances.delete",+ client: "deleteInstance",+ },+ {+ command: "update-props",+ id: "instances.updateProps",+ method: "mutation",+ path: "api.instances.updateProps",+ client: "updateProps",+ permit: "edit",+ },+ {+ command: "delete-props",+ id: "instances.deleteProps",+ method: "mutation",+ path: "api.instances.deleteProps",+ client: "deleteProps",+ permit: "edit",+ },+ {+ command: "bind-props",+ id: "instances.bindProps",+ method: "mutation",+ path: "api.instances.bindProps",+ client: "bindProps",+ },+ {+ command: "list-texts",+ id: "instances.listTexts",+ method: "query",+ path: "api.instances.listTexts",+ client: "listTexts",+ },+ {+ command: "update-text",+ id: "instances.updateText",+ method: "mutation",+ path: "api.instances.updateText",+ client: "updateText",+ permit: "edit",+ },+ {+ command: "get-styles",+ id: "styles.getDeclarations",+ method: "query",+ path: "api.styles.getDeclarations",+ client: "getStyleDeclarations",+ },+ {+ command: "update-styles",+ id: "styles.updateDeclarations",+ method: "mutation",+ path: "api.styles.updateDeclarations",+ client: "updateStyleDeclarations",+ },+ {+ command: "delete-styles",+ id: "styles.deleteDeclarations",+ method: "mutation",+ path: "api.styles.deleteDeclarations",+ client: "deleteStyleDeclarations",+ },+ {+ command: "replace-styles",+ id: "styles.replaceValues",+ method: "mutation",+ path: "api.styles.replaceValues",+ client: "replaceStyleValues",+ },+ {+ command: "list-design-tokens",+ id: "designTokens.list",+ method: "query",+ path: "api.designTokens.list",+ client: "listDesignTokens",+ },+ {+ command: "create-design-token",+ id: "designTokens.create",+ method: "mutation",+ path: "api.designTokens.create",+ client: "createDesignTokens",+ },+ {+ command: "update-design-token-styles",+ id: "designTokens.updateStyles",+ method: "mutation",+ path: "api.designTokens.updateStyles",+ client: "updateDesignTokenStyles",+ },+ {+ command: "delete-design-token-styles",+ id: "designTokens.deleteStyles",+ method: "mutation",+ path: "api.designTokens.deleteStyles",+ client: "deleteDesignTokenStyles",+ },+ {+ command: "attach-design-token",+ id: "designTokens.attach",+ method: "mutation",+ path: "api.designTokens.attach",+ client: "attachDesignToken",+ },+ {+ command: "detach-design-token",+ id: "designTokens.detach",+ method: "mutation",+ path: "api.designTokens.detach",+ client: "detachDesignToken",+ },+ {+ command: "extract-design-token",+ id: "designTokens.extract",+ method: "mutation",+ path: "api.designTokens.extract",+ client: "extractDesignToken",+ },+ {+ command: "list-css-variables",+ id: "cssVariables.list",+ method: "query",+ path: "api.cssVariables.list",+ client: "listCssVariables",+ },+ {+ command: "define-css-variable",+ id: "cssVariables.define",+ method: "mutation",+ path: "api.cssVariables.define",+ client: "defineCssVariables",+ },+ {+ command: "delete-css-variable",+ id: "cssVariables.delete",+ method: "mutation",+ path: "api.cssVariables.delete",+ client: "deleteCssVariables",+ },+ {+ command: "rewrite-css-variable-refs",+ id: "cssVariables.rewriteRefs",+ method: "mutation",+ path: "api.cssVariables.rewriteRefs",+ client: "rewriteCssVariableRefs",+ },+ {+ command: "list-variables",+ id: "variables.list",+ method: "query",+ path: "api.variables.list",+ client: "listVariables",+ },+ {+ command: "create-variable",+ id: "variables.create",+ method: "mutation",+ path: "api.variables.create",+ client: "createVariable",+ },+ {+ command: "update-variable",+ id: "variables.update",+ method: "mutation",+ path: "api.variables.update",+ client: "updateVariable",+ },+ {+ command: "delete-variable",+ id: "variables.delete",+ method: "mutation",+ path: "api.variables.delete",+ client: "deleteVariable",+ },+ {+ command: "list-resources",+ id: "resources.list",+ method: "query",+ path: "api.resources.list",+ client: "listResources",+ },+ {+ command: "create-resource",+ id: "resources.create",+ method: "mutation",+ path: "api.resources.create",+ client: "createResource",+ },+ {+ command: "update-resource",+ id: "resources.update",+ method: "mutation",+ path: "api.resources.update",+ client: "updateResource",+ },+ {+ command: "delete-resource",+ id: "resources.delete",+ method: "mutation",+ path: "api.resources.delete",+ client: "deleteResource",+ },+ {+ command: "publish",+ id: "publish.create",+ method: "mutation",+ path: "api.publish.create",+ client: "publish",+ permit: "edit",+ },+ {+ command: "list-publishes",+ id: "publish.list",+ method: "query",+ path: "api.publish.list",+ client: "listPublishes",+ },+ {+ command: "get-publish-job",+ id: "publish.getJob",+ method: "query",+ path: "api.publish.getJob",+ client: "getPublishJob",+ },+ {+ command: "unpublish",+ id: "publish.unpublish",+ method: "mutation",+ path: "api.publish.unpublish",+ client: "unpublish",+ permit: "edit",+ },+ {+ command: "list-domains",+ id: "domains.list",+ method: "query",+ path: "api.domains.list",+ client: "listDomains",+ },+ {+ command: "create-domain",+ id: "domains.create",+ method: "mutation",+ path: "api.domains.create",+ client: "createDomain",+ permit: "admin",+ },+ {+ command: "update-domain",+ id: "domains.update",+ method: "mutation",+ path: "api.domains.update",+ client: "updateDomain",+ permit: "admin",+ },+ {+ command: "delete-domain",+ id: "domains.delete",+ method: "mutation",+ path: "api.domains.delete",+ client: "deleteDomain",+ permit: "admin",+ },+ {+ command: "verify-domain",+ id: "domains.verify",+ method: "mutation",+ path: "api.domains.verify",+ client: "verifyDomain",+ permit: "admin",+ },+ {+ command: "list-assets",+ id: "assets.list",+ method: "query",+ path: "api.assets.list",+ client: "listAssets",+ },+ {+ command: "upload-asset",+ id: "assets.upload",+ method: "mutation",+ client: "uploadProjectAsset",+ invalidatesNamespaces: ["assets"],+ },+ {+ command: "upload-assets",+ id: "assets.uploadMany",+ method: "mutation",+ client: "uploadProjectAssets",+ invalidatesNamespaces: ["assets"],+ },+ {+ command: "find-asset-usage",+ id: "assets.findUsage",+ method: "query",+ path: "api.assets.findUsage",+ client: "findAssetUsage",+ },+ {+ command: "replace-asset",+ id: "assets.replace",+ method: "mutation",+ path: "api.assets.replace",+ client: "replaceAsset",+ },+ {+ command: "delete-asset",+ id: "assets.delete",+ method: "mutation",+ path: "api.assets.delete",+ client: "deleteAssets",+ },+] as const satisfies readonly PublicApiOperationInput[];++export const publicApiOperations =+ publicApiOperationInputs.map(withDefaultPermit);++export type PublicApiCommand =+ (typeof publicApiOperationInputs)[number]["command"];++const publicApiOperationByCommand = new Map(+ publicApiOperations.map((operation) => [operation.command, operation])+);++export const getPublicApiOperation = (command: PublicApiCommand) => {+ const operation = publicApiOperationByCommand.get(command);+ if (operation === undefined) {+ throw new Error(`Unknown public API operation "${command}".`);+ }+ return operation;+};++export const getPublicApiOperationPath = (command: PublicApiCommand) => {+ const operation = getPublicApiOperation(command);+ const path = "path" in operation ? operation.path : undefined;+ if (path === undefined) {+ throw new Error(`Public API operation "${command}" has no tRPC path.`);+ }+ return path;+};diff --git a/packages/protocol/src/builder-api/runtime-contracts.test.ts b/packages/protocol/src/builder-api/runtime-contracts.test.tsnew file mode 100644index 0000000000..c6e5f6cc3b--- /dev/null+++ b/packages/protocol/src/builder-api/runtime-contracts.test.ts@@ -0,0 +1,31 @@+import { expect, test } from "vitest";+import { runtimeOperationContracts } from "@webstudio-is/project-build/contracts/builder-runtime";+import { builderNamespaces } from "@webstudio-is/project-build/contracts/namespaces";+import {+ publicApiOperationNamespaces,+ publicRuntimeOperationContracts,+} from "./runtime-contracts";++test("exposes public runtime contracts without private metadata", () => {+ expect(publicRuntimeOperationContracts).toEqual(+ runtimeOperationContracts.map(+ ({+ id,+ readNamespaces,+ writeNamespaces,+ invalidatesNamespaces,+ retryOnConflict,+ }) => ({+ id,+ readNamespaces,+ writeNamespaces,+ invalidatesNamespaces,+ retryOnConflict,+ })+ )+ );+});++test("exposes public operation namespaces from builder namespaces", () => {+ expect(publicApiOperationNamespaces).toBe(builderNamespaces);+});diff --git a/packages/protocol/src/builder-api/runtime-contracts.ts b/packages/protocol/src/builder-api/runtime-contracts.tsnew file mode 100644index 0000000000..21cd9ac6a0--- /dev/null+++ b/packages/protocol/src/builder-api/runtime-contracts.ts@@ -0,0 +1,33 @@+import { runtimeOperationContracts } from "@webstudio-is/project-build/contracts/builder-runtime";+import { builderNamespaces } from "@webstudio-is/project-build/contracts/namespaces";++export const publicApiOperationNamespaces = builderNamespaces;+export type PublicApiOperationNamespace =+ (typeof publicApiOperationNamespaces)[number];++export type PublicRuntimeOperationId = string;++export type PublicRuntimeOperationContract = {+ id: PublicRuntimeOperationId;+ readNamespaces: readonly PublicApiOperationNamespace[];+ writeNamespaces: readonly PublicApiOperationNamespace[];+ invalidatesNamespaces: readonly PublicApiOperationNamespace[];+ retryOnConflict: boolean;+};++export const publicRuntimeOperationContracts: readonly PublicRuntimeOperationContract[] =+ runtimeOperationContracts.map(+ ({+ id,+ readNamespaces,+ writeNamespaces,+ invalidatesNamespaces,+ retryOnConflict,+ }): PublicRuntimeOperationContract => ({+ id,+ readNamespaces,+ writeNamespaces,+ invalidatesNamespaces,+ retryOnConflict,+ })+ );diff --git a/packages/protocol/src/builder-api/url.test.ts b/packages/protocol/src/builder-api/url.test.tsnew file mode 100644index 0000000000..c337231d41--- /dev/null+++ b/packages/protocol/src/builder-api/url.test.ts@@ -0,0 +1,55 @@+import { expect, test } from "vitest";+import { parseBuilderUrl } from "./url";++test.each([+ [+ "wstd.dev",+ "https://p-090e6e14-ae50-4b2e-bd22-71733cec05bb.wstd.dev",+ "https://wstd.dev",+ "090e6e14-ae50-4b2e-bd22-71733cec05bb",+ ],+ [+ "localhost",+ "https://p-090e6e14-ae50-4b2e-bd22-71733cec05bb.localhost",+ "https://localhost",+ "090e6e14-ae50-4b2e-bd22-71733cec05bb",+ ],+ [+ "invalid localhost",+ "https://p-eee.localhost",+ "https://p-eee.localhost",+ undefined,+ ],+ [+ "development.webstudio.is",+ "https://p-090e6e14-ae50-4b2e-bd22-71733cec05bb.development.webstudio.is",+ "https://development.webstudio.is",+ "090e6e14-ae50-4b2e-bd22-71733cec05bb",+ ],+ [+ "main.development.webstudio.is",+ "https://p-090e6e14-ae50-4b2e-bd22-71733cec05bb-dot-main.development.webstudio.is",+ "https://main.development.webstudio.is",+ "090e6e14-ae50-4b2e-bd22-71733cec05bb",+ ],+ [+ "branch.development.webstudio.is",+ "https://p-090e6e14-ae50-4b2e-bd22-71733cec05bb-dot-branch.development.webstudio.is",+ "https://branch.development.webstudio.is",+ "090e6e14-ae50-4b2e-bd22-71733cec05bb",+ ],+ [+ "apps.webstudio.is",+ "https://p-090e6e14-ae50-4b2e-bd22-71733cec05bb.apps.webstudio.is",+ "https://apps.webstudio.is",+ "090e6e14-ae50-4b2e-bd22-71733cec05bb",+ ],+ [+ "plain apps.webstudio.is",+ "https://apps.webstudio.is",+ "https://apps.webstudio.is",+ undefined,+ ],+] as const)("parseBuilderUrl %s", (_name, url, sourceOrigin, projectId) => {+ expect(parseBuilderUrl(url)).toEqual({ projectId, sourceOrigin });+});diff --git a/packages/protocol/src/builder-api/url.ts b/packages/protocol/src/builder-api/url.tsnew file mode 100644index 0000000000..1028d395da--- /dev/null+++ b/packages/protocol/src/builder-api/url.ts@@ -0,0 +1,42 @@+// For easier detecting the builder URL+const buildProjectDomainPrefix = "p-";++export const parseBuilderUrl = (urlStr: string) => {+ const url = new URL(urlStr);++ const fragments = url.host.split(".");+ // Regular expression to match the prefix, UUID, and any optional string after '-dot-'+ const re =+ /^(?<prefix>[a-z-]+)(?<uuid>[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-5][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})(-dot-(?<branch>.*))?/;+ const match = fragments[0].match(re);++ // Extract prefix, projectId (UUID), and branch (if exists)+ const prefix = match?.groups?.prefix;+ const projectId = match?.groups?.uuid;+ const branch = match?.groups?.branch;++ if (prefix !== buildProjectDomainPrefix) {+ return {+ projectId: undefined,+ sourceOrigin: url.origin,+ };+ }++ if (projectId === undefined) {+ return {+ projectId: undefined,+ sourceOrigin: url.origin,+ };+ }++ fragments[0] = fragments[0].replace(re, branch ?? "");++ const sourceUrl = new URL(url.origin);+ sourceUrl.protocol = "https";+ sourceUrl.host = fragments.filter(Boolean).join(".");++ return {+ projectId,+ sourceOrigin: sourceUrl.origin,+ };+};diff --git a/packages/protocol/src/fixture-projects.test.ts b/packages/protocol/src/fixtures.test.tssimilarity index 100%rename from packages/protocol/src/fixture-projects.test.tsrename to packages/protocol/src/fixtures.test.tsdiff --git a/packages/protocol/src/index.ts b/packages/protocol/src/index.tsindex 68c78b1bdb..a2a274783c 100644--- a/packages/protocol/src/index.ts+++ b/packages/protocol/src/index.ts@@ -4,3 +4,8 @@// stay owned by their packages and are imported through schema-only entrypoints// instead of being copied here.export * from "./schema";+export * from "./builder-api/operation-docs";+export * from "./builder-api/errors";+export * from "./builder-api/runtime-contracts";+export * from "./builder-api/operations";+export * from "./builder-api/url";diff --git a/packages/protocol/src/schema.test.ts b/packages/protocol/src/schema.test.tsindex 2069a38481..10ae5e1160 100644--- a/packages/protocol/src/schema.test.ts+++ b/packages/protocol/src/schema.test.ts@@ -1,4 +1,6 @@import { describe, expect, test } from "vitest";+import { builderNamespaces } from "@webstudio-is/project-build/contracts/namespaces";+import { builderPatchTransactionSchema } from "@webstudio-is/project-build/contracts/patch";import {isAssetFileName,getMissingImportedAssetFilesMessage,@@ -9,6 +11,8 @@ import {bundleVersion,stagedUploadPath,stagedUploadProjectIdHeader,+ buildPatchNamespaces,+ buildPatchTransaction,} from "./schema";import { createPublishedProjectBundleFixture } from "./fixtures";@@ -144,4 +148,39 @@ describe("project bundle contract", () => {`Project bundle format is incompatible. Expected version ${bundleVersion}, received missing. Sync with a compatible API/CLI version and retry, or override the check.`);});++ test("validates build patch transactions", () => {+ expect(buildPatchNamespaces).toBe(builderNamespaces);+ expect(buildPatchTransaction).toBe(builderPatchTransactionSchema);++ expect(+ buildPatchTransaction.safeParse({+ id: "tx-1",+ payload: [+ {+ namespace: "pages",+ patches: [+ {+ op: "replace",+ path: ["meta", "siteName"],+ value: "Site",+ },+ ],+ },+ ],+ }).success+ ).toBe(true);++ expect(+ buildPatchTransaction.safeParse({+ id: "tx-1",+ payload: [+ {+ namespace: "pages",+ patches: [{ op: "replace", path: ["meta", "siteName"] }],+ },+ ],+ }).success+ ).toBe(false);+ });});diff --git a/packages/protocol/src/schema.ts b/packages/protocol/src/schema.tsindex 68f3fcd33f..7cdf777189 100644--- a/packages/protocol/src/schema.ts+++ b/packages/protocol/src/schema.ts@@ -1,4 +1,9 @@import { asset, page } from "@webstudio-is/sdk/schema";+import { builderNamespaces } from "@webstudio-is/project-build/contracts/namespaces";+import {+ builderPatchSchema as internalBuilderPatchSchema,+ builderPatchTransactionSchema as internalBuilderPatchTransactionSchema,+} from "@webstudio-is/project-build/contracts/patch";import { serializedBuild } from "@webstudio-is/project-build/schema";import { wsAuthConfig } from "@webstudio-is/wsauth/schema";import { z } from "zod";@@ -95,6 +100,28 @@ export const checkProjectBuildPermissionInput = z.object({projectId: z.string().min(1),});+export const buildPatchNamespaces = builderNamespaces;+export type BuildPatchPath = Array<string | number>;+export type BuildPatch =+ | { op: "add"; path: BuildPatchPath; value: unknown }+ | { op: "replace"; path: BuildPatchPath; value: unknown }+ | { op: "remove"; path: BuildPatchPath };+export type BuildPatchChange = {+ namespace: (typeof buildPatchNamespaces)[number];+ patches: BuildPatch[];+};+export type BuildPatchTransaction = {+ id: string;+ payload: BuildPatchChange[];+};+export const buildPatch: z.ZodType<BuildPatch, z.ZodTypeDef, unknown> =+ internalBuilderPatchSchema;+export const buildPatchTransaction: z.ZodType<+ BuildPatchTransaction,+ z.ZodTypeDef,+ unknown+> = internalBuilderPatchTransactionSchema;+export const bundleVersion = createContractVersion(publishedProjectBundle, [wsAuthConfig,]);diff --git a/packages/sdk-components-animation/vitest.config.ts b/packages/sdk-components-animation/vitest.config.tsindex 8d4b156ac3..68528ef018 100644--- a/packages/sdk-components-animation/vitest.config.ts+++ b/packages/sdk-components-animation/vitest.config.ts@@ -1,5 +1,5 @@import { defineConfig } from "vitest/config";-import { existsSync, readdirSync } from "node:fs";+import { existsSync } from "node:fs";import path from "node:path";import fg from "fast-glob";diff --git a/packages/sync-client/src/transaction-utils.ts b/packages/sync-client/src/transaction-utils.tsindex 38b5d6d863..d89cc0def2 100644--- a/packages/sync-client/src/transaction-utils.ts+++ b/packages/sync-client/src/transaction-utils.ts@@ -30,9 +30,9 @@ export const stripRevisePatchesFromPayload = <Payload>(return nextPayload as Payload;};-export const stripRevisePatchesFromTransaction = (- transaction: Transaction-): Transaction => {+export const stripRevisePatchesFromTransaction = <Payload>(+ transaction: Transaction<Payload>+): Transaction<Payload> => {if (transaction.object !== "server") {return transaction;}diff --git a/packages/trpc-interface/package.json b/packages/trpc-interface/package.jsonindex 7d84f74a7a..dbfbc31403 100644--- a/packages/trpc-interface/package.json+++ b/packages/trpc-interface/package.json@@ -25,6 +25,7 @@"exports": {"./api-compatibility": {"webstudio": "./src/api-compatibility.ts",+ "types": "./src/api-compatibility.ts","import": "./src/api-compatibility.ts"},"./index.server": {diff --git a/packages/trpc-interface/src/context/errors.server.test.ts b/packages/trpc-interface/src/context/errors.server.test.tsnew file mode 100644index 0000000000..b89048c788--- /dev/null+++ b/packages/trpc-interface/src/context/errors.server.test.ts@@ -0,0 +1,25 @@+import { expect, test } from "vitest";+import {+ AuthorizationError,+ PlanRequiredError,+ createErrorResponse,+} from "./errors.server";++test("creates authorization and plan-required errors", () => {+ expect(new AuthorizationError("No access").message).toBe("No access");++ const error = new PlanRequiredError("Upgrade required");+ expect(error.message).toBe("Upgrade required");+ expect(error.code).toBe("PLAN_REQUIRED");+});++test("creates serializable error responses", () => {+ expect(createErrorResponse(new Error("Failed"))).toEqual({+ success: false,+ error: "Failed",+ });+ expect(createErrorResponse("Nope")).toEqual({+ success: false,+ error: "Nope",+ });+});diff --git a/packages/trpc-interface/src/context/errors.server.ts b/packages/trpc-interface/src/context/errors.server.tsindex 9d98feec43..da3a0bf92d 100644--- a/packages/trpc-interface/src/context/errors.server.ts+++ b/packages/trpc-interface/src/context/errors.server.ts@@ -6,6 +6,13 @@ export const AuthorizationError = customErrorFactory(});+export const PlanRequiredError = customErrorFactory(function PlanRequiredError(+ message: string+) {+ this.message = message;+ this.code = "PLAN_REQUIRED";+});+/*** Standard response for any client-server communication with an error.*/diff --git a/packages/trpc-interface/src/index.server.ts b/packages/trpc-interface/src/index.server.tsindex db79e82c17..9c6d3d435f 100644--- a/packages/trpc-interface/src/index.server.ts+++ b/packages/trpc-interface/src/index.server.ts@@ -10,6 +10,7 @@ export {export {AuthorizationError,+ PlanRequiredError,createErrorResponse,} from "./context/errors.server";export * as authorizeProject from "./authorize/project.server";diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 1280bc708b..0cbc0fb427 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -1109,6 +1109,9 @@ importers:packages/authorization-token:dependencies:+ '@trpc/server':+ specifier: ^10.45.2+ version: 10.45.2'@webstudio-is/postgrest':specifier: workspace:*version: link:../postgrest@@ -1143,12 +1146,18 @@ importers:'@trpc/client':specifier: ^10.45.2version: 10.45.2(@trpc/[email protected])+ '@webstudio-is/http-client':+ specifier: workspace:*+ version: link:../http-client+ '@webstudio-is/project-build':+ specifier: workspace:*+ version: link:../project-build'@webstudio-is/project-migrations':specifier: workspace:*version: link:../project-migrations- '@webstudio-is/trpc-interface':+ '@webstudio-is/protocol':specifier: workspace:*- version: link:../trpc-interface+ version: link:../protocolacorn:specifier: ^8.14.1version: 8.14.1@@ -1158,12 +1167,21 @@ importers:change-case:specifier: ^5.4.4version: 5.4.4+ chrome-launcher:+ specifier: ^1.2.1+ version: 1.2.1deepmerge:specifier: ^4.3.1version: 4.3.1env-paths:specifier: ^3.0.0version: 3.0.0+ fast-deep-equal:+ specifier: ^3.1.3+ version: 3.1.3+ immer:+ specifier: ^10.1.1+ version: 10.1.1nanoid:specifier: ^5.1.5version: 5.1.5@@ -1243,15 +1261,9 @@ importers:'@webstudio-is/css-engine':specifier: workspace:*version: link:../css-engine- '@webstudio-is/http-client':- specifier: workspace:*- version: link:../http-client'@webstudio-is/image':specifier: workspace:*version: link:../image- '@webstudio-is/protocol':- specifier: workspace:*- version: link:../protocol'@webstudio-is/react-sdk':specifier: workspace:*version: link:../react-sdk@@ -1708,6 +1720,9 @@ importers:'@webstudio-is/protocol':specifier: workspace:*version: link:../protocol+ '@webstudio-is/trpc-interface':+ specifier: workspace:*+ version: link:../trpc-interfacetus-js-client:specifier: ^4.3.1version: 4.3.1@@ -1906,9 +1921,18 @@ importers:packages/project-build:dependencies:+ '@modelcontextprotocol/sdk':+ specifier: ^1.10.0+ version: 1.10.0'@webstudio-is/authorization-token':specifier: workspace:*version: link:../authorization-token+ '@webstudio-is/css-data':+ specifier: workspace:*+ version: link:../css-data+ '@webstudio-is/css-engine':+ specifier: workspace:*+ version: link:../css-engine'@webstudio-is/postgrest':specifier: workspace:*version: link:../postgrest@@ -1924,6 +1948,15 @@ importers:'@webstudio-is/trpc-interface':specifier: workspace:*version: link:../trpc-interface+ fast-deep-equal:+ specifier: ^3.1.3+ version: 3.1.3+ fast-png:+ specifier: 8.0.0+ version: 8.0.0+ immer:+ specifier: ^10.1.1+ version: 10.1.1nanoid:specifier: ^5.1.5version: 5.1.5@@ -4232,6 +4265,10 @@ packages:'@mjackson/[email protected]':resolution: {integrity: sha512-EMlH1e30yzmTpGLQjlFmaDAjyOeZhng1/XCd7DExR8PNAnG/G1tyruZxEoUe11ClnwGhGrtsdnyyUx1frSzjng==}+ '@modelcontextprotocol/[email protected]':+ resolution: {integrity: sha512-wijOavYZfSOADbVM0LA7mrQ17N4IKNdFcfezknCCsZ1Y1KstVWlkDZ5ebcxuQJmqTTxsNjBHLc7it1SV0TBiPg==}+ engines: {node: '>=18'}+'@mswjs/[email protected]':resolution: {integrity: sha512-cXu86tF4VQVfwz8W1SPbhoRyHJkti6mjH/XJIxp40jhO4j2k1m4KYrEykxqWPkFF3vrK4rgQppBh//AwyGSXPA==}engines: {node: '>=18'}@@ -6154,6 +6191,10 @@ packages:resolution: {integrity: sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw==}engines: {node: '>= 0.6'}+ resolution: {integrity: sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng==}+ engines: {node: '>= 0.6'}+resolution: {integrity: sha512-umOSDSDrfHbTNPuNpC2NSnnA3LUrqpevPb4T9jRx4MagXNS0rs+gwiTcAvqCRmsD6utzsrzNt+ebm00SNWiC3Q==}@@ -6326,6 +6367,10 @@ packages:resolution: {integrity: sha512-7rAxByjUMqQ3/bHJy7D6OGXvx/MMc4IqBn/X0fcM1QUcAItpZrBEYhWGem+tzXH90c+G01ypMcYJBO9Y30203g==}engines: {node: '>= 0.8', npm: 1.2.8000 || >= 1.4.16}+ resolution: {integrity: sha512-2cGmJupaNgg+QUwVLAucDuWuoMZ6EX9iHDRswZ5lsNYEmwPaRknMPCLZz07yTzVq/83p4o/wzbDZbBrTvGGTIw==}+ engines: {node: '>=18'}+resolution: {integrity: sha512-JZOSA7Mo9sNGB8+UjSgzdLtokWAky1zbztM3WRLCbZ70/3cTANmQmOdR7y2g+J0e2WXywy1yS468tY+IruqEww==}@@ -6401,6 +6446,10 @@ packages:resolution: {integrity: sha512-GHTSNSYICQ7scH7sZ+M2rFopRoLh8t2bLSW6BbgrtLsahOIB5iyAVJf9GjWK3cYTDaMj4XdBpM1cA6pIS0Kv2w==}engines: {node: '>= 0.4'}+ resolution: {integrity: sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==}+ engines: {node: '>= 0.4'}+resolution: {integrity: sha512-5ExiE3qQN6oF8Clf8ifIDcMRCRE/dMGcETG/XGMD8/XiXm6HXQgQTh1yZYLXXpSOsEUlJm1Xr7kGULZTuGtP/w==}@@ -6452,6 +6501,11 @@ packages:resolution: {integrity: sha512-bIomtDF5KGpdogkLd9VspvFzk9KfpyyGlS8YFVZl7TGPBHL5snIOnxeshwVgPteQ9b4Eydl+pVbIyE1DcvCWgQ==}engines: {node: '>=10'}+ resolution: {integrity: sha512-qmFR5PLMzHyuNJHwOloHPAHhbaNglkfeV/xDtt5b7xiFFyU1I+AZZX0PYseMuhenJSSirgxELYIbswcoc+5H4A==}+ engines: {node: '>=12.13.0'}+ hasBin: true+resolution: {integrity: sha512-tskPPKEs8D2KPafUypv2gxwJP8h/OaJmC82QQGGDQcHvXX43xF2VDACcJVmZ0EuSxkpO9Kc4MlrA3q0+FG58AQ==}@@ -6574,10 +6628,18 @@ packages:resolution: {integrity: sha512-FveZTNuGw04cxlAiWbzi6zTAL/lhehaWbTtgluJh4/E95DqMwTmha3KZN1aAWA8cFIhHzMZUvLevkw5Rqk+tSQ==}engines: {node: '>= 0.6'}+ resolution: {integrity: sha512-5jRCH9Z/+DRP7rkvY83B+yGIGX96OYdJmzngqnw2SBSxqCFPd0w2km3s5iawpGX8krnwSGmF0FW5Nhr0Hfai3g==}+ engines: {node: '>=18'}+resolution: {integrity: sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==}engines: {node: '>= 0.6'}+ resolution: {integrity: sha512-j/O/d7GcZCyNl7/hwZAb606rzqkyvaDctLmckbxLzHvFBzTJHuGEdodATcP3yIRoDrLHkIATJuvzbFlp/ki2cQ==}+ engines: {node: '>=18'}+resolution: {integrity: sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==}@@ -6591,6 +6653,10 @@ packages:resolution: {integrity: sha512-R0BOPfLGTitaKhgKROKZQN6iyq2iDQcH1DOF8nJoaWapguX5bC2w+Q/I9NmmM5lfcvEarnLZr+cCvmEYYSXvYA==}engines: {node: '>=6.6.0'}+ resolution: {integrity: sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg==}+ engines: {node: '>=6.6.0'}+resolution: {integrity: sha512-YZ3GUyn/o8gfKJlnlX7g7xq4gyO6OSuhGPKaaGssGB2qgDUS0gPgtTvoyZLTt9Ab6dC4hfc9dV5arkvc/OCmrw==}engines: {node: '>= 0.6'}@@ -6614,6 +6680,10 @@ packages:resolution: {integrity: sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==}+ resolution: {integrity: sha512-tJtZBBHA6vjIAaF6EnIaq6laBBP9aq/Y3ouVJjEfoHbRBcHBAHYcMh/w8LDrk2PvIMMq8gmopa5D4V8RmbrxGw==}+ engines: {node: '>= 0.10'}+resolution: {integrity: sha512-VQ2MBenTq1fWZUH9DJNGti7kKv6EeAuYr3cLwxUWhIu1baTaXh4Ib5W2CqHVqib4/MqbYGJqiL3Zb8GJZr3l4g==}@@ -6903,10 +6973,6 @@ packages:resolution: {integrity: sha512-2bmlRpNKBxT/CRmPOlyISQpNj+qSeYvcym/uT0Jx2bMOlKLtSy1ZmLuVxSEKKyor/N5yhvp/ZiG1oE3DEYMSFA==}- resolution: {integrity: sha512-jxayLKShrEqqzJ0eumQbVhTYQM27CfT1T35+gCgDFoL82JLsXqTJ76zv6A0YLOgEnLUMvLzsDsGIrl8NFpT2gQ==}- engines: {node: '>= 0.4'}-resolution: {integrity: sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==}engines: {node: '>= 0.4'}@@ -7046,6 +7112,14 @@ packages:resolution: {integrity: sha512-i/2XbnSz/uxRCU6+NdVJgKWDTM427+MqYbkQzD321DuCQJUqOuJKIA0IM2+W2xtYHdKOmZ4dR6fExsd4SXL+WQ==}engines: {node: '>=6'}+ resolution: {integrity: sha512-kJezFj9YFAMLeORyi7aCLxLbD5/qWMQnoMVlVPyHIll7lgRJCc3JVln9Vgl9nwQi0YkMnhdGTMNn7CkRRAptMg==}+ engines: {node: '>=18.0.0'}++ resolution: {integrity: sha512-CRT1WTyuQoD771GW56XEZFQ/ZoSfWid1alKGDYMmkt2yl8UXrVR4pspqWNEcqKvVIzg6PAltWjxcSSPrboA4iA==}+ engines: {node: '>=18.0.0'}+resolution: {integrity: sha512-8uSpZZocAZRBAPIEINJj3Lo9HyGitllczc27Eh5YYojjMFMn8yHMDMaUHE2Jqfq05D/wucwI4JGURyXt1vchyg==}engines: {node: '>=10'}@@ -7066,10 +7140,20 @@ packages:resolution: {integrity: sha512-/kP8CAwxzLVEeFrMm4kMmy4CCDlpipyA7MYLVrdJIkV0fYF0UaigQHRsxHiuY/GEea+bh4KSv3TIlgr+2UL6bw==}engines: {node: '>=12.0.0'}+ resolution: {integrity: sha512-7iN8iPMDzOMHPUYllBEsQdWVB6fPDMPqwjBaFrgr4Jgr/+okjvzAy+UHlYYL/Vs0OsOrMkwS6PJDkFlJwoxUnw==}+ engines: {node: '>= 16'}+ peerDependencies:+ express: '>= 4.11'+resolution: {integrity: sha512-YSFlK1Ee0/GC8QaO91tHcDxJiE/X4FbpAyQWkxAvG6AXCuR65YzK8ua6D9hvi/TzUfZMpc+BwuM1IPw8fmQBiQ==}engines: {node: '>= 0.10.0'}+ resolution: {integrity: sha512-hIS4idWWai69NezIdRt2xFVofaF4j+6INOpJlVOLDO8zXGpUVEVzIYk12UUi2JzjEzWL3IOAxcTubgz9Po0yXw==}+ engines: {node: '>= 18'}+resolution: {integrity: sha512-pz5dvkYYKQ1AHVrgOzBKWeP4u4FRb3a6DNK2ucr0OoNwYIU4QWsJ+NM36LLzORT+z845MzKHHhpXiUF5nvQoJg==}@@ -7086,6 +7170,9 @@ packages:resolution: {integrity: sha512-oX2ruAFQwf/Orj8m737Y5adxDQO0LAB7/S5MnxCdTNDd4p6BsyIVsv9JQsATbTSq8KHRpLwIHbVlUNatxd+1Ow==}engines: {node: '>=8.6.0'}+ resolution: {integrity: sha512-gCysNasJ8KEMgfdYIKd/wTDo6ENK1PWT0RJO7O+0pgmuHPw2O6tA1WvdxFRJoLf9V8yFYpG0FA1YgI8X97OhJA==}+resolution: {integrity: sha512-g6KuKWmFXc0fID8WWH0jit4g0AGBoJhCkJMb1RmbsSEUNvQ+ZC8D6CUZ+GtF8nMzSPXnhiePyyqqipzNNEnHjg==}@@ -7103,6 +7190,9 @@ packages:picomatch:optional: true+ resolution: {integrity: sha512-tbZNuJrLwGUp3zshBtdy4W+ORxZuIh8a5ilyIEQDC5rY1f3U20JMry0Ll3WBzU58EZKsEuJFXhb5gwv8CsPvgA==}+resolution: {integrity: sha512-hn4cQfU6GOT/7cFHXBqeBg2TbrMBgdD0kcjLhvSQYYwm3s4B6cjvBfb7nBALJLAXqmU5xajSa7X2NnUud/VCdw==}engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0}@@ -7115,6 +7205,10 @@ packages:resolution: {integrity: sha512-6BN9trH7bp3qvnrRyzsBz+g3lZxTNZTbVO2EV1CS0WIcDbawYVdYvGflME/9QP0h0pYlCDBCTjYa9nZzMDpyxQ==}engines: {node: '>= 0.8'}+ resolution: {integrity: sha512-S8KoZgRZN+a5rNwqTxlZZePjT/4cnm0ROV70LedRHZ0p8u9fRID0hJUZQpkKLzro8LfmC8sx23bY6tVNxv8pQA==}+ engines: {node: '>= 18.0.0'}+resolution: {integrity: sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng==}engines: {node: '>=10'}@@ -7158,6 +7252,10 @@ packages:resolution: {integrity: sha512-zJ2mQYM18rEFOudeV4GShTGIQ7RbzA7ozbU9I/XBpm7kqgMywgmylMwXHxZJmkVoYkna9d2pVXVXPdYTP9ej8Q==}engines: {node: '>= 0.6'}+ resolution: {integrity: sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A==}+ engines: {node: '>= 0.8'}+resolution: {integrity: sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow==}@@ -7380,6 +7478,10 @@ packages:resolution: {integrity: sha512-FtwrG/euBzaEjYeRqOgly7G0qviiXoJWnvEH2Z1plBdXgbyjv34pHTSb9zoeHMyDy33+DWy5Wt9Wo+TURtOYSQ==}engines: {node: '>= 0.8'}+ resolution: {integrity: sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==}+ engines: {node: '>= 0.8'}+resolution: {integrity: sha512-n2hY8YdoRE1i7r6M0w9DIw5GgZN0G25P8zLCRQ8rjXtTU3vsNFBI/vWK/UIeE6g5MUUz6avwAPXmL6Fy9D/90w==}engines: {node: '>= 6'}@@ -7412,6 +7514,10 @@ packages:resolution: {integrity: sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==}engines: {node: '>=0.10.0'}+ resolution: {integrity: sha512-im9DjEDQ55s9fL4EYzOAv0yMqmMBSZp6G0VvFyTMPKWxiSBHUj9NW/qqLmXUwXrrM7AvqSlTCfvqRb0cM8yYqw==}+ engines: {node: '>=0.10.0'}+resolution: {integrity: sha512-soFhflCVWLfRNOPU3iv5Z9VUdT44xFRbzjLsEzSr5AQmgqPMTHdU3PMT1Cf1ssx8fLNJDA1juftYl+PUcv3MqA==}engines: {node: ^10 || ^12 || >= 14}@@ -7448,6 +7554,9 @@ packages:resolution: {integrity: sha512-7NXolsK4CAS5+xvdj5OMMbI962hU/wvwoxk+LWR9Ek9bVtyuuYScDN6eS0rUm6TxApFpw7CX1o4uJzcd4AyD3Q==}+ resolution: {integrity: sha512-SZWYkWNfjIXIBYSDpXDYIgshqtbOPsi4lviawAEceR1Kqk+sHDlcQjWrzNQsii80AyBY0q5c8HCTNjqo74ul+Q==}+resolution: {integrity: sha512-ehuGcf94bQXhfagULNXrJdfnWO38v070jxSx/qE87Kjzmu2fU7ro5EFAb+OPituLqgfyuQaym5DlrNydW2sJ9A==}engines: {node: '>=12.22.0'}@@ -7561,6 +7670,9 @@ packages:resolution: {integrity: sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==}+ resolution: {integrity: sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==}+resolution: {integrity: sha512-baJJdQLiYaJdvFbJqXrcGv3WU3QCzBlUcI5QhbesIm6/xPsvmO+2CDoi/GMOFBQEQm+PXkwOPrp9KK5ozZsp2w==}@@ -7702,6 +7814,9 @@ packages:engines: {node: '>=16'}hasBin: true+ resolution: {integrity: sha512-vWl2+u5jgOQuZR55Z1WM0XDdrJT6mzMP8zHUct7xTlWhuQs+eV0g+QL0RQdFjT54zVmbhLCP8vIVpy1wGn/gCg==}+resolution: {integrity: sha512-utWOt/GHzuUxnLKxB6dk81RoOeoNeHgbrXiuGk4yyF5qlRz+iIVWu56E2fqGHFrXz0QNUhLB/8nKqvRH66JKGQ==}engines: {node: '>=10'}@@ -7814,6 +7929,9 @@ packages:resolution: {integrity: sha512-WWC0ZuMzCyDHYCasEGs4IPvLyTGftYwh6wIEOULOF0HXcqZlhwRzrK0w2VUlxWA98xnvb/jszw4ZSkJ6ADpM6Q==}engines: {node: '>=0.10.0'}+ resolution: {integrity: sha512-ocnPZQLNpvbedwTy9kNrQEsknEfgvcLMvOtz3sFeWApDq1MXH1TqkCIx58xlpESsfwQOnuBO9beyQuNGzVvuhQ==}+resolution: {integrity: sha512-bGJ6Zb+OhzXe+ptP5d80OLVx7AkqfRbtGEh30vNSfjNwllu+hHI+tcbMIT/fbkx/FKN1PmKuDb65+Oofg+XUxw==}@@ -7873,6 +7991,10 @@ packages:resolution: {integrity: sha512-dq+qelQ9akHpcOl/gUVRTxVIOkAJ1wR3QAvb4RsVjS8oVoFjDGTc679wJYmUmknUF5HwMLOgb5O+a3KxfWapPQ==}engines: {node: '>= 0.6'}+ resolution: {integrity: sha512-aisnrDP4GNe06UcKFnV5bfMNPBUw4jsLGaWwWfnH3v02GnBuXX2MCVn5RbrWo0j3pczUilYblq7fQ7Nw2t5XKw==}+ engines: {node: '>= 0.8'}+resolution: {integrity: sha512-H6cBLgsi6vMWOcCpvVCdFFnl3kerEXbrYh9q+lY6VXvQSmM6CkmV08VOwT+WE2tzIEqRPFfAq3fm4v/UIW6mSA==}engines: {node: '>=18'}@@ -7883,6 +8005,10 @@ packages:resolution: {integrity: sha512-gaNvAS7TZ897/rVaZ0nMtAyxNyi/pdbjbAwUpFQpN70GqnVfOiXpeUUMKRBmzXaSQ8DdTX4/0ms62r2K+hE6mQ==}+ resolution: {integrity: sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g==}+ engines: {node: '>=18'}+resolution: {integrity: sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==}@@ -8070,10 +8196,18 @@ packages:resolution: {integrity: sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==}engines: {node: '>= 0.6'}+ resolution: {integrity: sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==}+ engines: {node: '>= 0.6'}+resolution: {integrity: sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==}engines: {node: '>= 0.6'}+ resolution: {integrity: sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A==}+ engines: {node: '>=18'}+resolution: {integrity: sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg==}engines: {node: '>=4'}@@ -8250,6 +8384,10 @@ packages:resolution: {integrity: sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg==}engines: {node: '>= 0.6'}+ resolution: {integrity: sha512-8Ofs/AUQh8MaEcrlq5xOX0CQ9ypTF5dl78mjlMNfOK08fzpgTHQRQPBxcPlEtIw0yRpws+Zo/3r+5WRby7u3Gg==}+ engines: {node: '>= 0.6'}+resolution: {integrity: sha512-5m3bsyrjFWE1xf7nz7YXdN4udnVtXK6/Yfgn5qnahL6bCkf2yKt4k3nuTKAtT4r3IG8JNR2ncsIMdZuAzJjHQQ==}@@ -8321,6 +8459,10 @@ packages:resolution: {integrity: sha512-kDCGIbxkDSXE3euJZZXzc6to7fCrKHNI/hSRQnRuQ+BWjFNzZwiFF8fj/6o2t2G9/jTj8PSIYTfCLelLZEeRpA==}engines: {node: '>= 0.4'}+ resolution: {integrity: sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==}+ engines: {node: '>= 0.4'}+resolution: {integrity: sha512-QZj2DfGplQAr2oj9KzceK9Hwz6Whxazmn85yYeVuS3u9XTMOGMRx0kO95MQ+vLsj/S/NwBDMMLU5hpxvI6Tklw==}@@ -8470,6 +8612,9 @@ packages:resolution: {integrity: sha512-Yhpw4T9C6hPpgPeA28us07OJeqZ5EzQTkbfwuhsUg0c237RomFoETJgmp2sa3F/41gfLE6G5cqcYwznmeEeOlQ==}+ resolution: {integrity: sha512-qRcuIdP69NPm4qbACK+aDogI5CBDMi1jKe0ry5rSQJz8JVLsC7jV8XpiJjGRLLol3N+R5ihGYcrPLTno6pAdBA==}+resolution: {integrity: sha512-whLdWMYL2TwI08hn8/ZqAbrVemu0LNaNNJZX73O6qaIdCTfXutsLhMkjdENX0qhsQ9uIimo4/aQOmXkoon2nDQ==}@@ -8505,6 +8650,10 @@ packages:engines: {node: '>=0.10'}hasBin: true+ resolution: {integrity: sha512-wQ0b/W4Fr01qtpHlqSqspcj3EhBvimsdh0KlHhH8HRZnMsEa0ea2fTULOXOS9ccQr3om+GcGRk4e+isrZWV8qQ==}+ engines: {node: '>=16.20.0'}+resolution: {integrity: sha512-/Jm5M4RvtBFVkKWRu2BLUTNP8/M2a+UwuAX+ae4770q1qVGtfjG+WTCupoZixokjmHiry8uI+dlY8KXYV5HVVQ==}@@ -8682,6 +8831,10 @@ packages:resolution: {integrity: sha512-+38qI9SOr8tfZ4QmJNplMUxqjbe7LKvvZgWdExBOmd+egZTtjLB67Gu0HRX3u/XOq7UU2Nx6nsjvS16Z9uwfpg==}engines: {node: '>=0.6'}+ resolution: {integrity: sha512-O9gl3zCl5h5blw1KGUzQKhA5oUXSl8rwUIM5o0S3nCXMliSvy5Dzx7/DJcI+SwgICv+IneSZwhBh1oSyEHA71A==}+ engines: {node: '>=0.6'}+resolution: {integrity: sha512-FIqgj2EUvTa7R50u0rGsyTftzjYmv/a3hO345bZNrqabNqjtgiDMgmo4mkUjd+nzU5oF3dClKqFIPUKybUyqoQ==}@@ -8702,6 +8855,10 @@ packages:resolution: {integrity: sha512-8zGqypfENjCIqGhgXToC8aB2r7YrBX+AQAfIPs/Mlk+BtPTztOvTS01NRW/3Eh60J+a48lt8qsCzirQ6loCVfA==}engines: {node: '>= 0.8'}+ resolution: {integrity: sha512-K5zQjDllxWkf7Z5xJdV0/B0WTNqx6vxG70zJE4N0kBs4LovmEYWJzQGxC9bS9RAKu3bgM40lrd5zoLJ12MQ5BA==}+ engines: {node: '>= 0.10'}+resolution: {integrity: sha512-1exovf0uGTGyq5mXQT0zgQ80uvj2PCwvF8zY1RN9/vbJVSjSo3fsB/4L3ObbF7u70NduSiK4xu4Y6q1MHoUGEw==}peerDependencies:@@ -9000,6 +9157,10 @@ packages:engines: {node: '>=18.0.0', npm: '>=8.0.0'}hasBin: true+ resolution: {integrity: sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ==}+ engines: {node: '>= 18'}+resolution: {integrity: sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA==}@@ -9045,10 +9206,18 @@ packages:resolution: {integrity: sha512-dW41u5VfLXu8SJh5bwRmyYUbAoSB3c9uQh6L8h/KtsFREPWpbX1lrljJo186Jc4nmci/sGUZ9a0a0J2zgfq2hw==}engines: {node: '>= 0.8.0'}+ resolution: {integrity: sha512-1gnZf7DFcoIcajTjTwjwuDjzuz4PPcY2StKPlsGAQ1+YH20IRVrBaXSWmdjowTJ6u8Rc01PoYOGHXfP1mYcZNQ==}+ engines: {node: '>= 18'}+resolution: {integrity: sha512-VqpjJZKadQB/PEbEwvFdO43Ax5dFBZ2UECszz8bQ7pi7wt//PWe1P6MN7eCnjsatYtBT6EuiClbjSWP2WrIoTw==}engines: {node: '>= 0.8.0'}+ resolution: {integrity: sha512-xRXBn0pPqQTVQiC8wyQrKs2MOlX24zQ0POGaj0kultvoOCstBQM5yvOhAVSUwOMjQtTvsPWoNCHfPGwaaQJhTw==}+ engines: {node: '>= 18'}+resolution: {integrity: sha512-RVnVQxTXuerk653XfuliOxBP81Sf0+qfQE73LIYKcyMYHG94AuH0kgrQpRDuTZnSmjpysHmzxJXKNfa6PjFhyQ==}@@ -9077,10 +9246,26 @@ packages:resolution: {integrity: sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==}engines: {node: '>=8'}+ resolution: {integrity: sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w==}+ engines: {node: '>= 0.4'}++ resolution: {integrity: sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==}+ engines: {node: '>= 0.4'}++ resolution: {integrity: sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==}+ engines: {node: '>= 0.4'}+resolution: {integrity: sha512-fDW/EZ6Q9RiO8eFG8Hj+7u/oW+XrPTIChwCOM2+th2A6OblDtYYIpve9m+KvI9Z4C9qSEXlaGR6bTEYHReuglA==}engines: {node: '>= 0.4'}+ resolution: {integrity: sha512-6x6dK6zJdpTzF4sQeNYxwtvBzf6Eg4GtlesS94HOvTudUeyK2WXAaIfmDgsyslYrRBeFIlsi54AYsFGUuhmvrQ==}+ engines: {node: '>= 0.4'}+resolution: {integrity: sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==}@@ -9440,6 +9625,10 @@ packages:resolution: {integrity: sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==}engines: {node: '>= 0.6'}+ resolution: {integrity: sha512-faYHw0anBbc/kWF3zFTEnxSFOAGUX9GFbOBthvDdLsIlEoWOFOtS0zgCiQYwIskL9iGXZL3kAXD8OoZ4GmMATA==}+ engines: {node: '>= 18'}+resolution: {integrity: sha512-aJn6wq13/afZp/jT9QZmwEjDqqvSGp1VT5GVg+f/t6/oVyrgXM6BY1h9BRh/O5p3PlUPAe+WuiEZOmb/49RqoQ==}engines: {node: '>=14.17'}@@ -10066,6 +10255,11 @@ packages:resolution: {integrity: sha512-UeVBXie8cA35DS6+nBkls68xaBBXCye0CNznrhszZjTbRVnJKQuNsyLKBTTL4ln1o1rh2PKtv35twV7irj5SEg==}+ resolution: {integrity: sha512-O/PgfnpT1xKSDeQYSCfRI5Gy3hPf91mKVDuYLUHZJMiDFptvP41MSnWofm8dnCm0256ZNfZIM7DSzuSMAFnjHA==}+ peerDependencies:+ zod: ^3.25.28 || ^4+resolution: {integrity: sha512-ZOPR9SVY6Pb2qqO5XHt+MkkTRxGXb4EVtnjc9JpXUOtUB1T9Ru7mZOT361AN3MsetVe7R0a1KZshJDZdgp9miQ==}engines: {node: '>=18.0.0'}@@ -10078,6 +10272,9 @@ packages:resolution: {integrity: sha512-lY7CDW43ECgW9u1TcT3IoXHflywfVqDYze4waEz812jR/bZ8FHDsl7pFQoSZTz5N+2NqRXs8GBwnAwo3ZNxqhQ==}+ resolution: {integrity: sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==}+resolution: {integrity: sha512-bXE4cR/kVZhKZX/RjPEflHaKVhUVl85noU3v6b8apfQEc1x4A+zBxjZ4lN8LqGd6WZ3dl98pY4o717VFmoPp+A==}@@ -11735,6 +11932,21 @@ snapshots:'@mjackson/[email protected]': {}+ '@modelcontextprotocol/[email protected]':+ dependencies:+ content-type: 1.0.5+ cors: 2.8.6+ cross-spawn: 7.0.6+ eventsource: 3.0.7+ express: 5.2.1+ express-rate-limit: 7.5.1([email protected])+ pkce-challenge: 5.0.1+ raw-body: 3.0.2+ zod: 3.25.76+ zod-to-json-schema: 3.25.2([email protected])+ transitivePeerDependencies:+ - supports-color+'@mswjs/[email protected]':dependencies:'@open-draft/deferred-promise': 2.2.0@@ -14006,6 +14218,11 @@ snapshots:mime-types: 2.1.35negotiator: 0.6.3+ dependencies:+ mime-types: 3.0.2+ negotiator: 1.0.0+dependencies:acorn: 8.16.0@@ -14181,6 +14398,20 @@ snapshots:transitivePeerDependencies:- supports-color+ dependencies:+ bytes: 3.1.2+ content-type: 2.0.0+ debug: 4.4.3+ http-errors: 2.0.1+ iconv-lite: 0.7.2+ on-finished: 2.4.1+ qs: 6.15.3+ raw-body: 3.0.2+ type-is: 2.1.0+ transitivePeerDependencies:+ - supports-color+@@ -14270,12 +14501,17 @@ snapshots:dependencies:- es-define-property: 1.0.0+ es-define-property: 1.0.1es-errors: 1.3.0function-bind: 1.1.2get-intrinsic: 1.2.4set-function-length: 1.2.2+ dependencies:+ call-bind-apply-helpers: 1.0.2+ get-intrinsic: 1.3.0+@@ -14332,6 +14568,15 @@ snapshots:+ dependencies:+ '@types/node': 22.13.10+ escape-string-regexp: 4.0.0+ is-wsl: 2.2.0+ lighthouse-logger: 2.0.2+ transitivePeerDependencies:+ - supports-color+dependencies:consola: 3.4.2@@ -14449,8 +14694,12 @@ snapshots:dependencies:safe-buffer: 5.2.1+ [email protected]: {}++ [email protected]: {}+@@ -14459,6 +14708,8 @@ snapshots:+ [email protected]: {}+@@ -14471,6 +14722,11 @@ snapshots:+ dependencies:+ object-assign: 4.1.1+ vary: 1.1.2+@@ -14583,7 +14839,7 @@ snapshots:dependencies:- es-define-property: 1.0.0+ es-define-property: 1.0.1es-errors: 1.3.0gopd: 1.0.1@@ -14707,10 +14963,6 @@ snapshots:- dependencies:- get-intrinsic: 1.3.0-@@ -14973,6 +15225,12 @@ snapshots:+ [email protected]: {}++ dependencies:+ eventsource-parser: 3.1.0+dependencies:cross-spawn: 7.0.6@@ -15013,6 +15271,10 @@ snapshots:+ dependencies:+ express: 5.2.1+dependencies:accepts: 1.3.8@@ -15049,6 +15311,39 @@ snapshots:transitivePeerDependencies:- supports-color+ dependencies:+ accepts: 2.0.0+ body-parser: 2.3.0+ content-disposition: 1.1.0+ content-type: 1.0.5+ cookie: 0.7.2+ cookie-signature: 1.2.2+ debug: 4.4.3+ depd: 2.0.0+ encodeurl: 2.0.0+ escape-html: 1.0.3+ etag: 1.8.1+ finalhandler: 2.1.1+ fresh: 2.0.0+ http-errors: 2.0.1+ merge-descriptors: 2.0.0+ mime-types: 3.0.2+ on-finished: 2.4.1+ once: 1.4.0+ parseurl: 1.3.3+ proxy-addr: 2.0.7+ qs: 6.15.3+ range-parser: 1.2.1+ router: 2.2.0+ send: 1.2.1+ serve-static: 2.2.1+ statuses: 2.0.2+ type-is: 2.1.0+ vary: 1.1.2+ transitivePeerDependencies:+ - supports-color+@@ -15065,6 +15360,11 @@ snapshots:merge2: 1.4.1micromatch: 4.0.5+ dependencies:+ fflate: 0.8.3+ iobuffer: 6.0.1+dependencies:fast-decode-uri-component: 1.0.1@@ -15081,6 +15381,8 @@ snapshots:optionalDependencies:picomatch: 4.0.2+ [email protected]: {}+@@ -15099,6 +15401,17 @@ snapshots:transitivePeerDependencies:- supports-color+ dependencies:+ debug: 4.4.3+ encodeurl: 2.0.0+ escape-html: 1.0.3+ on-finished: 2.4.1+ parseurl: 1.3.3+ statuses: 2.0.2+ transitivePeerDependencies:+ - supports-color+dependencies:locate-path: 6.0.0@@ -15148,6 +15461,8 @@ snapshots:+ [email protected]: {}+@@ -15324,7 +15639,7 @@ snapshots:dependencies:- es-define-property: 1.0.0+ es-define-property: 1.0.1@@ -15404,6 +15719,14 @@ snapshots:statuses: 2.0.1toidentifier: 1.0.1+ dependencies:+ depd: 2.0.0+ inherits: 2.0.4+ setprototypeof: 1.2.0+ statuses: 2.0.2+ toidentifier: 1.0.1+dependencies:'@tootallnate/once': 2.0.0@@ -15438,6 +15761,10 @@ snapshots:safer-buffer: 2.1.2optional: true+ dependencies:+ safer-buffer: 2.1.2+dependencies:postcss: 8.5.3@@ -15466,6 +15793,8 @@ snapshots:+ [email protected]: {}+dependencies:'@ioredis/commands': 1.10.0@@ -15590,6 +15919,8 @@ snapshots:optional: true+ [email protected]: {}+dependencies:'@types/estree': 1.0.7@@ -15740,6 +16071,13 @@ snapshots:dependencies:isomorphic.js: 0.2.5+ dependencies:+ debug: 4.4.3+ marky: 1.3.0+ transitivePeerDependencies:+ - supports-color+@@ -15861,6 +16199,8 @@ snapshots:+ [email protected]: {}+dependencies:'@babel/runtime': 7.25.0@@ -15989,6 +16329,8 @@ snapshots:+ [email protected]: {}+dependencies:mimic-function: 5.0.1@@ -15999,6 +16341,8 @@ snapshots:+ [email protected]: {}+@@ -16409,10 +16753,16 @@ snapshots:+ [email protected]: {}+dependencies:mime-db: 1.52.0+ dependencies:+ mime-db: 1.54.0+@@ -16440,7 +16790,7 @@ snapshots:workerd: 1.20240701.0ws: 8.18.0youch: 3.3.3- zod: 3.24.2+ zod: 3.25.76transitivePeerDependencies:- bufferutil- supports-color@@ -16587,6 +16937,8 @@ snapshots:+ [email protected]: {}+@@ -16656,6 +17008,8 @@ snapshots:+ [email protected]: {}+dependencies:destr: 2.0.3@@ -16820,6 +17174,8 @@ snapshots:+ [email protected]: {}+@@ -16848,6 +17204,8 @@ snapshots:+ [email protected]: {}+dependencies:confbox: 0.1.8@@ -17013,6 +17371,11 @@ snapshots:dependencies:side-channel: 1.0.6+ dependencies:+ es-define-property: 1.0.1+ side-channel: 1.1.1+@@ -17030,6 +17393,13 @@ snapshots:iconv-lite: 0.4.24unpipe: 1.0.0+ dependencies:+ bytes: 3.1.2+ http-errors: 2.0.1+ iconv-lite: 0.7.2+ unpipe: 1.0.0+dependencies:react: 18.3.0-canary-14898b6a9-20240318@@ -17364,6 +17734,16 @@ snapshots:'@rollup/rollup-win32-x64-msvc': 4.40.0fsevents: 2.3.3+ dependencies:+ debug: 4.4.3+ depd: 2.0.0+ is-promise: 4.0.0+ parseurl: 1.3.3+ path-to-regexp: 8.4.2+ transitivePeerDependencies:+ - supports-color+dependencies:queue-microtask: 1.2.3@@ -17415,6 +17795,22 @@ snapshots:transitivePeerDependencies:- supports-color+ dependencies:+ debug: 4.4.3+ encodeurl: 2.0.0+ escape-html: 1.0.3+ etag: 1.8.1+ fresh: 2.0.0+ http-errors: 2.0.1+ mime-types: 3.0.2+ ms: 2.1.3+ on-finished: 2.4.1+ range-parser: 1.2.1+ statuses: 2.0.2+ transitivePeerDependencies:+ - supports-color+dependencies:encodeurl: 2.0.0@@ -17424,6 +17820,15 @@ snapshots:transitivePeerDependencies:- supports-color+ dependencies:+ encodeurl: 2.0.0+ escape-html: 1.0.3+ parseurl: 1.3.3+ send: 1.2.1+ transitivePeerDependencies:+ - supports-color+@@ -17473,6 +17878,26 @@ snapshots:+ dependencies:+ es-errors: 1.3.0+ object-inspect: 1.13.4++ dependencies:+ call-bound: 1.0.4+ es-errors: 1.3.0+ get-intrinsic: 1.3.0+ object-inspect: 1.13.4++ dependencies:+ call-bound: 1.0.4+ es-errors: 1.3.0+ get-intrinsic: 1.3.0+ object-inspect: 1.13.4+ side-channel-map: 1.0.1+dependencies:call-bind: 1.0.7@@ -17480,6 +17905,14 @@ snapshots:get-intrinsic: 1.3.0object-inspect: 1.13.3+ dependencies:+ es-errors: 1.3.0+ object-inspect: 1.13.4+ side-channel-list: 1.0.1+ side-channel-map: 1.0.1+ side-channel-weakmap: 1.0.2+@@ -17814,6 +18247,12 @@ snapshots:media-typer: 0.3.0mime-types: 2.1.35+ dependencies:+ content-type: 2.0.0+ media-typer: 1.1.0+ mime-types: 3.0.2+@@ -18453,6 +18892,10 @@ snapshots:mustache: 4.2.0stacktracey: 2.1.8+ dependencies:+ zod: 3.25.76+dependencies:zod: 3.24.2@@ -18461,4 +18904,6 @@ snapshots:+ [email protected]: {}+diff --git a/vitest.config.ts b/vitest.config.tsindex db3b75f37a..f6c57baafb 100644--- a/vitest.config.ts+++ b/vitest.config.ts@@ -5,7 +5,6 @@ import {} from "vite";export default defineConfig({- // resolve webstudio condition in testsresolve: {conditions: ["webstudio", ...defaultClientConditions],},