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: Add safer MCP authoring and draft-page verification (#5905)
Oleg Isonend440e029903e
diff --git a/apps/builder/app/builder/builder.tsx b/apps/builder/app/builder/builder.tsxindex 39da7db9e7..03220d99e3 100644--- a/apps/builder/app/builder/builder.tsx+++ b/apps/builder/app/builder/builder.tsx@@ -68,6 +68,7 @@ import { DeleteUnusedCssVariablesDialog } from "~/builder/shared/css-variable-utimport { DeleteUnusedAssetsDialog } from "~/builder/shared/asset-manager/delete-unused-assets";import { KeyboardShortcutsDialog } from "./features/keyboard-shortcuts-dialog";import { TokenConflictDialog } from "~/shared/token-conflict-dialog";+import { DesignTokenImportDialog } from "~/shared/design-token-import-dialog";import type { User } from "~/shared/db/user.server";import {@@ -524,6 +525,7 @@ export const Builder = (props: BuilderProps) => {<DeleteUnusedCssVariablesDialog /><DeleteUnusedAssetsDialog /><KeyboardShortcutsDialog />+ <DesignTokenImportDialog /><TokenConflictDialog /><RemoteDialog /><Toaster />diff --git a/apps/builder/app/builder/features/marketplace/templates.tsx b/apps/builder/app/builder/features/marketplace/templates.tsxindex d6a7c2d3f4..26bef19211 100644--- a/apps/builder/app/builder/features/marketplace/templates.tsx+++ b/apps/builder/app/builder/features/marketplace/templates.tsx@@ -1,7 +1,6 @@import { findClosestInsertable } from "~/shared/instance-utils/insert";import { insertWebstudioFragmentAt } from "~/shared/instance-utils/insert";import {- detectFragmentTokenConflicts,detectPageTokenConflicts,extractWebstudioFragment,} from "@webstudio-is/project-build/runtime";@@ -33,11 +32,14 @@ import { mapGroupBy } from "~/shared/shim";import { CollapsibleSection } from "~/builder/shared/collapsible-section";import { builderUrl } from "~/shared/router-utils";import { getWebstudioData } from "~/shared/instance-utils/data";-import { builderApi } from "~/shared/builder-api";import { $project } from "~/shared/sync/data-stores";import { Card } from "./card";import type { MarketplaceOverviewItem } from "~/shared/marketplace/types";import { selectPage } from "~/shared/nano-states";+import {+ resolveFragmentTokenConflicts,+ resolveTokenConflicts,+} from "~/shared/resolve-token-conflicts";const isBody = (instance: Instance) =>instance.component === "Body" ||@@ -71,14 +73,10 @@ const insertSection = async ({if (insertable.position === "end") {insertable.position = "after";}- const conflicts = detectFragmentTokenConflicts({- fragment,- targetData: getWebstudioData(),- });- const conflictResolution =- conflicts.length > 0- ? await builderApi.showTokenConflictDialog(conflicts)- : "theirs";+ const conflictResolution = await resolveFragmentTokenConflicts(fragment);+ if (conflictResolution === "cancel") {+ return;+ }await insertWebstudioFragmentAt(fragment, insertable, conflictResolution);}};@@ -95,10 +93,10 @@ const insertPage = async ({targetData: getWebstudioData(),pageId,});- const conflictResolution =- conflicts.length > 0- ? await builderApi.showTokenConflictDialog(conflicts)- : "theirs";+ const conflictResolution = await resolveTokenConflicts(conflicts);+ if (conflictResolution === "cancel") {+ return;+ }const projectId = $project.get()?.id;if (projectId === undefined) {return;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 4983305201..6ab4cfa799 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@@ -13,7 +13,7 @@ import {$selectedInstanceSelector,selectInstance,} from "~/shared/nano-states";-import { builderApi } from "~/shared/builder-api";+import { resolveTokenConflicts } from "~/shared/resolve-token-conflicts";import {$registeredComponentMetas,$isContentMode,@@ -158,10 +158,10 @@ export const insertTemplateAt = async (targetData: getWebstudioData(),contentMode,});- const conflictResolution =- conflicts.length > 0- ? await builderApi.showTokenConflictDialog(conflicts)- : "theirs";+ const conflictResolution = await resolveTokenConflicts(conflicts);+ if (conflictResolution === "cancel") {+ return;+ }const didInsert = await insertWebstudioFragmentAt(fragment,diff --git a/apps/builder/app/services/api-build.server.test.ts b/apps/builder/app/services/api-build.server.test.tsindex 89a9b53857..16f0ba78af 100644--- a/apps/builder/app/services/api-build.server.test.ts+++ b/apps/builder/app/services/api-build.server.test.ts@@ -15,6 +15,8 @@ import * as projectApi from "@webstudio-is/project/index.server";import * as projectBuild from "@webstudio-is/project-build/server";import type { z } from "zod";import {+ buildPatchInput,+ buildRestorePointInput,commitBuildPatch,commitBuildTransactions,createBuildSnapshot,@@ -23,6 +25,65 @@ import {serializeProjectSummary,} from "./api-build.server";+test("separates validated restore points from raw build patches", () => {+ const input = {+ projectId: "project-1",+ baseVersion: 1,+ transactions: [+ {+ id: "restore-1",+ payload: [+ {+ namespace: "instances" as const,+ patches: [{ op: "replace" as const, path: [], value: [] }],+ },+ ],+ },+ ],+ };++ expect(buildPatchInput.safeParse(input).success).toBe(false);+ expect(buildRestorePointInput.safeParse(input).success).toBe(true);+ expect(+ buildRestorePointInput.safeParse({+ ...input,+ transactions: [...input.transactions, ...input.transactions],+ }).success+ ).toBe(false);+ expect(+ buildRestorePointInput.safeParse({+ ...input,+ transactions: [+ {+ id: "restore-1",+ payload: [+ {+ namespace: "instances",+ patches: [{ op: "add", path: [], value: [] }],+ },+ ],+ },+ ],+ }).success+ ).toBe(false);+ expect(+ buildRestorePointInput.safeParse({+ ...input,+ transactions: [+ {+ id: "restore-assets",+ payload: [+ {+ namespace: "assets",+ patches: [{ op: "replace", path: [], value: [] }],+ },+ ],+ },+ ],+ }).success+ ).toBe(false);+});+const server = createTestServer();type ProjectSummaryInput = Parameters<typeof serializeProjectSummary>[0];diff --git a/apps/builder/app/services/api-build.server.ts b/apps/builder/app/services/api-build.server.tsindex 8db974eda2..7d0ce655be 100644--- a/apps/builder/app/services/api-build.server.ts+++ b/apps/builder/app/services/api-build.server.ts@@ -9,6 +9,7 @@ import {import {buildPatchTransaction,publicBuildIncludes,+ restorePointPatchTransaction,} from "@webstudio-is/protocol/schema";import type { AppContext } from "@webstudio-is/trpc-interface/index.server";import { serializePages } from "@webstudio-is/project-migrations/pages";@@ -58,12 +59,21 @@ export const buildGetInput = z.object({version: z.number().int().optional(),});-export const buildPatchInput = z.object({+const buildPatchInputBase = {projectId: z.string(),baseVersion: z.number().int(),+};++export const buildPatchInput = z.object({+ ...buildPatchInputBase,transactions: z.array(buildPatchTransaction).min(1),});+export const buildRestorePointInput = z.object({+ ...buildPatchInputBase,+ transactions: z.array(restorePointPatchTransaction).length(1),+});+export const createBuildSnapshot = ({build,include,diff --git a/apps/builder/app/services/build-router.server.ts b/apps/builder/app/services/build-router.server.tsindex 77ff3d5302..44947692c4 100644--- a/apps/builder/app/services/build-router.server.ts+++ b/apps/builder/app/services/build-router.server.ts@@ -30,6 +30,7 @@ import {publishedProjectBundle,} from "@webstudio-is/protocol";import { removeAgentInstructionsFromProjectSettings } from "@webstudio-is/project-build";+import { hydrateRestorePointTransaction } from "@webstudio-is/project-build/project-session";import {loadProjectBundleByBuildId,loadPublishedProjectBundleByProjectId,@@ -43,6 +44,11 @@ import {removeStagedUpload,} from "./staged-upload.server";import { throwApiClientUpdateRequired } from "./api-compatibility.server";+import {+ buildRestorePointInput,+ commitBuildTransactions,+} from "./api-build.server";+import { assertApiProjectPermit } from "./api-permits.server";const projectBundleInput = z.object({projectId: z.string(),@@ -290,6 +296,20 @@ export const buildRouter = router({})),+ restorePoint: procedure+ .input(buildRestorePointInput)+ .mutation(async ({ ctx, input }) => {+ await assertApiProjectPermit(ctx, input.projectId, "build");+ const build = await loadDevBuildByProjectId(ctx, input.projectId);+ return await commitBuildTransactions({+ ctx,+ projectId: input.projectId,+ buildId: build.id,+ clientVersion: input.baseVersion,+ transactions: input.transactions.map(hydrateRestorePointTransaction),+ });+ }),+createCollabToken: procedure.input(z.object({diff --git a/apps/builder/app/shared/builder-api.ts b/apps/builder/app/shared/builder-api.tsindex 8317b8af8d..798f5d596f 100644--- a/apps/builder/app/shared/builder-api.ts+++ b/apps/builder/app/shared/builder-api.ts@@ -3,6 +3,7 @@ import invariant from "tiny-invariant";import { toast } from "@webstudio-is/design-system";import { uploadAssets } from "~/builder/shared/assets/upload-assets";import { showTokenConflictDialog } from "./token-conflict-dialog";+import { showDesignTokenImportDialog } from "./design-token-import-dialog";const apiWindowNamespace = "__webstudio__$__builderApi";@@ -32,6 +33,7 @@ const _builderApi = {return new Map([...urlToIds.entries()].map(([url, id]) => [url.href, id]));},+ showDesignTokenImportDialog,showTokenConflictDialog,};diff --git a/apps/builder/app/shared/copy-paste/copy-paste.test.ts b/apps/builder/app/shared/copy-paste/copy-paste.test.tsindex ffd5f6e191..9fe990624a 100644--- a/apps/builder/app/shared/copy-paste/copy-paste.test.ts+++ b/apps/builder/app/shared/copy-paste/copy-paste.test.ts@@ -1,6 +1,7 @@import { afterEach, expect, test, vi } from "vitest";import { enableMapSet } from "immer";import { createDefaultPages } from "@webstudio-is/project-build";+import { createEmptyWebstudioFragment } from "@webstudio-is/project-build/runtime";import { coreMetas, type Instance } from "@webstudio-is/sdk";import * as baseComponentMetas from "@webstudio-is/sdk-components-react/metas";import type { Project } from "@webstudio-is/project";@@ -35,6 +36,7 @@ import {initCopyPaste,initCopyPasteForContentEditMode,} from "./copy-paste";+import { insertFragmentWithBreakpointWarning } from "./fragment-utils";enableMapSet();registerContainers();@@ -84,6 +86,28 @@ const setupPage = () => {);};+const setupRootCssVariable = (property: `--${string}`, value: string) => {+ $styleSources.set(+ new Map([["root-local", { id: "root-local", type: "local" }]])+ );+ $styleSourceSelections.set(+ new Map([["body-id", { instanceId: "body-id", values: ["root-local"] }]])+ );+ $styles.set(+ new Map([+ [+ `root-local:base:${property}:`,+ {+ styleSourceId: "root-local",+ breakpointId: "base",+ property,+ value: { type: "unparsed", value },+ },+ ],+ ])+ );+};+const createClipboardEvent = (type: "copy" | "cut" | "paste") => {const data = new Map<string, string>();const clipboardData = {@@ -138,11 +162,38 @@ const setupToastError = () => {return toastError;};+const setupToastSuccess = () => {+ initBuilderApi();+ const toastSuccess = vi.fn();+ window.__webstudio__$__builderApi.toast.success = toastSuccess;+ return toastSuccess;+};+const waitForClipboardEvent = () =>new Promise((resolve) => setTimeout(resolve, 0));+const pastePlainText = async (+ value: unknown,+ target: "design-token" | "css-variable" | "cancel" = "css-variable"+) => {+ initBuilderApi();+ vi.spyOn(+ window.__webstudio__$__builderApi,+ "showDesignTokenImportDialog"+ ).mockResolvedValue(target);+ const abortController = new AbortController();+ initCopyPaste({ signal: abortController.signal });+ const { clipboardData, event } = createClipboardEvent("paste");+ clipboardData.setData("text/plain", JSON.stringify(value));+ document.dispatchEvent(event);+ await waitForClipboardEvent();+ abortController.abort();+ return event;+};+afterEach(() => {resetStores();+ vi.restoreAllMocks();vi.unstubAllGlobals();});@@ -510,6 +561,383 @@ test("reports malformed Webflow json through generic paste", async () => {abortController.abort();});+test("imports pasted DTCG tokens through the runtime mutation pipeline", async () => {+ resetStores();+ setupPage();+ const toastError = setupToastError();+ const toastSuccess = setupToastSuccess();+ const event = await pastePlainText({+ color: {+ $type: "color",+ primary: { $value: "#123456" },+ action: { $ref: "#/color/primary" },+ },+ });++ expect(toastError).not.toHaveBeenCalled();+ expect(event.defaultPrevented).toBe(true);+ expect(+ Array.from($styles.get().values()).map((style) => [+ style.property,+ style.value,+ ])+ ).toEqual(+ expect.arrayContaining([+ ["--color-primary", { type: "unparsed", value: "#123456" }],+ ["--color-action", { type: "unparsed", value: "#123456" }],+ ])+ );+ expect(toastSuccess).toHaveBeenCalledWith("Imported 2 tokens.");+});++test("imports a pasted DTCG composite as one Webstudio design token", async () => {+ resetStores();+ setupPage();+ const toastError = setupToastError();+ const toastSuccess = setupToastSuccess();+ const event = await pastePlainText(+ {+ typography: {+ $type: "typography",+ body: {+ $value: {+ fontFamily: ["Inter", "sans-serif"],+ fontSize: { value: 16, unit: "px" },+ fontWeight: 400,+ letterSpacing: { value: 0, unit: "px" },+ lineHeight: 1.5,+ },+ },+ },+ },+ "design-token"+ );++ expect(toastError).not.toHaveBeenCalled();+ expect(event.defaultPrevented).toBe(true);+ const token = Array.from($styleSources.get().values()).find(+ (source) => source.type === "token"+ );+ expect(token).toMatchObject({ name: "typography-body" });+ expect(+ Array.from($styles.get().values())+ .filter((style) => style.styleSourceId === token?.id)+ .map((style) => style.property)+ ).toEqual(+ expect.arrayContaining([+ "fontFamily",+ "fontSize",+ "fontWeight",+ "letterSpacing",+ "lineHeight",+ ])+ );+ expect(toastSuccess).toHaveBeenCalledWith("Imported 1 token.");+});++test("keeps ambiguous primitives as CSS variables when importing design tokens", async () => {+ resetStores();+ setupPage();+ setupToastError();+ await pastePlainText(+ {+ color: {+ $type: "color",+ primary: { $value: "#123456" },+ },+ spacing: {+ $type: "dimension",+ small: { $value: { value: 8, unit: "px" } },+ },+ },+ "design-token"+ );++ expect(+ Array.from($styleSources.get().values()).find(+ (source) => source.type === "token"+ )+ ).toMatchObject({ name: "color-primary" });+ expect(+ Array.from($styles.get().values()).find(+ (style) => style.property === "--spacing-small"+ )?.value+ ).toEqual({ type: "unparsed", value: "8px" });+});++test("cancels a pasted token import without changing project styles", async () => {+ resetStores();+ setupPage();+ setupToastError();+ const event = await pastePlainText(+ { color: { $type: "color", $value: "#123456" } },+ "cancel"+ );++ expect(event.defaultPrevented).toBe(true);+ expect($styleSources.get().size).toBe(0);+ expect($styles.get().size).toBe(0);+});++test("resolves token conflicts for fragments through the shared paste helper", async () => {+ resetStores();+ setupPage();+ setupToastError();+ $project.set({ id: "project-id" } as Project);+ $styleSources.set(+ new Map([+ [+ "existing-token",+ { id: "existing-token", type: "token", name: "Primary" },+ ],+ ])+ );+ $styles.set(+ new Map([+ [+ "existing-token:base:color:",+ {+ styleSourceId: "existing-token",+ breakpointId: "base",+ property: "color",+ value: { type: "unparsed", value: "red" },+ },+ ],+ ])+ );+ const fragment = createEmptyWebstudioFragment();+ fragment.styleSources.push({+ id: "incoming-token",+ type: "token",+ name: "Primary",+ });+ fragment.styles.push({+ styleSourceId: "incoming-token",+ breakpointId: "base",+ property: "color",+ value: { type: "unparsed", value: "blue" },+ });+ const conflictDialog = vi+ .spyOn(window.__webstudio__$__builderApi, "showTokenConflictDialog")+ .mockResolvedValue("ours");++ await insertFragmentWithBreakpointWarning(fragment);++ expect(conflictDialog).toHaveBeenCalledWith([+ expect.objectContaining({+ tokenName: "Primary",+ fragmentTokenId: "incoming-token",+ }),+ ]);+ expect(Array.from($styleSources.get().values())).toEqual([+ { id: "existing-token", type: "token", name: "Primary" },+ ]);+ expect($styles.get().get("existing-token:base:color:")?.value).toEqual({+ type: "unparsed",+ value: "red",+ });+});++test("does not insert a fragment when token conflict resolution is cancelled", async () => {+ resetStores();+ setupPage();+ setupToastError();+ $project.set({ id: "project-id" } as Project);+ $styleSources.set(+ new Map([+ [+ "existing-token",+ { id: "existing-token", type: "token", name: "Primary" },+ ],+ ])+ );+ const fragment = createEmptyWebstudioFragment();+ fragment.styleSources.push({+ id: "incoming-token",+ type: "token",+ name: "Primary",+ });+ fragment.styles.push({+ styleSourceId: "incoming-token",+ breakpointId: "base",+ property: "color",+ value: { type: "unparsed", value: "blue" },+ });+ vi.spyOn(+ window.__webstudio__$__builderApi,+ "showTokenConflictDialog"+ ).mockResolvedValue("cancel");++ const inserted = await insertFragmentWithBreakpointWarning(fragment);++ expect(inserted).toBe(false);+ expect(Array.from($styleSources.get().values())).toEqual([+ { id: "existing-token", type: "token", name: "Primary" },+ ]);+});++test.each([+ ["ours", "old", undefined],+ ["theirs", "old", "#123456"],+ ["merge", "#123456", undefined],+] as const)(+ "resolves pasted design token collisions with %s",+ async (resolution, expectedValue, expectedRenamedValue) => {+ resetStores();+ setupPage();+ setupRootCssVariable("--color", "old");+ setupToastError();+ setupToastSuccess();+ const conflictDialog = vi+ .spyOn(window.__webstudio__$__builderApi, "showTokenConflictDialog")+ .mockResolvedValue(resolution);+ await pastePlainText({+ color: { $type: "color", $value: "#123456" },+ });++ expect(conflictDialog).toHaveBeenCalledWith([+ {+ tokenName: "--color",+ },+ ]);+ expect($styles.get().get("root-local:base:--color:")?.value).toEqual({+ type: "unparsed",+ value: expectedValue,+ });+ expect($styles.get().get("root-local:base:--color-1:")?.value).toEqual(+ expectedRenamedValue === undefined+ ? undefined+ : { type: "unparsed", value: expectedRenamedValue }+ );+ }+);++test("silently reuses an identical pasted design value", async () => {+ resetStores();+ setupPage();+ setupRootCssVariable("--color", "#123456");+ setupToastError();+ const toastSuccess = setupToastSuccess();+ const conflictDialog = vi.spyOn(+ window.__webstudio__$__builderApi,+ "showTokenConflictDialog"+ );+ await pastePlainText({+ color: { $type: "color", $value: "#123456" },+ });++ expect(conflictDialog).not.toHaveBeenCalled();+ expect($styles.get().size).toBe(1);+ expect(toastSuccess).toHaveBeenCalledWith(+ "Imported 0 tokens; skipped 1 existing."+ );+});++test("imports the default mode from pasted Figma variables", async () => {+ resetStores();+ setupPage();+ const toastError = setupToastError();+ const toastSuccess = setupToastSuccess();+ await pastePlainText({+ meta: {+ variableCollections: {+ palette: {+ defaultModeId: "dark",+ modes: [+ { modeId: "light", name: "Light" },+ { modeId: "dark", name: "Dark" },+ ],+ },+ },+ variables: {+ primary: {+ name: "Color/Primary",+ resolvedType: "COLOR",+ variableCollectionId: "palette",+ valuesByMode: {+ light: { r: 1, g: 1, b: 1 },+ dark: { r: 0, g: 0, b: 0 },+ },+ },+ },+ },+ });++ expect(toastError).not.toHaveBeenCalled();+ expect(+ Array.from($styles.get().values()).find(+ (style) => style.property === "--color-primary"+ )?.value+ ).toEqual({ type: "unparsed", value: "rgb(0 0 0 / 1)" });+ expect(toastSuccess).toHaveBeenCalledWith("Imported 1 token.");+});++test("imports pasted DTCG resolver documents and composite tokens", async () => {+ resetStores();+ setupPage();+ const toastError = setupToastError();+ const toastSuccess = setupToastSuccess();+ const event = await pastePlainText({+ version: "2025.10",+ resolutionOrder: [+ {+ type: "set",+ name: "Base",+ sources: [+ {+ body: {+ $type: "typography",+ $value: {+ fontFamily: "Inter",+ fontSize: { value: 16, unit: "px" },+ fontWeight: 500,+ letterSpacing: { value: 0, unit: "px" },+ lineHeight: 1.5,+ },+ },+ },+ ],+ },+ ],+ });++ expect(toastError).not.toHaveBeenCalled();+ expect(event.defaultPrevented).toBe(true);+ expect(+ Array.from($styles.get().values()).map((style) => [+ style.property,+ style.value,+ ])+ ).toEqual(+ expect.arrayContaining([+ ["--body-font-family", { type: "unparsed", value: '"Inter"' }],+ ["--body-font-size", { type: "unparsed", value: "16px" }],+ ["--body-font-weight", { type: "unparsed", value: "500" }],+ ["--body-letter-spacing", { type: "unparsed", value: "0px" }],+ ["--body-line-height", { type: "unparsed", value: "1.5" }],+ ])+ );+ expect(toastSuccess).toHaveBeenCalledWith("Imported 5 tokens.");+});++test("reports invalid pasted design token documents", async () => {+ resetStores();+ setupPage();+ const toastError = setupToastError();+ const event = await pastePlainText({+ spacing: {+ $type: "dimension",+ $value: { value: 8, unit: "invalid" },+ },+ });++ expect(event.defaultPrevented).toBe(true);+ expect($styles.get()).toEqual(new Map());+ expect(toastError).toHaveBeenCalledWith(+ expect.stringContaining("invalid dimension unit invalid")+ );+});+test("does not intercept native paste while editing text", async () => {resetStores();const abortController = new AbortController();diff --git a/apps/builder/app/shared/copy-paste/copy-paste.ts b/apps/builder/app/shared/copy-paste/copy-paste.tsindex 31d00cb3d1..ae30783661 100644--- a/apps/builder/app/shared/copy-paste/copy-paste.ts+++ b/apps/builder/app/shared/copy-paste/copy-paste.ts@@ -15,6 +15,7 @@ import { html } from "./plugin-html";import { jsx } from "./plugin-jsx";import { markdown } from "./plugin-markdown";import { webflow } from "./plugin-webflow/plugin-webflow";+import { designTokens } from "./plugin-design-tokens";import { builderApi } from "../builder-api";import { readClipboardText } from "../clipboard";@@ -182,6 +183,7 @@ export const initCopyPaste = ({ signal }: { signal: AbortSignal }) => {pageText,instanceJson,instanceText,+ designTokens,jsx,html,markdown,diff --git a/apps/builder/app/shared/copy-paste/fragment-utils.ts b/apps/builder/app/shared/copy-paste/fragment-utils.tsindex 785114c4e6..152e02045b 100644--- a/apps/builder/app/shared/copy-paste/fragment-utils.ts+++ b/apps/builder/app/shared/copy-paste/fragment-utils.ts@@ -5,16 +5,22 @@ import {type Insertable,} from "../instance-utils/insert";import { builderApi } from "../builder-api";+import { resolveFragmentTokenConflicts } from "../resolve-token-conflicts";export const hasFragmentData = (fragment: WebstudioFragment) =>fragment.children.length > 0 || fragment.styleSources.length > 0;-export const insertFragmentWithBreakpointWarning = (+export const insertFragmentWithBreakpointWarning = async (fragment: WebstudioFragment,insertable?: Insertable-) =>- insertWebstudioFragmentAt(fragment, insertable, undefined, {+) => {+ const conflictResolution = await resolveFragmentTokenConflicts(fragment);+ if (conflictResolution === "cancel") {+ return false;+ }+ return insertWebstudioFragmentAt(fragment, insertable, conflictResolution, {onBreakpointLimitMerge: () => {builderApi.toast.warn(breakpointPasteLimitWarning);},});+};diff --git a/apps/builder/app/shared/copy-paste/plugin-design-tokens.ts b/apps/builder/app/shared/copy-paste/plugin-design-tokens.tsnew file mode 100644index 0000000000..5044a98e30--- /dev/null+++ b/apps/builder/app/shared/copy-paste/plugin-design-tokens.ts@@ -0,0 +1,100 @@+import {+ detectDesignTokenSource,+ planDesignTokenImport,+} from "@webstudio-is/project-build/runtime";+import {+ executeRuntimeMutation,+ getWebstudioData,+} from "../instance-utils/data";+import { builderApi } from "../builder-api";+import { resolveTokenConflicts } from "../resolve-token-conflicts";+import {+ pasteHandled,+ pasteIgnored,+ type PasteResult,+ type Plugin,+} from "./copy-paste";++const parseJson = (value: string) => {+ try {+ return JSON.parse(value) as unknown;+ } catch {+ return;+ }+};++const collisionByResolution = {+ ours: "skip",+ theirs: "rename",+ merge: "overwrite",+} as const;++const designTokenMapping = {+ color: { target: "design-token", property: "color" },+ fontFamily: { target: "design-token", property: "fontFamily" },+ fontWeight: { target: "design-token", property: "fontWeight" },+ strokeStyle: { target: "design-token", property: "borderStyle" },+ border: { target: "design-token", property: "border" },+ transition: { target: "design-token", property: "transition" },+ shadow: { target: "design-token", property: "boxShadow" },+ gradient: { target: "design-token", property: "backgroundImage" },+ typography: { target: "design-token", property: "font" },+} as const;++const handlePasteDesignTokens = async (value: string): Promise<PasteResult> => {+ const source = detectDesignTokenSource(parseJson(value));+ if (source === undefined) {+ return pasteIgnored;+ }+ try {+ const target = await builderApi.showDesignTokenImportDialog();+ if (target === "cancel") {+ return pasteHandled;+ }+ const importInput = {+ source,+ mapping: target === "design-token" ? designTokenMapping : undefined,+ defaultTarget: { target: "css-variable" as const },+ collision: "skip" as const,+ };+ const plan = planDesignTokenImport(getWebstudioData(), importInput);+ const conflicts = plan+ .filter((entry) => entry.conflict)+ .map((entry) => ({ tokenName: entry.outputName }));+ const resolution = await resolveTokenConflicts(conflicts);+ if (resolution === "cancel") {+ return pasteHandled;+ }+ const collision = collisionByResolution[resolution];+ const mutation = executeRuntimeMutation({+ id: "designTokens.import",+ input: { ...importInput, collision },+ });+ if (mutation === undefined) {+ return {+ success: false,+ error: "Design tokens cannot be pasted in the current context.",+ };+ }+ const { create, overwrite, skip } = mutation.result.counts;+ const imported = create + overwrite;+ builderApi.toast.success(+ `Imported ${imported} ${imported === 1 ? "token" : "tokens"}${skip === 0 ? "" : `; skipped ${skip} existing`}.`+ );+ return pasteHandled;+ } catch (error) {+ return {+ success: false,+ error:+ error instanceof Error+ ? error.message+ : "Could not import design tokens.",+ };+ }+};++export const designTokens: Plugin = {+ name: "design-tokens",+ mimeType: "text/plain",+ onPaste: handlePasteDesignTokens,+};diff --git a/apps/builder/app/shared/copy-paste/plugin-html.ts b/apps/builder/app/shared/copy-paste/plugin-html.tsindex 31c933b126..80eb896749 100644--- a/apps/builder/app/shared/copy-paste/plugin-html.ts+++ b/apps/builder/app/shared/copy-paste/plugin-html.ts@@ -22,7 +22,9 @@ const handlePasteHtml = async (html: string) => {if (html.includes(inceptionMark)) {fragment = await generateFragmentFromTailwind(fragment);}- insertFragmentWithBreakpointWarning(fragment);+ if ((await insertFragmentWithBreakpointWarning(fragment)) === false) {+ return pasteHandled;+ }if (skippedSelectors.length > 0) {builderApi.toast.info(`Skipped nested selectors (no matching elements): ${skippedSelectors.join(", ")}`diff --git a/apps/builder/app/shared/copy-paste/plugin-instance.ts b/apps/builder/app/shared/copy-paste/plugin-instance.tsindex 8851ba9c19..5a1bc76975 100644--- a/apps/builder/app/shared/copy-paste/plugin-instance.ts+++ b/apps/builder/app/shared/copy-paste/plugin-instance.ts@@ -1,5 +1,4 @@import {- detectFragmentTokenConflicts,extractWebstudioFragment,findSafeFragmentPasteTarget,getCommonAncestorSelector,@@ -44,6 +43,7 @@ import { getInstancePath } from "@webstudio-is/project-build/runtime";import { builderApi } from "../builder-api";import { pasteHandled, pasteIgnored, type Plugin } from "./copy-paste";import { breakpointPasteLimitWarning } from "@webstudio-is/project-build/runtime";+import { resolveFragmentTokenConflicts } from "../resolve-token-conflicts";const invalidPasteDataMessage ="Could not paste Webstudio instance data. The clipboard data appears to be incomplete or invalid.";@@ -198,16 +198,6 @@ const findPasteTarget = (return findSelectionPasteTarget(data);};-const resolveFragmentTokenConflicts = async (fragment: WebstudioFragment) => {- const conflicts = detectFragmentTokenConflicts({- fragment,- targetData: getWebstudioData(),- });- return conflicts.length > 0- ? await builderApi.showTokenConflictDialog(conflicts)- : "theirs";-};-const insertPastedFragment = async ({fragment,pasteTarget,@@ -219,6 +209,9 @@ const insertPastedFragment = async ({}) => {try {const conflictResolution = await resolveFragmentTokenConflicts(fragment);+ if (conflictResolution === "cancel") {+ return;+ }const result = await executeRuntimeMutationAsync({id: "instances.insertFragment",input: {diff --git a/apps/builder/app/shared/copy-paste/plugin-jsx.test.ts b/apps/builder/app/shared/copy-paste/plugin-jsx.test.tsindex c68961382d..70efa77c01 100644--- a/apps/builder/app/shared/copy-paste/plugin-jsx.test.ts+++ b/apps/builder/app/shared/copy-paste/plugin-jsx.test.ts@@ -75,7 +75,7 @@ describe("jsx paste plugin", () => {expect(mocks.insertWebstudioFragmentAt).toHaveBeenCalledWith(fragment,undefined,- undefined,+ "theirs",expect.objectContaining({onBreakpointLimitMerge: expect.any(Function),})diff --git a/apps/builder/app/shared/copy-paste/plugin-jsx.ts b/apps/builder/app/shared/copy-paste/plugin-jsx.tsindex 674e83fcc7..ea29f0988e 100644--- a/apps/builder/app/shared/copy-paste/plugin-jsx.ts+++ b/apps/builder/app/shared/copy-paste/plugin-jsx.ts@@ -19,7 +19,7 @@ const handlePasteJsx = async (source: string) => {projectId: project.id,source,});- insertFragmentWithBreakpointWarning(fragment);+ await insertFragmentWithBreakpointWarning(fragment);return pasteHandled;} catch (error) {return {diff --git a/apps/builder/app/shared/copy-paste/plugin-markdown.ts b/apps/builder/app/shared/copy-paste/plugin-markdown.tsindex c659990ccb..5bc1a73ee0 100644--- a/apps/builder/app/shared/copy-paste/plugin-markdown.ts+++ b/apps/builder/app/shared/copy-paste/plugin-markdown.ts@@ -32,7 +32,7 @@ const handlePasteMarkdown = async (clipboardData: string) => {return pasteIgnored;}fragment = await denormalizeSrcProps(fragment);- insertFragmentWithBreakpointWarning(fragment);+ await insertFragmentWithBreakpointWarning(fragment);return pasteHandled;};diff --git a/apps/builder/app/shared/copy-paste/plugin-page.ts b/apps/builder/app/shared/copy-paste/plugin-page.tsindex db5cc4bdba..3d7c648d06 100644--- a/apps/builder/app/shared/copy-paste/plugin-page.ts+++ b/apps/builder/app/shared/copy-paste/plugin-page.ts@@ -13,7 +13,7 @@ import {} from "@webstudio-is/sdk";import { $pages, $project } from "~/shared/sync/data-stores";import { detectFragmentTokenConflicts } from "@webstudio-is/project-build/runtime";-import { builderApi } from "../builder-api";+import { resolveTokenConflicts } from "../resolve-token-conflicts";import {createFolderCopyData,createPageCopyData,@@ -192,10 +192,10 @@ export const handlePastePage = async (targetData,}));- const conflictResolution =- conflicts.length > 0- ? await builderApi.showTokenConflictDialog(conflicts)- : "theirs";+ const conflictResolution = await resolveTokenConflicts(conflicts);+ if (conflictResolution === "cancel") {+ return pasteHandled;+ }const result = executeRuntimeMutation({id: "pageTransfer.insert",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 e786a5008c..8e176c8062 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@@ -203,7 +203,7 @@ const handlePasteWebflow = async (clipboardData: string) => {return pasteHandled;}- insertFragmentWithBreakpointWarning(fragment, insertable);+ await insertFragmentWithBreakpointWarning(fragment, insertable);return pasteHandled;};diff --git a/apps/builder/app/shared/design-token-import-dialog.test.tsx b/apps/builder/app/shared/design-token-import-dialog.test.tsxnew file mode 100644index 0000000000..1f854d256d--- /dev/null+++ b/apps/builder/app/shared/design-token-import-dialog.test.tsx@@ -0,0 +1,96 @@+import { createElement } from "react";+import { createRoot, type Root } from "react-dom/client";+import { act } from "react-dom/test-utils";+import { afterEach, beforeEach, expect, test, vi } from "vitest";+import {+ DesignTokenImportDialog,+ showDesignTokenImportDialog,+} from "./design-token-import-dialog";++(+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }+).IS_REACT_ACT_ENVIRONMENT = true;++let root: Root | undefined;++beforeEach(() => {+ vi.stubGlobal(+ "ResizeObserver",+ class {+ observe() {}+ disconnect() {}+ }+ );+});++afterEach(() => {+ act(() => root?.unmount());+ root = undefined;+ document.body.innerHTML = "";+ vi.unstubAllGlobals();+});++const renderDialog = () => {+ const container = document.createElement("div");+ document.body.appendChild(container);+ root = createRoot(container);+ act(() => root?.render(createElement(DesignTokenImportDialog)));+};++const click = (element: Element | undefined) => {+ if (element === undefined) {+ throw new Error("Expected dialog control");+ }+ act(() => element.dispatchEvent(new MouseEvent("click", { bubbles: true })));+};++const findButton = (label: string) =>+ Array.from(document.querySelectorAll("button")).find(+ (button) => button.textContent === label+ );++const findRadio = (value: string) =>+ Array.from(document.querySelectorAll('[role="radio"]')).find(+ (radio) => radio.getAttribute("value") === value+ );++test("imports as design tokens by default", async () => {+ const result = showDesignTokenImportDialog();+ renderDialog();+ click(findButton("Import"));++ await expect(result).resolves.toBe("design-token");+});++test("returns the selected CSS variable target", async () => {+ const result = showDesignTokenImportDialog();+ renderDialog();+ click(findRadio("css-variable"));+ click(findButton("Import"));++ await expect(result).resolves.toBe("css-variable");+});++test("cancels without selecting an import target", async () => {+ const result = showDesignTokenImportDialog();+ renderDialog();+ click(findButton("Cancel"));++ await expect(result).resolves.toBe("cancel");+});++test("resets the target when a newer request replaces the open dialog", async () => {+ const first = showDesignTokenImportDialog();+ renderDialog();+ click(findRadio("css-variable"));++ let second!: ReturnType<typeof showDesignTokenImportDialog>;+ act(() => {+ second = showDesignTokenImportDialog();+ });++ await expect(first).resolves.toBe("cancel");+ expect(findRadio("design-token")?.getAttribute("aria-checked")).toBe("true");+ click(findButton("Cancel"));+ await expect(second).resolves.toBe("cancel");+});diff --git a/apps/builder/app/shared/design-token-import-dialog.tsx b/apps/builder/app/shared/design-token-import-dialog.tsxnew file mode 100644index 0000000000..b4e7ee15e5--- /dev/null+++ b/apps/builder/app/shared/design-token-import-dialog.tsx@@ -0,0 +1,106 @@+import { atom } from "nanostores";+import { useStore } from "@nanostores/react";+import {+ Button,+ Dialog,+ DialogActions,+ DialogContent,+ DialogDescription,+ DialogTitle,+ Flex,+ theme,+} from "@webstudio-is/design-system";+import { DialogRadioOptions } from "./dialog-radio-options";++export type DesignTokenImportTarget = "design-token" | "css-variable";+export type DesignTokenImportDialogResult = DesignTokenImportTarget | "cancel";++const importTargetOptions = [+ {+ value: "design-token",+ label: "Design tokens",+ description:+ "Create reusable style tokens for composite and unambiguous values. Keep other primitive values as CSS variables.",+ },+ {+ value: "css-variable",+ label: "CSS variables",+ description:+ "Create custom properties that can be used in individual styles.",+ },+] as const satisfies ReadonlyArray<{+ value: DesignTokenImportTarget;+ label: string;+ description: string;+}>;++type DialogState =+ | {+ target: DesignTokenImportTarget;+ resolve: (result: DesignTokenImportDialogResult) => void;+ }+ | undefined;++const $dialogState = atom<DialogState>(undefined);++export const showDesignTokenImportDialog = () =>+ new Promise<DesignTokenImportDialogResult>((resolve) => {+ $dialogState.get()?.resolve("cancel");+ $dialogState.set({ target: "design-token", resolve });+ });++export const DesignTokenImportDialog = () => {+ const dialogState = useStore($dialogState);++ if (dialogState === undefined) {+ return;+ }++ const { resolve, target } = dialogState;+ const close = () => {+ if ($dialogState.get()?.resolve === resolve) {+ $dialogState.set(undefined);+ }+ };+ const finish = (result: DesignTokenImportDialogResult) => {+ resolve(result);+ close();+ };++ return (+ <Dialog+ open={true}+ onOpenChange={(open) => {+ if (open === false) {+ finish("cancel");+ }+ }}+ >+ <DialogContent css={{ minWidth: "40ch" }}>+ <DialogTitle>Import tokens</DialogTitle>+ <Flex direction="column" gap="2" css={{ padding: theme.panel.padding }}>+ <DialogDescription>+ Choose how these tokens should be represented in Webstudio.+ </DialogDescription>+ <DialogRadioOptions+ value={target}+ options={importTargetOptions}+ onValueChange={(target) => {+ if ($dialogState.get()?.resolve === resolve) {+ $dialogState.set({ target, resolve });+ }+ }}+ />+ </Flex>+ <DialogActions>+ <Button autoFocus color="positive" onClick={() => finish(target)}>+ Import+ </Button>+ <Button color="ghost" onClick={() => finish("cancel")}>+ Cancel+ </Button>+ </DialogActions>+ </DialogContent>+ </Dialog>+ );+};diff --git a/apps/builder/app/shared/dialog-radio-options.tsx b/apps/builder/app/shared/dialog-radio-options.tsxnew file mode 100644index 0000000000..acab61e702--- /dev/null+++ b/apps/builder/app/shared/dialog-radio-options.tsx@@ -0,0 +1,53 @@+import {+ Flex,+ Label,+ Radio,+ RadioGroup,+ Text,+ theme,+} from "@webstudio-is/design-system";++type DialogRadioOption<Value extends string> = {+ value: Value;+ label: string;+ description: string;+};++export const DialogRadioOptions = <Value extends string>({+ value,+ options,+ onValueChange,+}: {+ value: Value;+ options: ReadonlyArray<DialogRadioOption<Value>>;+ onValueChange: (value: Value) => void;+}) => (+ <RadioGroup+ value={value}+ onValueChange={(nextValue) => onValueChange(nextValue as Value)}+ >+ <Flex direction="column" gap="1">+ {options.map((option) => (+ <Label key={option.value}>+ <Flex+ gap="2"+ css={{+ padding: theme.spacing[3],+ cursor: "pointer",+ borderRadius: theme.borderRadius[4],+ "&:hover": {+ backgroundColor: theme.colors.backgroundHover,+ },+ }}+ >+ <Radio value={option.value} />+ <Flex direction="column" gap="1">+ <Text variant="labels">{option.label}</Text>+ <Text color="subtle">{option.description}</Text>+ </Flex>+ </Flex>+ </Label>+ ))}+ </Flex>+ </RadioGroup>+);diff --git a/apps/builder/app/shared/instance-utils/insert.ts b/apps/builder/app/shared/instance-utils/insert.tsindex e3b3bb4dba..1deaebf8ed 100644--- a/apps/builder/app/shared/instance-utils/insert.ts+++ b/apps/builder/app/shared/instance-utils/insert.ts@@ -4,7 +4,7 @@// in mutation.ts.import { toast } from "@webstudio-is/design-system";import { type WebstudioFragment, elementComponent } from "@webstudio-is/sdk";-import type { ConflictResolution } from "../token-conflict-dialog";+import type { ConflictResolution } from "@webstudio-is/project-build/runtime";import {$registeredComponentMetas,$registeredTemplates,diff --git a/apps/builder/app/shared/resolve-token-conflicts.ts b/apps/builder/app/shared/resolve-token-conflicts.tsnew file mode 100644index 0000000000..2f694b252f--- /dev/null+++ b/apps/builder/app/shared/resolve-token-conflicts.ts@@ -0,0 +1,31 @@+import type { WebstudioFragment } from "@webstudio-is/sdk";+import { detectFragmentTokenConflicts } from "@webstudio-is/project-build/runtime";+import { builderApi } from "./builder-api";+import { getWebstudioData } from "./instance-utils/data";+import type {+ TokenConflictDialogConflict,+ TokenConflictDialogResult,+} from "./token-conflict-dialog";++export const resolveTokenConflicts = async (+ conflicts: TokenConflictDialogConflict[]+): Promise<TokenConflictDialogResult> =>+ conflicts.length === 0+ ? "theirs"+ : builderApi.showTokenConflictDialog(conflicts);++export const resolveFragmentTokenConflicts = (+ fragment: WebstudioFragment+): Promise<TokenConflictDialogResult> => {+ if (+ fragment.styleSources.some((source) => source.type === "token") === false+ ) {+ return Promise.resolve("theirs");+ }+ return resolveTokenConflicts(+ detectFragmentTokenConflicts({+ fragment,+ targetData: getWebstudioData(),+ })+ );+};diff --git a/apps/builder/app/shared/token-conflict-dialog.test.tsx b/apps/builder/app/shared/token-conflict-dialog.test.tsxnew file mode 100644index 0000000000..8df7ce52b0--- /dev/null+++ b/apps/builder/app/shared/token-conflict-dialog.test.tsx@@ -0,0 +1,88 @@+import { createElement } from "react";+import { createRoot, type Root } from "react-dom/client";+import { act } from "react-dom/test-utils";+import { afterEach, beforeEach, expect, test, vi } from "vitest";+import {+ showTokenConflictDialog,+ TokenConflictDialog,+} from "./token-conflict-dialog";++(+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }+).IS_REACT_ACT_ENVIRONMENT = true;++let root: Root | undefined;++beforeEach(() => {+ vi.stubGlobal(+ "ResizeObserver",+ class {+ observe() {}+ disconnect() {}+ }+ );+});++afterEach(() => {+ act(() => root?.unmount());+ root = undefined;+ document.body.innerHTML = "";+ vi.unstubAllGlobals();+});++const renderAndCancelDialog = () => {+ const container = document.createElement("div");+ document.body.appendChild(container);+ root = createRoot(container);+ act(() => root?.render(createElement(TokenConflictDialog)));+ const cancel = Array.from(document.querySelectorAll("button")).find(+ (button) => button.textContent === "Cancel"+ );+ if (cancel === undefined) {+ throw new Error("Expected token conflict cancel button");+ }+ act(() => {+ cancel.dispatchEvent(new MouseEvent("click", { bubbles: true }));+ });+};++test("settles the pending request when the dialog is cancelled", async () => {+ const result = showTokenConflictDialog([{ tokenName: "Primary" }]);+ renderAndCancelDialog();++ await expect(result).resolves.toBe("cancel");+});++test("cancels a pending request when a newer conflict dialog replaces it", async () => {+ const first = showTokenConflictDialog([{ tokenName: "Primary" }]);+ const container = document.createElement("div");+ document.body.appendChild(container);+ root = createRoot(container);+ act(() => root?.render(createElement(TokenConflictDialog)));+ const staleCancel = Array.from(document.querySelectorAll("button")).find(+ (button) => button.textContent === "Cancel"+ );+ if (staleCancel === undefined) {+ throw new Error("Expected token conflict cancel button");+ }++ let second!: ReturnType<typeof showTokenConflictDialog>;+ act(() => {+ second = showTokenConflictDialog([{ tokenName: "Secondary" }]);+ staleCancel.dispatchEvent(new MouseEvent("click", { bubbles: true }));+ });++ await expect(first).resolves.toBe("cancel");+ expect(document.body.textContent).toContain("Secondary");+ const currentCancel = Array.from(document.querySelectorAll("button")).find(+ (button) => button.textContent === "Cancel"+ );+ if (currentCancel === undefined) {+ throw new Error("Expected replacement token conflict cancel button");+ }+ act(() => {+ currentCancel.dispatchEvent(new MouseEvent("click", { bubbles: true }));+ });++ await expect(second).resolves.toBe("cancel");+});diff --git a/apps/builder/app/shared/token-conflict-dialog.tsx b/apps/builder/app/shared/token-conflict-dialog.tsxindex bb42c0609c..5a84b12346 100644--- a/apps/builder/app/shared/token-conflict-dialog.tsx+++ b/apps/builder/app/shared/token-conflict-dialog.tsx@@ -1,4 +1,3 @@-import { useState } from "react";import { atom } from "nanostores";import { useStore } from "@nanostores/react";import {@@ -11,77 +10,81 @@ import {Flex,Text,theme,- RadioGroup,- Radio,- Label,} from "@webstudio-is/design-system";-import type { TokenConflict } from "@webstudio-is/project-build/runtime";--export type ConflictResolution = "ours" | "theirs" | "merge";+import type {+ ConflictResolution,+ TokenConflict,+} from "@webstudio-is/project-build/runtime";+import { DialogRadioOptions } from "./dialog-radio-options";++export type TokenConflictDialogResult = ConflictResolution | "cancel";+export type TokenConflictDialogConflict = Pick<TokenConflict, "tokenName">;++const conflictResolutionOptions = [+ {+ value: "theirs",+ label: "Theirs",+ description:+ 'Keep incoming tokens with a suffix added to their names (e.g., "primary-color-1")',+ },+ {+ value: "ours",+ label: "Ours",+ description:+ "Discard incoming tokens and use your existing project tokens instead",+ },+ {+ value: "merge",+ label: "Merge",+ description:+ "Combine both into your existing token (incoming styles override existing ones)",+ },+] as const satisfies ReadonlyArray<{+ value: ConflictResolution;+ label: string;+ description: string;+}>;type DialogState =| {- conflicts: TokenConflict[];- resolve: (resolution: ConflictResolution) => void;+ conflicts: TokenConflictDialogConflict[];+ resolution: ConflictResolution;+ resolve: (result: TokenConflictDialogResult) => void;}| undefined;-const $tokenConflictDialogState = atom<DialogState>(undefined);+const $dialogState = atom<DialogState>(undefined);export const showTokenConflictDialog = (- conflicts: Array<{- tokenName: string;- fragmentTokenId: string;- }>-): Promise<ConflictResolution> => {- return new Promise((resolve) => {- const fullConflicts: TokenConflict[] = conflicts.map((c) => ({- tokenName: c.tokenName,- fragmentTokenId: c.fragmentTokenId,- fragmentToken: {- type: "token" as const,- id: c.fragmentTokenId,- name: c.tokenName,- },- existingToken: {- type: "token" as const,- id: "existing",- name: c.tokenName,- },- }));-- $tokenConflictDialogState.set({- conflicts: fullConflicts,- resolve,- });+ conflicts: TokenConflictDialogConflict[]+): Promise<TokenConflictDialogResult> =>+ new Promise((resolve) => {+ $dialogState.get()?.resolve("cancel");+ $dialogState.set({ conflicts, resolution: "theirs", resolve });});-};export const TokenConflictDialog = () => {- const dialogState = useStore($tokenConflictDialogState);- const [resolution, setResolution] = useState<ConflictResolution | undefined>(- "theirs"- );+ const dialogState = useStore($dialogState);if (!dialogState) {return;}- const { conflicts, resolve } = dialogState;+ const { conflicts, resolution, resolve } = dialogState;const handleClose = () => {- $tokenConflictDialogState.set(undefined);- setResolution("theirs");+ if ($dialogState.get()?.resolve === resolve) {+ $dialogState.set(undefined);+ }};const handleResolve = () => {- if (resolution) {- resolve(resolution);- handleClose();- }+ resolve(resolution);+ handleClose();};const handleCancel = () => {+ resolve("cancel");handleClose();};@@ -118,83 +121,15 @@ export const TokenConflictDialog = () => {</Text></DialogDescription>- <RadioGroup+ <DialogRadioOptionsvalue={resolution}- onValueChange={(value) =>- setResolution(value as ConflictResolution)- }- >- <Flex direction="column" gap="1">- <Label>- <Flex- gap="2"- css={{- padding: theme.spacing[3],- cursor: "pointer",- borderRadius: theme.borderRadius[4],- "&:hover": {- backgroundColor: theme.colors.backgroundHover,- },- }}- >- <Radio value="theirs" />- <Flex direction="column" gap="1">- <Text variant="labels">Theirs</Text>- <Text color="subtle">- Keep incoming tokens with a suffix added to their names- (e.g., "primary-color-1")- </Text>- </Flex>- </Flex>- </Label>-- <Label>- <Flex- gap="2"- css={{- padding: theme.spacing[3],- cursor: "pointer",- borderRadius: theme.borderRadius[4],- "&:hover": {- backgroundColor: theme.colors.backgroundHover,- },- }}- >- <Radio value="ours" />- <Flex direction="column" gap="1">- <Text variant="labels">Ours</Text>- <Text color="subtle">- Discard incoming tokens and use your existing project- tokens instead- </Text>- </Flex>- </Flex>- </Label>-- <Label>- <Flex- gap="2"- css={{- padding: theme.spacing[3],- cursor: "pointer",- borderRadius: theme.borderRadius[4],- "&:hover": {- backgroundColor: theme.colors.backgroundHover,- },- }}- >- <Radio value="merge" />- <Flex direction="column" gap="1">- <Text variant="labels">Merge</Text>- <Text color="subtle">- Combine both into your existing token (incoming styles- override existing ones)- </Text>- </Flex>- </Flex>- </Label>- </Flex>- </RadioGroup>+ options={conflictResolutionOptions}+ onValueChange={(resolution) => {+ if ($dialogState.get()?.resolve === resolve) {+ $dialogState.set({ conflicts, resolution, resolve });+ }+ }}+ /><Flex as="details" direction="column" gap="1"><Text as="summary">Show conflicting tokens</Text>diff --git a/packages/cli/evaluations/high-impact/fixture-api.test.ts b/packages/cli/evaluations/high-impact/fixture-api.test.tsindex 1e68ef2ca9..abedf98fa0 100644--- a/packages/cli/evaluations/high-impact/fixture-api.test.ts+++ b/packages/cli/evaluations/high-impact/fixture-api.test.ts@@ -50,5 +50,5 @@ describe("high-impact fixture API", () => {await fixtureApi.close();await rm(directory, { recursive: true, force: true });}- }, 15_000);+ }, 30_000);});diff --git a/packages/cli/evaluations/high-impact/fixture-api.ts b/packages/cli/evaluations/high-impact/fixture-api.tsindex 0297a4f1a4..0dc3efdd40 100644--- a/packages/cli/evaluations/high-impact/fixture-api.ts+++ b/packages/cli/evaluations/high-impact/fixture-api.ts@@ -79,15 +79,18 @@ export const startHighImpactFixtureApi = async (fixture: HighImpactFixture): Promise<HighImpactFixtureApi> => {Object.assign(globalThis, { React });- const [stateAdapters, runtime, projectSession] = await Promise.all([- import("@webstudio-is/project-build/state"),- import("@webstudio-is/project-build/runtime"),- import("../../src/project-session"),- ]);+ const [stateAdapters, runtime, projectSession, restorePoints] =+ await Promise.all([+ import("@webstudio-is/project-build/state"),+ import("@webstudio-is/project-build/runtime"),+ import("../../src/project-session"),+ import("@webstudio-is/project-build/project-session"),+ ]);const { createBuilderStateFromBuildData, applyBuilderPatchTransactions } =stateAdapters;const { executeBuilderRuntimeOperation } = runtime;const { createLocalProjectBundleFromSessionSnapshot } = projectSession;+ const { hydrateRestorePointTransaction } = restorePoints;const persistedPages = createPersistedPages(fixture.project);const build = {id: buildId,@@ -146,13 +149,19 @@ export const startHighImpactFixtureApi = async (homePageId: "home",features: {},};- } else if (operationPath === "build.patch") {+ } else if (+ operationPath === "build.patch" ||+ operationPath === "build.restorePoint"+ ) {const input = (await readInput()) as {transactions?: BuilderPatchTransaction[];};+ const transactions = input.transactions ?? [];state = applyBuilderPatchTransactions(state,- input.transactions ?? []+ operationPath === "build.restorePoint"+ ? transactions.map(hydrateRestorePointTransaction)+ : transactions).state;version += 1;data = { version };diff --git a/packages/cli/src/commands/api-command-metadata.ts b/packages/cli/src/commands/api-command-metadata.tsindex 70932ea63b..e2015023f6 100644--- a/packages/cli/src/commands/api-command-metadata.ts+++ b/packages/cli/src/commands/api-command-metadata.ts@@ -183,6 +183,7 @@ const apiCommandOptionsByCommand: Partial<"replace-styles": apiCommand.replaceStylesCommandOptions,"list-design-tokens": apiCommand.designTokensCommandOptions,"create-design-token": apiCommand.createDesignTokenCommandOptions,+ "import-design-tokens": apiCommand.importDesignTokensCommandOptions,"update-design-token-styles":apiCommand.updateDesignTokenStylesCommandOptions,"delete-design-token-styles":diff --git a/packages/cli/src/commands/api-command.test.ts b/packages/cli/src/commands/api-command.test.tsindex eb5f1485b7..ab6ac13dd0 100644--- a/packages/cli/src/commands/api-command.test.ts+++ b/packages/cli/src/commands/api-command.test.ts@@ -2005,6 +2005,28 @@ test("creates design tokens from input file", async () => {});});+test("imports design tokens from input file", async () => {+ const inputJson = {+ source: {+ format: "dtcg",+ document: {+ color: {+ brand: { $type: "color", $value: "#0066ff" },+ },+ },+ },+ mapping: {+ color: { target: "design-token", property: "color" },+ },+ };+ await expectCommandCall({+ options: { command: "import-design-tokens", input: "tokens.json" },+ call: apiCalls.importDesignTokens,+ inputJson,+ connection: inputJson,+ });+});+test("updates design token styles from input file", async () => {const updates = [{ property: "color", value: { type: "keyword", value: "blue" } },diff --git a/packages/cli/src/commands/api-command.ts b/packages/cli/src/commands/api-command.tsindex 5553bef622..fec2be4cec 100644--- a/packages/cli/src/commands/api-command.ts+++ b/packages/cli/src/commands/api-command.ts@@ -823,6 +823,12 @@ export const createDesignTokenCommandOptions = (yargs: CommonYargsArgv) =>"Required JSON file containing an array of design tokens with name, styles object, or declarations array");+export const importDesignTokensCommandOptions = (yargs: CommonYargsArgv) =>+ requiredInputOption(+ apiCommandOptions(yargs),+ "Required JSON file containing DTCG tokens, Figma variables, and import mapping options"+ );+export const updateDesignTokenStylesCommandOptions = (yargs: CommonYargsArgv) =>requiredInputOption(apiCommandOptions(yargs).option("design-token", {@@ -1430,6 +1436,10 @@ type StyleReplaceInput = Omit<type CreateDesignTokensInput = Parameters<typeof httpClient.createDesignTokens>[0]["tokens"];+type ImportDesignTokensInput = Omit<+ Parameters<typeof httpClient.importDesignTokens>[0],+ "authToken" | "headers" | "origin" | "projectId"+>;type UpdateDesignTokenStylesInput = Parameters<typeof httpClient.updateDesignTokenStyles>[0]["updates"];@@ -2632,6 +2642,18 @@ const apiCommandHandlers: Partial<Record<ApiCommandName, ApiCommandHandler>> = {dependencies);},+ "import-design-tokens": async (options, connection, dependencies) => {+ const input = await readInputObject<ImportDesignTokensInput>(+ dependencies,+ options+ );+ return runProjectSessionCommand(+ "import-design-tokens",+ input,+ connection,+ dependencies+ );+ },"update-design-token-styles": async (options, connection, dependencies) => {const input = {designTokenId: requireOption(options.designToken, "--design-token"),diff --git a/packages/cli/src/commands/link.ts b/packages/cli/src/commands/link.tsindex cffb3525ac..6cabdc0326 100644--- a/packages/cli/src/commands/link.ts+++ b/packages/cli/src/commands/link.ts@@ -1,6 +1,6 @@import { cwd, exit } from "node:process";import { dirname, join } from "node:path";-import { mkdir, readFile, rm, writeFile } from "node:fs/promises";+import { mkdir, readFile, writeFile } from "node:fs/promises";import { cancel, isCancel, log, text } from "@clack/prompts";import { parseBuilderUrl } from "@webstudio-is/protocol";import {@@ -10,42 +10,12 @@ import {jsonToGlobalConfig,type LocalConfig,} from "../config";-import { writeFileAtomic } from "../fs-utils";+import { withFileLock, writeFileAtomic } from "../fs-utils";import type {CommonYargsArgv,StrictYargsOptionsToInterface,} from "./yargs-types";-const wait = (duration: number) =>- new Promise((resolve) => setTimeout(resolve, duration));--const withConfigLock = async <Result>(callback: () => Promise<Result>) => {- const lockPath = `${GLOBAL_CONFIG_FILE}.lock`;- const start = Date.now();-- while (true) {- try {- await mkdir(lockPath);- break;- } catch (error) {- const code = (error as NodeJS.ErrnoException).code;- if (code !== "EEXIST") {- throw error;- }- if (Date.now() - start > 10_000) {- throw new Error(`Timed out waiting for config lock ${lockPath}`);- }- await wait(50);- }- }-- try {- return await callback();- } finally {- await rm(lockPath, { recursive: true, force: true });- }-};-const writeConfigFile = async (content: string) => {await writeFileAtomic(GLOBAL_CONFIG_FILE, content);};@@ -106,7 +76,7 @@ export const linkOptions = (yargs: CommonYargsArgv) =>export const saveShareLink = async (shareLink: string) => {const { origin, projectId, token } = parseShareLink(shareLink);- await withConfigLock(async () => {+ await withFileLock(GLOBAL_CONFIG_FILE, async () => {const currentConfig = await readFile(GLOBAL_CONFIG_FILE, "utf-8");const currentConfigJson = jsonToGlobalConfig(JSON.parse(currentConfig));diff --git a/packages/cli/src/commands/mcp-preview.ts b/packages/cli/src/commands/mcp-preview.tsindex 738481686e..f416583856 100644--- a/packages/cli/src/commands/mcp-preview.ts+++ b/packages/cli/src/commands/mcp-preview.ts@@ -68,6 +68,7 @@ const prepareDefaultPreviewProject = (source,syncIfMissing: true,silent: true,+ includeDraftPages: true,prepareSessionDataFile,});diff --git a/packages/cli/src/commands/mcp.ts b/packages/cli/src/commands/mcp.tsindex 2070fc50ec..a15de09ee6 100644--- a/packages/cli/src/commands/mcp.ts+++ b/packages/cli/src/commands/mcp.ts@@ -31,7 +31,9 @@ import { HandledCliError, isHandledCliError } from "../errors";import { loadJSONFile } from "../fs-utils";import {assertCliServerOperationSupported,+ createCliProjectRestorePointStorage,createCliProjectSession,+ getCliProjectRestorePointsFile,getCliServerApiContract,getSupportedPublicApiOperations,type CliServerApiContract,@@ -829,6 +831,9 @@ const createCliMcpHost = async ({projectRoot,sessionProjectId: projectId,});+ const restorePointStorage = createCliProjectRestorePointStorage(+ getCliProjectRestorePointsFile(projectRoot, projectId)+ );await prepareMcpProjectSession(session);const preview = createPreviewController({ host: "127.0.0.1", port: 5173 });let isPreviewStale = true;@@ -880,6 +885,29 @@ const createCliMcpHost = async ({}return result;},+ restorePoints: {+ async create({ name }) {+ return await restorePointStorage.create(+ name,+ await session.captureRestorePointSnapshot()+ );+ },+ async list() {+ return { points: await restorePointStorage.list() };+ },+ async delete({ id }) {+ return { deleted: await restorePointStorage.delete(id) };+ },+ async revert({ id }, { dryRun }) {+ const restorePoint = await restorePointStorage.get(id);+ if (restorePoint === undefined) {+ throw Object.assign(new Error("Restore point not found"), {+ code: "NOT_FOUND",+ });+ }+ return await session.restoreSnapshot(restorePoint, { dryRun });+ },+ },async importProject(input) {importErrorMessage = "Project import failed.";try {diff --git a/packages/cli/src/commands/preview.test.ts b/packages/cli/src/commands/preview.test.tsindex e464e2b05b..1dffb05ea0 100644--- a/packages/cli/src/commands/preview.test.ts+++ b/packages/cli/src/commands/preview.test.ts@@ -96,6 +96,13 @@ test("keys packaged preview builds to project inputs and asset metadata", asynctemplate: [],cliVersion: "1.2.3",});+ const withDraftPages = await getPreviewBuildCacheKey({+ projectDir,+ assets: true,+ template: [],+ includeDraftPages: true,+ cliVersion: "1.2.3",+ });await writeFile(join(projectDir, ".webstudio", "data.json"), "second");const changed = await getPreviewBuildCacheKey({projectDir,@@ -105,6 +112,7 @@ test("keys packaged preview builds to project inputs and asset metadata", async});expect(first).toBe(same);+ expect(withDraftPages).not.toBe(first);expect(changed).not.toBe(first);await expect(getPreviewBuildCacheKey({@@ -165,6 +173,34 @@ test("prepares preview by syncing missing data and generating the app template",expect(result.cwd).toBe(getPreviewProjectDir());});+test("prepares local verification previews with draft routes", async () => {+ const prebuildProject = vi.fn(async () => undefined);+ const getBuildCacheKey = vi.fn(async () => "draft-cache-key");++ await preparePreviewProject({+ assets: true,+ template: [],+ generate: true,+ includeDraftPages: true,+ accessLocalDataFile: vi.fn(async () => undefined),+ prebuildProject,+ ensureDependencies: vi.fn(async () => undefined),+ getBuildCacheKey,+ });++ expect(getBuildCacheKey).toHaveBeenCalledWith({+ projectDir: cwd(),+ assets: true,+ template: [],+ includeDraftPages: true,+ });+ expect(prebuildProject).toHaveBeenCalledWith({+ assets: true,+ template: ["defaults", "react-router"],+ includeDraftPages: true,+ });+});+test("generates preview project in isolated directory", async () => {const previousDirectory = cwd();const projectDir = join(tmpdir(), `webstudio-preview-test-${randomUUID()}`);diff --git a/packages/cli/src/commands/preview.ts b/packages/cli/src/commands/preview.tsindex db8e20d072..230be9a2a5 100644--- a/packages/cli/src/commands/preview.ts+++ b/packages/cli/src/commands/preview.ts@@ -378,11 +378,13 @@ export const getPreviewBuildCacheKey = async ({projectDir,assets,template,+ includeDraftPages = false,cliVersion = packageJson.version,}: {projectDir: string;assets: boolean;template: string[];+ includeDraftPages?: boolean;cliVersion?: string;}) => {if (cliVersion === developmentCliVersion) {@@ -395,6 +397,7 @@ export const getPreviewBuildCacheKey = async ({cliVersion,assets,template: getPreviewTemplates(template),+ includeDraftPages,}));for (const file of localPreviewFiles) {@@ -425,6 +428,7 @@ export const preparePreviewProject = async ({ensureDependencies = ensurePreviewDependencies,getBuildCacheKey = getPreviewBuildCacheKey,silent = false,+ includeDraftPages = false,prepareSessionDataFile = async () => {const connection = await resolveApiConnection();const session = createCliProjectSession({ connection });@@ -446,6 +450,7 @@ export const preparePreviewProject = async ({ensureDependencies?: typeof ensurePreviewDependencies;getBuildCacheKey?: typeof getPreviewBuildCacheKey;silent?: boolean;+ includeDraftPages?: boolean;prepareSessionDataFile?: () => Promise<void>;}): Promise<{cwd: string;@@ -488,6 +493,7 @@ export const preparePreviewProject = async ({projectDir,assets,template,+ includeDraftPages,});if (buildCacheKey !== undefined) {const cachedBuildKey = await readFile(@@ -508,6 +514,7 @@ export const preparePreviewProject = async ({assets,template: getPreviewTemplates(template),...(silent ? { silent: true } : {}),+ ...(includeDraftPages ? { includeDraftPages: true } : {}),});});await ensureDependencies(previewProjectDir);diff --git a/packages/cli/src/fs-utils.test.ts b/packages/cli/src/fs-utils.test.tsindex d6005db7a7..c248288c8c 100644--- a/packages/cli/src/fs-utils.test.ts+++ b/packages/cli/src/fs-utils.test.ts@@ -2,7 +2,7 @@ import { afterEach, beforeEach, expect, test } from "vitest";import { mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises";import { join } from "node:path";import { tmpdir } from "node:os";-import { loadJSONFile, writeFileAtomic } from "./fs-utils";+import { loadJSONFile, withFileLock, writeFileAtomic } from "./fs-utils";const originalCwd = process.cwd();let tempDir: string;@@ -39,3 +39,16 @@ test("writes files atomically without leaving temporary files", async () => {await expect(readFile("nested/data.txt", "utf8")).resolves.toBe("hello");await expect(readdir("nested")).resolves.toEqual(["data.txt"]);});++test("releases file locks when an operation fails", async () => {+ await expect(+ withFileLock("nested/data.json", async () => {+ throw new Error("failed write");+ })+ ).rejects.toThrow("failed write");++ await expect(+ withFileLock("nested/data.json", async () => "next write")+ ).resolves.toBe("next write");+ await expect(readdir("nested")).resolves.toEqual([]);+});diff --git a/packages/cli/src/fs-utils.ts b/packages/cli/src/fs-utils.tsindex 7379c5a939..ee44fb8f9f 100644--- a/packages/cli/src/fs-utils.ts+++ b/packages/cli/src/fs-utils.ts@@ -54,6 +54,37 @@ export const writeFileAtomic = async (filePath: string, content: string) => {}};+const wait = (duration: number) =>+ new Promise((resolve) => setTimeout(resolve, duration));++export const withFileLock = async <Result>(+ filePath: string,+ callback: () => Promise<Result>+) => {+ const lockPath = `${filePath}.lock`;+ await createFolderIfNotExists(dirname(filePath));+ const start = Date.now();+ while (true) {+ try {+ await mkdir(lockPath, { recursive: false });+ break;+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== "EEXIST") {+ throw error;+ }+ if (Date.now() - start > 10_000) {+ throw new Error(`Timed out waiting for file lock ${lockPath}`);+ }+ await wait(50);+ }+ }+ try {+ return await callback();+ } finally {+ await rm(lockPath, { recursive: true, force: true });+ }+};+export const loadJSONFile = async <T>(filePath: string): Promise<T | null> => {try {const content = await readFile(filePath, "utf8");diff --git a/packages/cli/src/prebuild.test.ts b/packages/cli/src/prebuild.test.tsindex e26c413f93..1d7a5c2caf 100644--- a/packages/cli/src/prebuild.test.ts+++ b/packages/cli/src/prebuild.test.ts@@ -336,6 +336,48 @@ describe("prebuild", () => {).resolves.not.toContain('"path": "/draft"');});+ test("generates draft routes for local verification without publishing them", async () => {+ await writeSiteData(+ createSiteData({+ pages: [+ {+ id: "home",+ name: "Home",+ title: "Home",+ path: "",+ rootInstanceId: "root",+ meta: {},+ },+ {+ id: "draft",+ name: "Draft",+ title: "Draft",+ path: "/draft",+ rootInstanceId: "root",+ meta: {},+ isDraft: true,+ },+ ],+ })+ );++ await prebuild({+ assets: false,+ template: ["react-router"],+ includeDraftPages: true,+ });++ await expect(+ readFile("app/routes/[draft]._index.tsx", "utf8")+ ).resolves.toContain("../__generated__/[draft]._index");+ await expect(+ readFile("app/__generated__/[draft]._index.tsx", "utf8")+ ).resolves.toContain('export const siteName = "Site"');+ await expect(+ readFile("app/__generated__/$resources.sitemap.xml.ts", "utf8")+ ).resolves.not.toContain('"path": "/draft"');+ });+test("scaffolds generated files and stores redirects as data", async () => {await mkdir("app/__generated__", { recursive: true });await mkdir("app/routes", { recursive: true });diff --git a/packages/cli/src/prebuild.ts b/packages/cli/src/prebuild.tsindex dbd18b0826..9d83bafd69 100644--- a/packages/cli/src/prebuild.ts+++ b/packages/cli/src/prebuild.ts@@ -27,6 +27,7 @@ import type {import {createScope,findTreeInstanceIds,+ getAllPages,getPagePath,getPublishablePages,generateResources,@@ -261,6 +262,8 @@ export const prebuild = async (options: {template: string[];/** Keep generated-project progress off stdout for JSON and MCP callers. */silent?: boolean;+ /** Generate draft routes for local verification without publishing them. */+ includeDraftPages?: boolean;}) => {const buildRoot = cwd();const feedback = options.silent@@ -352,6 +355,9 @@ export const prebuild = async (options: {);const pages = migratePages(siteData.build.pages);const publishablePages = getPublishablePages(pages);+ const generatedPages = options.includeDraftPages+ ? getAllPages(pages)+ : publishablePages;await writeWsAuthResources(generatedDir,pages,@@ -371,7 +377,7 @@ export const prebuild = async (options: {source: "prebuild",});- for (const page of publishablePages) {+ for (const page of generatedPages) {const instanceMap = new Map(siteData.build.instances);const pageInstanceSet = findTreeInstanceIds(instanceMap,@@ -514,7 +520,7 @@ export const prebuild = async (options: {await createFileIfNotExists(join(generatedDir, "index.css"), cssText);- for (const page of publishablePages) {+ for (const page of generatedPages) {const scope = createScope([// manually maintained list of occupied identifiers"useState",diff --git a/packages/cli/src/project-session.test.ts b/packages/cli/src/project-session.test.tsindex d441a28d7c..00a530ee64 100644--- a/packages/cli/src/project-session.test.ts+++ b/packages/cli/src/project-session.test.ts@@ -6,10 +6,12 @@ import { createBuilderStateFromSnapshot } from "@webstudio-is/project-build/statimport { createBuilderStateFreshness } from "@webstudio-is/project-build/state";import {createLocalProjectBundleFromSessionSnapshot,+ createCliProjectRestorePointStorage,createCliProjectSessionStorage,createCliProjectSessionTransport,getCliServerApiContract,getCliProjectSessionFile,+ getCliProjectRestorePointsFile,getSupportedPublicApiOperations,} from "./project-session";@@ -20,6 +22,9 @@ test("scopes project session files for explicitly selected projects", () => {expect(getCliProjectSessionFile("/workspace")).toBe("/workspace/.webstudio/project-session.json");+ expect(getCliProjectRestorePointsFile("/workspace", "project/a")).toBe(+ "/workspace/.webstudio/projects/project%2Fa/restore-points.json"+ );});const temporaryDirectories: string[] = [];@@ -40,6 +45,71 @@ afterEach(async () => {});describe("cli project session storage", () => {+ test.each([0, -1, 1.5, Number.NaN, Number.POSITIVE_INFINITY])(+ "rejects invalid restore point retention %s",+ (maxPoints) => {+ expect(() =>+ createCliProjectRestorePointStorage("restore-points.json", maxPoints)+ ).toThrow("Restore point retention must be a positive integer");+ }+ );++ test("persists named restore points and hydrates Map namespaces", async () => {+ const directory = await createTemporaryDirectory();+ const storage = createCliProjectRestorePointStorage(+ join(directory, ".webstudio", "restore-points.json")+ );+ const state = createBuilderStateFromSnapshot({+ instances: [+ [+ "body",+ { type: "instance", id: "body", component: "Body", children: [] },+ ],+ ],+ });+ const snapshot = {+ projectId: "project-1",+ buildId: "build-1",+ version: 3,+ state,+ freshness: createBuilderStateFreshness({ state, version: 3 }),+ compatibilityVersion: "test",+ compatibility: {+ sessionVersion: "test",+ runtimeContractVersion: "test-runtime",+ projectSchemaVersion: "test-schema",+ },+ };++ const created = await storage.create("Before redesign", snapshot);+ expect(await storage.list()).toEqual([created]);+ expect((await storage.get(created.id))?.state.instances).toBeInstanceOf(+ Map+ );++ const concurrentNames = Array.from(+ { length: 20 },+ (_, index) => `Concurrent ${index}`+ );+ const secondStorage = createCliProjectRestorePointStorage(+ join(directory, ".webstudio", "restore-points.json")+ );+ await Promise.all(+ concurrentNames.map((name, index) =>+ (index % 2 === 0 ? storage : secondStorage).create(name, snapshot)+ )+ );+ const retained = await storage.list();+ expect(retained).toHaveLength(20);+ expect(retained.map((point) => point.name).sort()).toEqual(+ concurrentNames.sort()+ );++ expect(await storage.delete(retained[0].id)).toBe(true);+ expect(await storage.delete(retained[0].id)).toBe(false);+ expect(await storage.list()).toHaveLength(19);+ });+test("persists builder state snapshots as JSON and checks revisions", async () => {const directory = await createTemporaryDirectory();const path = join(directory, ".webstudio", "project-session.json");diff --git a/packages/cli/src/project-session.ts b/packages/cli/src/project-session.tsindex 7e7c1f3f40..2835848633 100644--- a/packages/cli/src/project-session.ts+++ b/packages/cli/src/project-session.ts@@ -1,4 +1,4 @@-import { readFile, rm } from "node:fs/promises";+import { rm } from "node:fs/promises";import { join } from "node:path";import { cwd } from "node:process";import {@@ -18,10 +18,12 @@ import { getHomePage } from "@webstudio-is/sdk";import {createProjectSession,createDefaultProjectSessionCompatibility,+ serializeRestorePointTransaction,type ProjectSessionCompatibility,type ProjectSessionPersistedSnapshot,type ProjectSessionPermissions,type ProjectSessionRemoteSnapshot,+ type ProjectSessionRestorePointSummary,type ProjectSessionSnapshot,type ProjectSessionStorage,type ProjectSessionTransport,@@ -40,7 +42,7 @@ import type { BuilderStateFreshness } from "@webstudio-is/project-build/state";import { getLocalProjectStateDirectory, LOCAL_DATA_FILE } from "./config";import type { ApiConnection } from "./api-connection";import { getStableErrorCode } from "./error-codes";-import { writeFileAtomic } from "./fs-utils";+import { loadJSONFile, withFileLock, writeFileAtomic } from "./fs-utils";import { isPlainRecord } from "./type-utils";export type CliServerApiContract = {@@ -150,6 +152,15 @@ export const getCliProjectSessionFile = (getLocalProjectStateDirectory(projectRoot, projectId),"project-session.json");++export const getCliProjectRestorePointsFile = (+ projectRoot = cwd(),+ projectId?: string+) =>+ join(+ getLocalProjectStateDirectory(projectRoot, projectId),+ "restore-points.json"+ );const compatibilityVersion = "cli-project-session-v1";const createCliProjectSessionCompatibility = (@@ -269,19 +280,8 @@ export const createCliProjectSessionStorage = (path = getCliProjectSessionFile()): 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;- }+ const value = await loadJSONFile<PersistedCliProjectSessionSnapshot>(path);+ return value === null ? undefined : parsePersistedSnapshot(value);},async save(snapshot, options) {const current = await this.load();@@ -307,6 +307,91 @@ export const createCliProjectSessionStorage = (},});+type PersistedCliProjectRestorePoint = Pick<+ ProjectSessionRestorePointSummary,+ "id" | "name" | "createdAt"+> & {+ snapshot: PersistedCliProjectSessionSnapshot;+};++type PersistedCliProjectRestorePoints = {+ version: 1;+ points: PersistedCliProjectRestorePoint[];+};++const maxCliProjectRestorePoints = 20;++export const createCliProjectRestorePointStorage = (+ path = getCliProjectRestorePointsFile(),+ maxPoints = maxCliProjectRestorePoints+) => {+ if (Number.isInteger(maxPoints) === false || maxPoints < 1) {+ throw new Error("Restore point retention must be a positive integer");+ }+ const load = async (): Promise<PersistedCliProjectRestorePoints> =>+ (await loadJSONFile<PersistedCliProjectRestorePoints>(path)) ?? {+ version: 1,+ points: [],+ };+ const getSummary = ({+ id,+ name,+ createdAt,+ snapshot,+ }: PersistedCliProjectRestorePoint): ProjectSessionRestorePointSummary => ({+ id,+ name,+ createdAt,+ projectId: snapshot.projectId,+ buildId: snapshot.buildId,+ version: snapshot.version,+ });+ const save = async (points: PersistedCliProjectRestorePoint[]) => {+ await writeFileAtomic(+ path,+ `${JSON.stringify({ version: 1, points }, undefined, 2)}\n`+ );+ };+ return {+ async create(name: string, snapshot: ProjectSessionSnapshot) {+ return await withFileLock(path, async () => {+ const persisted = await load();+ const point: PersistedCliProjectRestorePoint = {+ id: crypto.randomUUID(),+ name,+ createdAt: new Date().toISOString(),+ snapshot: serializePersistedSnapshot(snapshot),+ };+ await save([...persisted.points, point].slice(-maxPoints));+ return getSummary(point);+ });+ },+ async list() {+ return (await load()).points.map(getSummary);+ },+ async get(id: string) {+ const point = (await load()).points.find(+ (candidate) => candidate.id === id+ );+ if (point === undefined) {+ return;+ }+ return parsePersistedSnapshot(point.snapshot);+ },+ async delete(id: string) {+ return await withFileLock(path, async () => {+ const persisted = await load();+ const points = persisted.points.filter((point) => point.id !== id);+ if (points.length === persisted.points.length) {+ return false;+ }+ await save(points);+ return true;+ });+ },+ };+};+export const createCliProjectSessionTransport = ({connection,executeServerOperation,@@ -352,6 +437,15 @@ export const createCliProjectSessionTransport = ({}))) as { version: number };},+ async commitRestorePoint({ baseVersion, transactions }) {+ return (await withMappedRemoteError(() =>+ httpClient.applyRestorePointPatch({+ ...connection,+ baseVersion,+ transactions: transactions.map(serializeRestorePointTransaction),+ })+ )) as { version: number };+ },getPermissions:getPermissions ??(async () => {diff --git a/packages/http-client/src/index.test.ts b/packages/http-client/src/index.test.tsindex 43a2737b5a..3ede461b6a 100644--- a/packages/http-client/src/index.test.ts+++ b/packages/http-client/src/index.test.ts@@ -12,6 +12,7 @@ import {} from "@webstudio-is/protocol/fixtures";import {applyBuildPatch,+ applyRestorePointPatch,attachDesignToken,bindProps,cloneInstance,@@ -834,6 +835,21 @@ test("wraps project api trpc calls in named functions", async () => {],},});+ await applyRestorePointPatch({+ ...params,+ baseVersion: 3,+ transactions: [+ {+ id: "restore-1",+ payload: [+ {+ namespace: "pages",+ patches: [{ op: "replace", path: [], value: {} }],+ },+ ],+ },+ ],+ });} finally {await new Promise<void>((resolve, reject) => {server.close((error) => (error ? reject(error) : resolve()));@@ -967,6 +983,7 @@ test("wraps project api trpc calls in named functions", async () => {expectRequest("/trpc/api.projects.permissions"),expectRequest("/trpc/api.folders.list"),expectBodyRequest("/trpc/api.build.patch", '"baseVersion":2'),+ expectBodyRequest("/trpc/build.restorePoint", '"baseVersion":3'),]);expect(decodeURIComponent(requests[0]?.search ?? "")).toContain('"include":["pages"]'diff --git a/packages/http-client/src/index.ts b/packages/http-client/src/index.tsindex 39059ad865..7acddabbcf 100644--- a/packages/http-client/src/index.ts+++ b/packages/http-client/src/index.ts@@ -7,6 +7,7 @@ import {} from "@webstudio-is/trpc-interface/api-compatibility";import {buildPatchTransaction,+ restorePointPatchTransaction,buildPatchNamespaces,bundleVersion as currentBundleVersion,importProjectBundleResult,@@ -16,6 +17,7 @@ import {stagedUploadPath,stagedUploadProjectIdHeader,parseBuilderUrl,+ projectSessionRestorePointPath,type BuildPatchTransaction,getPublicApiOperation,getPublicApiOperationPath,@@ -666,6 +668,16 @@ export const parseBuildPatchTransactions = (transactions: unknown) => {return result.data;};+const parseRestorePointPatchTransactions = (transactions: unknown) => {+ const result = restorePointPatchTransaction.array().safeParse(transactions);+ if (result.success === false) {+ throw new Error(+ `Invalid restore point transaction: ${formatSchemaIssues(result.error.issues)}`+ );+ }+ return result.data;+};+export const getBuildPatchSummary = (transactions: BuildPatchTransaction[]) => {const namespaces = new Set<(typeof buildPatchNamespaces)[number]>();let patchCount = 0;@@ -722,6 +734,17 @@ export const applyBuildPatch = async ();};+export const applyRestorePointPatch = async (+ params: AuthProjectParams & {+ baseVersion: number;+ transactions: unknown;+ }+) =>+ await mutateProjectApi(params, projectSessionRestorePointPath, {+ baseVersion: params.baseVersion,+ transactions: parseRestorePointPatchTransactions(params.transactions),+ });+type PageMetaInput = {description?: string;language?: string;@@ -1123,6 +1146,10 @@ export const insertComponent = projectMutationInput<export const insertCollection = runtimeProjectMutation("insert-collection");+export const attachSharedSlot = runtimeProjectMutation("attach-slot");++export const extractSharedSlot = runtimeProjectMutation("extract-slot");+export const insertFragment = projectMutationInput<AuthProjectParams & {parentInstanceId: string;@@ -1303,6 +1330,10 @@ export const createDesignTokens = projectMutationInput<}>("create-design-token");+export const importDesignTokens = runtimeProjectMutation(+ "import-design-tokens"+);+export const updateDesignTokenStyles = projectMutationInput<AuthProjectParams & {designTokenId: string;diff --git a/packages/project-build/src/contracts/__generated__/runtime-operation-contracts.ts b/packages/project-build/src/contracts/__generated__/runtime-operation-contracts.tsindex 1ddfdd8ddc..a95a0b001a 100644--- a/packages/project-build/src/contracts/__generated__/runtime-operation-contracts.ts+++ b/packages/project-build/src/contracts/__generated__/runtime-operation-contracts.ts@@ -57468,6 +57468,96 @@ export const runtimeOperationContractData = [retryOnConflict: false,requiresAssets: true,},+ {+ id: "slots.attach",+ command: "attach-slot",+ client: "attachSharedSlot",+ kind: "mutation",+ inputSchema: {+ type: "object",+ properties: {+ sourceSlotId: {+ type: "string",+ minLength: 1,+ },+ parentInstanceId: {+ type: "string",+ minLength: 1,+ },+ insertIndex: {+ type: "integer",+ minimum: 0,+ maximum: 9007199254740991,+ },+ label: {+ type: "string",+ minLength: 1,+ },+ },+ required: ["sourceSlotId", "parentInstanceId"],+ },+ outputSchema: {+ type: "object",+ properties: {+ slotId: {+ type: "string",+ },+ fragmentId: {+ type: "string",+ },+ },+ required: ["slotId", "fragmentId"],+ additionalProperties: {},+ },+ readNamespaces: ["instances", "props"],+ writeNamespaces: ["instances"],+ invalidatesNamespaces: ["instances"],+ retryOnConflict: false,+ },+ {+ id: "slots.extract",+ command: "extract-slot",+ client: "extractSharedSlot",+ kind: "mutation",+ inputSchema: {+ type: "object",+ properties: {+ instanceSelector: {+ minItems: 2,+ type: "array",+ items: {+ type: "string",+ minLength: 1,+ },+ },+ label: {+ type: "string",+ minLength: 1,+ },+ },+ required: ["instanceSelector"],+ },+ outputSchema: {+ type: "object",+ properties: {+ slotId: {+ type: "string",+ },+ fragmentId: {+ type: "string",+ },+ instanceId: {+ type: "string",+ },+ },+ required: ["slotId", "fragmentId", "instanceId"],+ additionalProperties: {},+ },+ readNamespaces: ["instances", "props"],+ writeNamespaces: ["instances"],+ invalidatesNamespaces: ["instances"],+ retryOnConflict: false,+ },{id: "instances.move",command: "move-instance",@@ -60261,6 +60351,257 @@ export const runtimeOperationContractData = [invalidatesNamespaces: ["styleSources", "styles"],retryOnConflict: false,},+ {+ id: "designTokens.import",+ command: "import-design-tokens",+ client: "importDesignTokens",+ kind: "mutation",+ inputSchema: {+ type: "object",+ properties: {+ source: {+ oneOf: [+ {+ type: "object",+ properties: {+ format: {+ type: "string",+ const: "dtcg",+ },+ document: {+ description:+ "DTCG token document or 2025.10 resolver document. Resolver documents may use sets, modifiers, and resolutionOrder.",+ },+ contexts: {+ description:+ "Resolver modifier contexts keyed by modifier name",+ type: "object",+ propertyNames: {+ type: "string",+ },+ additionalProperties: {+ type: "string",+ },+ },+ documents: {+ description:+ "Bundled DTCG documents keyed by resolver source path",+ type: "object",+ propertyNames: {+ type: "string",+ },+ additionalProperties: {},+ },+ },+ required: ["format"],+ },+ {+ type: "object",+ properties: {+ format: {+ type: "string",+ const: "figma",+ },+ document: {+ description:+ "Figma Variables API document containing variables and optional variableCollections",+ },+ mode: {+ description: "Optional Figma mode name or id",+ type: "string",+ minLength: 1,+ },+ allModes: {+ description:+ "Import every Figma mode under mode-qualified token names",+ type: "boolean",+ },+ },+ required: ["format"],+ },+ ],+ },+ mapping: {+ description:+ "Optional targets keyed by token type, such as color or dimension. Keys are token types, not token paths or names.",+ type: "object",+ propertyNames: {+ type: "string",+ },+ additionalProperties: {+ oneOf: [+ {+ type: "object",+ properties: {+ target: {+ type: "string",+ const: "css-variable",+ },+ },+ required: ["target"],+ },+ {+ type: "object",+ properties: {+ target: {+ type: "string",+ const: "design-token",+ },+ property: {+ type: "string",+ minLength: 1,+ description:+ "Style property for primitive tokens. Composite tokens use their canonical style properties.",+ },+ },+ required: ["target", "property"],+ },+ ],+ },+ },+ defaultTarget: {+ oneOf: [+ {+ type: "object",+ properties: {+ target: {+ type: "string",+ const: "css-variable",+ },+ },+ required: ["target"],+ },+ {+ type: "object",+ properties: {+ target: {+ type: "string",+ const: "design-token",+ },+ property: {+ type: "string",+ minLength: 1,+ description:+ "Style property for primitive tokens. Composite tokens use their canonical style properties.",+ },+ },+ required: ["target", "property"],+ },+ ],+ },+ prefix: {+ type: "string",+ },+ breakpoint: {+ type: "string",+ },+ collision: {+ default: "skip",+ type: "string",+ enum: ["skip", "overwrite", "rename"],+ },+ },+ required: ["source"],+ },+ outputSchema: {+ type: "object",+ properties: {+ plan: {+ type: "array",+ items: {+ type: "object",+ properties: {+ path: {+ type: "string",+ },+ type: {+ type: "string",+ },+ target: {+ type: "string",+ enum: ["css-variable", "design-token"],+ },+ outputName: {+ type: "string",+ },+ property: {+ type: "string",+ },+ cssValue: {+ type: "string",+ },+ declarations: {+ type: "array",+ items: {+ type: "object",+ properties: {+ property: {+ type: "string",+ },+ cssValue: {+ type: "string",+ },+ },+ required: ["property", "cssValue"],+ },+ },+ action: {+ type: "string",+ enum: ["create", "overwrite", "skip"],+ },+ conflict: {+ type: "boolean",+ },+ },+ required: [+ "path",+ "type",+ "target",+ "outputName",+ "cssValue",+ "declarations",+ "action",+ "conflict",+ ],+ },+ },+ counts: {+ type: "object",+ properties: {+ create: {+ type: "integer",+ minimum: -9007199254740991,+ maximum: 9007199254740991,+ },+ overwrite: {+ type: "integer",+ minimum: -9007199254740991,+ maximum: 9007199254740991,+ },+ skip: {+ type: "integer",+ minimum: -9007199254740991,+ maximum: 9007199254740991,+ },+ },+ required: ["create", "overwrite", "skip"],+ additionalProperties: {},+ },+ },+ required: ["plan", "counts"],+ additionalProperties: {},+ },+ readNamespaces: [+ "pages",+ "styles",+ "styleSources",+ "styleSourceSelections",+ "breakpoints",+ ],+ writeNamespaces: ["styles", "styleSources", "styleSourceSelections"],+ invalidatesNamespaces: ["styles", "styleSources", "styleSourceSelections"],+ retryOnConflict: false,+ },{id: "designTokens.createAttached",command: "create-attached-design-token",@@ -61003,6 +61344,9 @@ export const runtimeOperationContractData = [overwrite: {type: "boolean",},+ breakpoint: {+ type: "string",+ },},required: ["vars"],$defs: {diff --git a/packages/project-build/src/contracts/namespaces.ts b/packages/project-build/src/contracts/namespaces.tsindex b69f637754..b7df580fea 100644--- a/packages/project-build/src/contracts/namespaces.ts+++ b/packages/project-build/src/contracts/namespaces.ts@@ -30,3 +30,10 @@ export const builderNamespaces = [] as const;export type BuilderNamespace = (typeof builderNamespaces)[number];++// Assets are persisted separately from the versioned Build row and cannot be+// restored in the same atomic transaction.+export const restorePointNamespaces = builderNamespaces.filter(+ (namespace): namespace is Exclude<BuilderNamespace, "assets"> =>+ namespace !== "assets"+);diff --git a/packages/project-build/src/contracts/patch.test.ts b/packages/project-build/src/contracts/patch.test.tsindex 0fdc800603..b4d2d55df2 100644--- a/packages/project-build/src/contracts/patch.test.ts+++ b/packages/project-build/src/contracts/patch.test.ts@@ -5,10 +5,72 @@ import {builderPatchTransactionSchema,compactBuilderPatchPayload,hasGeneratedRecordWritePatch,+ restorePointPatchTransactionSchema,} from "./patch";import { builderNamespaces } from "./namespaces";describe("builder patch contracts", () => {+ test("restore point transactions only replace namespace roots", () => {+ const transaction = {+ id: "restore",+ payload: [+ {+ namespace: "pages",+ patches: [{ op: "replace", path: [], value: {} }],+ },+ ],+ };++ expect(+ restorePointPatchTransactionSchema.safeParse(transaction).success+ ).toBe(true);+ expect(+ restorePointPatchTransactionSchema.safeParse({+ ...transaction,+ payload: [+ {+ namespace: "pages",+ patches: [{ op: "replace", path: ["pages"], value: new Map() }],+ },+ ],+ }).success+ ).toBe(false);+ expect(+ restorePointPatchTransactionSchema.safeParse({+ ...transaction,+ payload: [+ {+ namespace: "pages",+ patches: [{ op: "add", path: [], value: {} }],+ },+ ],+ }).success+ ).toBe(false);+ expect(+ restorePointPatchTransactionSchema.safeParse({+ ...transaction,+ payload: [+ {+ namespace: "assets",+ patches: [{ op: "replace", path: [], value: new Map() }],+ },+ ],+ }).success+ ).toBe(false);+ expect(+ restorePointPatchTransactionSchema.safeParse({+ ...transaction,+ payload: [],+ }).success+ ).toBe(false);+ expect(+ restorePointPatchTransactionSchema.safeParse({+ ...transaction,+ payload: [transaction.payload[0], transaction.payload[0]],+ }).success+ ).toBe(false);+ });+test("requires values for add and replace patches", () => {expect(builderPatchSchema.safeParse({ op: "add", path: ["prop-subtitle"] })diff --git a/packages/project-build/src/contracts/patch.ts b/packages/project-build/src/contracts/patch.tsindex 09becc3116..f8c7044c73 100644--- a/packages/project-build/src/contracts/patch.ts+++ b/packages/project-build/src/contracts/patch.ts@@ -1,5 +1,9 @@import { z } from "zod";-import { builderNamespaces, type BuilderNamespace } from "./namespaces";+import {+ builderNamespaces,+ restorePointNamespaces,+ type BuilderNamespace,+} from "./namespaces";const builderPatchPath = z.array(z.union([z.string(), z.number()]));@@ -198,6 +202,42 @@ export const builderPatchTransactionSchema: z.ZodType<payload: z.array(builderPatchChangeSchema),});+const restorePointPatchSchema = z+ .object({+ op: z.literal("replace"),+ path: z.tuple([]),+ value: z.unknown(),+ })+ .superRefine(requireBuilderPatchValue);++export const restorePointPatchTransactionSchema: z.ZodType<+ BuilderPatchTransaction,+ unknown+> = z.object({+ id: z.string().min(1),+ payload: z+ .array(+ z.object({+ namespace: z.enum(restorePointNamespaces),+ patches: z.array(restorePointPatchSchema).length(1),+ })+ )+ .min(1)+ .superRefine((changes, context) => {+ const namespaces = new Set<string>();+ for (const [index, change] of changes.entries()) {+ if (namespaces.has(change.namespace)) {+ context.addIssue({+ code: z.ZodIssueCode.custom,+ path: [index, "namespace"],+ message: `Restore point namespace ${change.namespace} appears more than once`,+ });+ }+ namespaces.add(change.namespace);+ }+ }),+});+export type BuilderPatchChange = {namespace: (typeof builderNamespaces)[number];patches: BuilderPatch[];diff --git a/packages/project-build/src/mcp.test.ts b/packages/project-build/src/mcp.test.tsindex 8d0f23c4fd..53b0805019 100644--- a/packages/project-build/src/mcp.test.ts+++ b/packages/project-build/src/mcp.test.ts@@ -631,6 +631,119 @@ const createConnectedClient = async (};describe("project session mcp adapter", () => {+ test("lists restore-point tools only when the host supports them", () => {+ const restorePointToolNames = new Set([+ "create-restore-point",+ "list-restore-points",+ "delete-restore-point",+ "revert-to-restore-point",+ ]);+ expect(+ listProjectSessionMcpTools(publicMcpOperations).some((tool) =>+ restorePointToolNames.has(tool.name)+ )+ ).toBe(false);+ expect(+ listProjectSessionMcpTools(publicMcpOperations, {+ includeRestorePoints: true,+ })+ .filter((tool) => restorePointToolNames.has(tool.name))+ .map((tool) => tool.name)+ ).toEqual([+ "create-restore-point",+ "list-restore-points",+ "delete-restore-point",+ "revert-to-restore-point",+ ]);+ });++ test("requires explicit confirmation before deleting a restore point", async () => {+ const deleteRestorePoint = vi.fn(async () => ({ deleted: true }));+ const adapter = createProjectSessionMcpCore({+ operations: publicMcpOperations,+ createProjectSession: createSessionFactory(),+ executeOperation: createExecuteOperation(),+ restorePoints: {+ create: vi.fn(),+ list: vi.fn(),+ delete: deleteRestorePoint,+ revert: vi.fn(),+ },+ });++ await expect(+ adapter.callTool({+ name: "delete-restore-point",+ input: { id: "point-1" },+ })+ ).rejects.toThrow();++ const result = await adapter.callTool({+ name: "delete-restore-point",+ input: { id: "point-1", confirm: true },+ });+ expect(result.structuredContent).toMatchObject({+ ok: true,+ data: { deleted: true },+ });+ expect(deleteRestorePoint).toHaveBeenCalledWith({ id: "point-1" });+ });++ test("requires a matching confirmation token before reverting", async () => {+ const revert = vi.fn(+ async (_input: { id: string }, options: { dryRun: boolean }) =>+ createEnvelope({+ operationId: "project-session.restore-point.revert",+ result: { restoredNamespaces: ["pages"] },+ source: options.dryRun ? "dry-run" : "local",+ state: { committed: options.dryRun === false, freshness: {} },+ transaction: {+ id: "restore",+ payload: [+ {+ namespace: "pages",+ patches: [{ op: "replace", path: [], value: {} }],+ },+ ],+ },+ })+ );+ const adapter = createProjectSessionMcpCore({+ operations: publicMcpOperations,+ createProjectSession: createSessionFactory(),+ executeOperation: createExecuteOperation(),+ restorePoints: {+ create: vi.fn(),+ list: vi.fn(),+ delete: vi.fn(),+ revert,+ },+ });++ const planned = await adapter.callTool({+ name: "revert-to-restore-point",+ input: { id: "point-1", dryRun: true },+ });+ const confirmation = planned.structuredContent.meta.confirmation as {+ token: string;+ };+ expect(confirmation.token).toBeTypeOf("string");+ const committed = await adapter.callTool({+ name: "revert-to-restore-point",+ input: {+ id: "point-1",+ confirmDestructive: true,+ confirmationToken: confirmation.token,+ },+ });++ expect(committed.structuredContent.ok).toBe(true);+ expect(revert).toHaveBeenLastCalledWith(+ { id: "point-1" },+ { dryRun: false }+ );+ });+test("lists tools from the public operation catalog", () => {const tools = listProjectSessionMcpTools(publicMcpOperations);const toolNames = tools.map((tool) => tool.name);diff --git a/packages/project-build/src/mcp.ts b/packages/project-build/src/mcp.tsindex 1408e5722c..13e4f6c598 100644--- a/packages/project-build/src/mcp.ts+++ b/packages/project-build/src/mcp.ts@@ -1,5 +1,6 @@import {builderNamespaces,+ restorePointNamespaces,type BuilderNamespace,} from "./contracts/namespaces";import {@@ -16,9 +17,11 @@ import {import type { BuilderApiCapability } from "./contracts/permissions";import path from "node:path";import {+ projectSessionRestorePointSummarySchema,projectSessionBusyMessage,serializeProjectSessionMeta,type ProjectSessionEnvelope,+ type ProjectSessionRestorePointSummary,} from "./project-session";import type { ScreenshotVisualExpectation } from "./visual/screenshot-diff";import { isPlainRecord, isRecord } from "./shared/type-utils";@@ -739,6 +742,23 @@ const getHandshakeInputSchema = (};};+const getZodObjectSchema = (schema: z.ZodTypeAny) => {+ const inputSchema = toInputJsonSchemaObject(+ getInputSchemaMetadata(schema).inputJsonSchema+ );+ if (inputSchema?.type !== "object") {+ throw new Error("MCP schema must be an object");+ }+ return {+ ...inputSchema,+ type: "object",+ additionalProperties: inputSchema.additionalProperties ?? false,+ } as const;+};++const getZodMcpInputSchema = (schema: z.ZodTypeAny) =>+ getHandshakeInputSchema(getZodObjectSchema(schema)).inputSchema;+const insertCollectionMcpInputSchema = getOperationInputSchema({inputSchema: getInputSchemaMetadata(insertCollectionMcpInput).inputJsonSchema,});@@ -1927,6 +1947,118 @@ const previewDataSchema = {additionalProperties: false,} as const satisfies InputJsonSchema;+const restorePointSummaryDataSchema = getZodObjectSchema(+ projectSessionRestorePointSummarySchema+);++const restorePointCreateInput = z.object({ name: z.string().trim().min(1) });+const restorePointRevertInput = z.object({ id: z.string().min(1) });+const restorePointDeleteInput = z.object({+ id: z.string().min(1),+ confirm: z.literal(true),+});++const restorePointTools: readonly ProjectSessionMcpTool[] = [+ createProjectSessionMcpTool({+ name: "create-restore-point",+ description:+ "Create a named local restore point for versioned Build data before risky agent work. Asset records remain unchanged by restore points.",+ inputSchema: getZodMcpInputSchema(restorePointCreateInput),+ outputSchema: getMcpOutputSchema(restorePointSummaryDataSchema),+ annotations: {+ command: "create-restore-point",+ operationId: "project-session.restore-point.create",+ method: "session",+ permit: "edit",+ localCapable: true,+ serverOnly: false,+ readNamespaces: restorePointNamespaces,+ writeNamespaces: [],+ invalidatesNamespaces: [],+ retryOnConflict: false,+ },+ }),+ createProjectSessionMcpTool({+ name: "list-restore-points",+ description: "List named local restore points for the configured project.",+ inputSchema: emptyInputSchema,+ outputSchema: getMcpOutputSchema({+ type: "object",+ properties: {+ points: { type: "array", items: restorePointSummaryDataSchema },+ },+ required: ["points"],+ additionalProperties: false,+ }),+ annotations: {+ command: "list-restore-points",+ operationId: "project-session.restore-point.list",+ method: "session",+ permit: "api",+ localCapable: true,+ serverOnly: false,+ readNamespaces: [],+ writeNamespaces: [],+ invalidatesNamespaces: [],+ retryOnConflict: false,+ },+ }),+ createProjectSessionMcpTool({+ name: "delete-restore-point",+ description:+ "Permanently delete one local restore point after explicit confirmation.",+ inputSchema: getZodMcpInputSchema(restorePointDeleteInput),+ outputSchema: getMcpOutputSchema({+ type: "object",+ properties: { deleted: { type: "boolean" } },+ required: ["deleted"],+ additionalProperties: false,+ }),+ annotations: {+ command: "delete-restore-point",+ operationId: "project-session.restore-point.delete",+ method: "session",+ permit: "api",+ localCapable: true,+ serverOnly: false,+ readNamespaces: [],+ writeNamespaces: [],+ invalidatesNamespaces: [],+ retryOnConflict: false,+ },+ }),+ createProjectSessionMcpTool({+ name: "revert-to-restore-point",+ description:+ "Revert versioned Build data to a named restore point without changing assets. This is destructive and requires a reviewed dry-run confirmation token.",+ inputSchema: getZodMcpInputSchema(restorePointRevertInput),+ outputSchema: getMcpOutputSchema({+ type: "object",+ properties: {+ restoredNamespaces: {+ type: "array",+ items: { type: "string", enum: restorePointNamespaces },+ },+ },+ required: ["restoredNamespaces"],+ additionalProperties: false,+ }),+ annotations: {+ command: "revert-to-restore-point",+ operationId: "project-session.restore-point.revert",+ method: "session",+ permit: "edit",+ localCapable: true,+ serverOnly: false,+ readNamespaces: restorePointNamespaces,+ writeNamespaces: restorePointNamespaces,+ invalidatesNamespaces: [],+ retryOnConflict: false,+ requiresConfirm: true,+ },+ }),+];+const sessionTools: readonly ProjectSessionMcpTool[] = [createProjectSessionMcpTool({name: "meta.index",@@ -2567,6 +2699,7 @@ export const listProjectSessionMcpTools = (includeScreenshotDiff?: boolean;includeInstallOcr?: boolean;includePreview?: boolean;+ includeRestorePoints?: boolean;} = {}): ProjectSessionMcpTool[] => [...operations@@ -2614,6 +2747,7 @@ export const listProjectSessionMcpTools = (...tool,mcpExamples: getMcpExamples(tool.name),})),+ ...(options.includeRestorePoints ? restorePointTools : []),...(options.includeImport ? [importTool] : []),...(options.includeScreenshot ? [screenshotTool] : []),...(options.includeScreenshotDiff ? [screenshotDiffTool] : []),@@ -5783,6 +5917,19 @@ type ProjectSessionMcpCoreOptions<Command extends string> = {storeRenderedAuditArtifacts?: (manifest: RenderedAuditArtifactManifest) => Promise<string>;+ restorePoints?: ProjectSessionRestorePointHandlers;+};++type ProjectSessionRestorePointHandlers = {+ create: (input: {+ name: string;+ }) => Promise<ProjectSessionRestorePointSummary>;+ list: () => Promise<{ points: ProjectSessionRestorePointSummary[] }>;+ delete: (input: { id: string }) => Promise<{ deleted: boolean }>;+ revert: (+ input: { id: string },+ options: { dryRun: boolean }+ ) => Promise<ProjectSessionEnvelope>;};export const createProjectSessionMcpCore = <Command extends string = string>({@@ -5800,6 +5947,7 @@ export const createProjectSessionMcpCore = <Command extends string = string>({guidance,reportToolProgress,storeRenderedAuditArtifacts,+ restorePoints,}: ProjectSessionMcpCoreOptions<Command>) => {let session: ReturnType<CreateProjectSession> | undefined;let pendingCheckpoint: ProjectSessionMcpCheckpoint | undefined;@@ -5821,6 +5969,7 @@ export const createProjectSessionMcpCore = <Command extends string = string>({includeInstallOcr: installOcr !== undefined,includePreview:startPreview !== undefined && getPreviewStatus !== undefined,+ includeRestorePoints: restorePoints !== undefined,});const getSession = () => {session ??= createProjectSession();@@ -6110,6 +6259,36 @@ export const createProjectSessionMcpCore = <Command extends string = string>({const session = getSession();return toCallResult(await session.reset());}+ if (name === "create-restore-point" && restorePoints !== undefined) {+ return toMetaResult(+ await restorePoints.create(restorePointCreateInput.parse(input))+ );+ }+ if (name === "list-restore-points" && restorePoints !== undefined) {+ return toMetaResult(await restorePoints.list());+ }+ if (name === "delete-restore-point" && restorePoints !== undefined) {+ const { id } = restorePointDeleteInput.parse(input);+ return toMetaResult(await restorePoints.delete({ id }));+ }+ if (name === "revert-to-restore-point" && restorePoints !== undefined) {+ const transportInput = getToolCallInput(input, true);+ const restoreInput = restorePointRevertInput.parse(+ transportInput.input+ );+ const [envelope, response] = await executeDestructiveMcpOperation({+ command: "revert-to-restore-point",+ input: restoreInput,+ dryRun: dryRun || transportInput.dryRun,+ confirmDestructive: transportInput.confirmDestructive,+ confirmationToken: transportInput.confirmationToken,+ executeOperation: async ({ input, dryRun }) =>+ await restorePoints.revert(restorePointRevertInput.parse(input), {+ dryRun,+ }),+ });+ return response ?? toCallResult(envelope);+ }if (name === "import" && importProject !== undefined) {return toMetaResult(await importProject(getImportInput(input)));}@@ -6451,6 +6630,7 @@ export const createProjectSessionMcpServer = async <getErrorCode,reportLog,storeRenderedAuditArtifacts,+ restorePoints,onInitialized,toolHeartbeatIntervalMs = 10_000,}: Omit<ProjectSessionMcpCoreOptions<Command>, "reportToolProgress"> & {@@ -6492,6 +6672,7 @@ export const createProjectSessionMcpServer = async <stopPreview,guidance,storeRenderedAuditArtifacts,+ restorePoints,reportToolProgress: (message) => {sendLog("info", message);},diff --git a/packages/project-build/src/project-session.test.ts b/packages/project-build/src/project-session.test.tsindex 302fc064e7..a8349ab8fa 100644--- a/packages/project-build/src/project-session.test.ts+++ b/packages/project-build/src/project-session.test.ts@@ -6,9 +6,11 @@ import {createDefaultProjectSessionCompatibility,createProjectSession,hasProjectSessionPermit,+ hydrateRestorePointTransaction,projectSessionBusyMessage,redactProjectSessionValue,serializeProjectSessionMeta,+ serializeRestorePointTransaction,} from "./project-session";import { runtimeOperationContracts } from "./contracts/builder-runtime";import type {@@ -129,11 +131,15 @@ const createTransport = (): ProjectSessionTransport & {loadedNamespaces: BuilderNamespace[][];commits: BuilderPatchTransaction[][];+ patchCommits: BuilderPatchTransaction[][];+ restoreCommits: BuilderPatchTransaction[][];serverOperations: Array<{ operationId: string; input: unknown }>;permissionReads: number;} => ({loadedNamespaces: [],commits: [],+ patchCommits: [],+ restoreCommits: [],serverOperations: [],permissionReads: 0,async fetchNamespaces(input) {@@ -142,6 +148,12 @@ const createTransport = (},async commitPatch(input) {this.commits.push([...input.transactions]);+ this.patchCommits.push([...input.transactions]);+ return { version: input.baseVersion + 1 };+ },+ async commitRestorePoint(input) {+ this.commits.push([...input.transactions]);+ this.restoreCommits.push([...input.transactions]);return { version: input.baseVersion + 1 };},async getPermissions() {@@ -171,7 +183,7 @@ const createMutableTransport = () => {let remote = initialRemote;const transport = createTransport(remote);- transport.commitPatch = async (input) => {+ const commit = async (input: Parameters<typeof transport.commitPatch>[0]) => {transport.commits.push([...input.transactions]);const applied = applyBuilderPatchTransactions(remote.state,@@ -184,6 +196,14 @@ const createMutableTransport = (};return { version: remote.version };};+ transport.commitPatch = async (input) => {+ transport.patchCommits.push([...input.transactions]);+ return await commit(input);+ };+ transport.commitRestorePoint = async (input) => {+ transport.restoreCommits.push([...input.transactions]);+ return await commit(input);+ };transport.fetchNamespaces = async (input) => {transport.loadedNamespaces.push([...input.namespaces]);return remote;@@ -211,6 +231,85 @@ const createSession = ({};describe("project session", () => {+ test("round-trips hydrated restore transactions through JSON", () => {+ const state = createSnapshot().state;+ const transaction: BuilderPatchTransaction = {+ id: "restore",+ payload: ["pages", "props"].map((namespace) => ({+ namespace: namespace as "pages" | "props",+ patches: [+ {+ op: "replace",+ path: [],+ value: state[namespace as "pages" | "props"],+ },+ ],+ })),+ };++ const serialized = JSON.parse(+ JSON.stringify(serializeRestorePointTransaction(transaction))+ );+ const hydrated = hydrateRestorePointTransaction(serialized);+ const getPatchValue = (namespaceIndex: number) => {+ const patch = hydrated.payload[namespaceIndex]?.patches[0];+ if (patch?.op !== "replace") {+ throw new Error("Expected a root replacement patch");+ }+ return patch.value;+ };++ expect(getPatchValue(0)).toMatchObject({+ pages: expect.any(Map),+ folders: expect.any(Map),+ });+ expect(getPatchValue(1)).toBeInstanceOf(Map);+ });++ test("round-trips an explicitly empty marketplace product", () => {+ const transaction: BuilderPatchTransaction = {+ id: "restore",+ payload: [+ {+ namespace: "marketplaceProduct",+ patches: [{ op: "replace", path: [], value: undefined }],+ },+ ],+ };++ const serialized = JSON.parse(+ JSON.stringify(serializeRestorePointTransaction(transaction))+ );+ expect(serialized.payload[0].patches[0].value).toBeNull();++ const hydrated = hydrateRestorePointTransaction(serialized);+ expect(hydrated.payload[0]?.patches[0]).toEqual({+ op: "replace",+ path: [],+ value: undefined,+ });+ });++ test("rejects malformed serialized restore namespace values", () => {+ expect(() =>+ hydrateRestorePointTransaction({+ id: "restore",+ payload: [+ {+ namespace: "instances",+ patches: [+ {+ op: "replace",+ path: [],+ value: [["broken", { id: "broken" }]],+ },+ ],+ },+ ],+ })+ ).toThrow();+ });+test("derives default compatibility from the full runtime contract shape", () => {const compatibility =createDefaultProjectSessionCompatibility("test-session");@@ -311,6 +410,8 @@ describe("project session", () => {meta: { siteName: "Persisted site" },});expect(transport.commits).toHaveLength(1);+ expect(transport.patchCommits).toHaveLength(1);+ expect(transport.restoreCommits).toHaveLength(0);expect(transport.loadedNamespaces).toEqual([["projectSettings"],["projectSettings"],@@ -1210,6 +1311,162 @@ describe("project session", () => {expect(storage.saved.at(-1)?.version).toBe(5);});+ test("plans and atomically restores a versioned Build snapshot", async () => {+ const target = createPersistedSnapshot();+ const current = structuredClone(target);+ current.version = 2;+ current.revision = "rev-2";+ const currentHome = current.state.pages?.pages.get("page-home");+ if (currentHome === undefined) {+ throw new Error("Home page fixture is missing");+ }+ currentHome.name = "Edited after restore point";+ const storage = createStorage(current);+ const transport = createMutableTransport({+ projectId: current.projectId,+ buildId: current.buildId,+ version: current.version,+ state: current.state,+ });+ const session = createSession({ storage, transport });++ await session.initialize();+ const planned = await session.restoreSnapshot(target, { dryRun: true });+ expect(planned.source).toBe("dry-run");+ expect(planned.transaction?.payload).toContainEqual({+ namespace: "pages",+ patches: [expect.objectContaining({ op: "replace", path: [] })],+ });++ const restored = await session.restoreSnapshot(target);+ expect(restored.state.committed).toBe(true);+ expect(restored.result.restoredNamespaces).toEqual(["pages"]);+ expect(session.snapshot?.state.pages?.pages.get("page-home")?.name).toBe(+ target.state.pages?.pages.get("page-home")?.name+ );+ expect(transport.commits).toHaveLength(1);+ expect(transport.patchCommits).toHaveLength(0);+ expect(transport.restoreCommits).toHaveLength(1);+ });++ test("keeps separately persisted assets outside restore points", async () => {+ const current = createPersistedSnapshot();+ current.state.assets = new Map([+ [+ "asset-current",+ {+ id: "asset-current",+ projectId: current.projectId,+ name: "current.png",+ type: "image",+ size: 1,+ format: "png",+ createdAt: "2026-01-01T00:00:00.000Z",+ meta: { width: 1, height: 1 },+ },+ ],+ ]);+ current.freshness = createBuilderStateFreshness({+ state: current.state,+ version: current.version,+ });+ const session = createSession({ storage: createStorage(current) });++ await session.initialize();+ const restorePoint = await session.captureRestorePointSnapshot();+ expect(restorePoint.state.assets).toBeUndefined();+ expect(restorePoint.freshness.assets).toBeUndefined();++ const result = await session.restoreSnapshot({+ ...restorePoint,+ state: {+ ...restorePoint.state,+ assets: new Map(),+ },+ });+ expect(result.result.restoredNamespaces).not.toContain("assets");+ expect(session.snapshot?.state.assets?.has("asset-current")).toBe(true);+ });++ test("rejects restore points from another editable build", async () => {+ const current = createPersistedSnapshot();+ const session = createSession({ storage: createStorage(current) });+ await session.initialize();++ await expect(+ session.restoreSnapshot({ ...current, buildId: "another-build" })+ ).rejects.toThrow("different editable build");+ });++ test("restores snapshots with optional namespaces absent on both sides", async () => {+ const target = createPersistedSnapshot();+ const current = structuredClone(target);+ target.state.marketplaceProduct = undefined;+ current.state.marketplaceProduct = undefined;+ const currentHome = current.state.pages?.pages.get("page-home");+ if (currentHome === undefined) {+ throw new Error("Home page fixture is missing");+ }+ currentHome.name = "Edited after restore point";+ const transport = createMutableTransport({+ projectId: current.projectId,+ buildId: current.buildId,+ version: current.version,+ state: current.state,+ });+ const session = createSession({+ storage: createStorage(current),+ transport,+ });+ await session.initialize();++ const result = await session.restoreSnapshot(target, { dryRun: true });++ expect(result.result.restoredNamespaces).toEqual(["pages"]);+ });++ test("restores marketplace product presence and absence", async () => {+ const withProduct = createPersistedSnapshot();+ const withoutProduct = structuredClone(withProduct);+ withoutProduct.state.marketplaceProduct = undefined;+ withoutProduct.freshness = createBuilderStateFreshness({+ state: withoutProduct.state,+ version: withoutProduct.version,+ });++ const clearTransport = createMutableTransport({+ projectId: withProduct.projectId,+ buildId: withProduct.buildId,+ version: withProduct.version,+ state: withProduct.state,+ });+ const clearSession = createSession({+ storage: createStorage(withProduct),+ transport: clearTransport,+ });+ await clearSession.initialize();+ const cleared = await clearSession.restoreSnapshot(withoutProduct);+ expect(cleared.result.restoredNamespaces).toEqual(["marketplaceProduct"]);+ expect(clearSession.snapshot?.state.marketplaceProduct).toBeUndefined();++ const restoreTransport = createMutableTransport({+ projectId: withoutProduct.projectId,+ buildId: withoutProduct.buildId,+ version: withoutProduct.version,+ state: withoutProduct.state,+ });+ const restoreSession = createSession({+ storage: createStorage(withoutProduct),+ transport: restoreTransport,+ });+ await restoreSession.initialize();+ const restored = await restoreSession.restoreSnapshot(withProduct);+ expect(restored.result.restoredNamespaces).toEqual(["marketplaceProduct"]);+ expect(restoreSession.snapshot?.state.marketplaceProduct).toEqual(+ withProduct.state.marketplaceProduct+ );+ });+test("redacts sensitive diagnostic values", () => {expect(redactProjectSessionValue({diff --git a/packages/project-build/src/project-session.ts b/packages/project-build/src/project-session.tsindex 2257c96d06..d66f351903 100644--- a/packages/project-build/src/project-session.ts+++ b/packages/project-build/src/project-session.ts@@ -1,10 +1,15 @@import hash from "@emotion/hash";+import deepEqual from "fast-deep-equal";+import { z } from "zod";import type {RuntimeOperationContract,RuntimeOperationId,} from "./contracts/builder-runtime";import { runtimeOperationContracts } from "./contracts/builder-runtime";-import type { BuilderNamespace } from "./contracts/namespaces";+import {+ restorePointNamespaces,+ type BuilderNamespace,+} from "./contracts/namespaces";import type { BuilderPatchTransaction } from "./contracts/patch";import { hasGeneratedRecordWritePatch } from "./contracts/patch";import type { BuilderApiCapability } from "./contracts/permissions";@@ -32,6 +37,11 @@ import {type BuilderStateNamespaceSource,} from "./state/freshness";import { applyBuilderPatchTransactions } from "./state/patch";+import {+ createBuilderStateFromSerializedSnapshot,+ createSerializedBuilderStateSnapshotFromState,+} from "./state/adapters";+import { serializedRestorePointState } from "./schema";type ProjectSessionSource = "local" | "remote" | "dry-run" | "server";type ProjectSessionEnvelopeContract = Pick<@@ -58,6 +68,19 @@ export type ProjectSessionSnapshot = {compatibility: ProjectSessionCompatibility;};+export const projectSessionRestorePointSummarySchema = z.object({+ id: z.string(),+ name: z.string(),+ createdAt: z.string(),+ projectId: z.string(),+ buildId: z.string(),+ version: z.number().int(),+});++export type ProjectSessionRestorePointSummary = z.infer<+ typeof projectSessionRestorePointSummarySchema+>;+export type ProjectSessionPersistedSnapshot = ProjectSessionSnapshot & {revision?: string;};@@ -102,6 +125,12 @@ export type ProjectSessionTransport = {baseVersion: number;transactions: readonly BuilderPatchTransaction[];}) => Promise<ProjectSessionCommitResult>;+ commitRestorePoint: (input: {+ projectId: string;+ buildId: string;+ baseVersion: number;+ transactions: readonly BuilderPatchTransaction[];+ }) => Promise<ProjectSessionCommitResult>;executeServerOperation?: <Result>(input: {operationId: string;input: unknown;@@ -120,6 +149,71 @@ export type ProjectSessionStorage = {clear: () => Promise<void>;};+const transformRestorePointTransaction = (+ transaction: BuilderPatchTransaction,+ transform: (state: Record<string, unknown>) => Record<string, unknown>+): BuilderPatchTransaction => {+ const state: Record<string, unknown> = {};+ for (const change of transaction.payload) {+ const patch = change.patches[0];+ if (+ change.patches.length !== 1 ||+ patch?.op !== "replace" ||+ patch.path.length !== 0+ ) {+ throw new Error(+ "Restore point transactions must replace namespace roots"+ );+ }+ state[change.namespace] = patch.value;+ }+ const transformed = transform(state);+ return {+ ...transaction,+ payload: transaction.payload.map((change) => ({+ namespace: change.namespace,+ patches: [+ {+ op: "replace",+ path: [],+ value: transformed[change.namespace],+ },+ ],+ })),+ };+};++export const serializeRestorePointTransaction = (+ transaction: BuilderPatchTransaction+) =>+ transformRestorePointTransaction(transaction, (state) => {+ const serialized = createSerializedBuilderStateSnapshotFromState(+ state as BuilderState+ ) as Record<string, unknown>;+ if (+ Object.hasOwn(state, "marketplaceProduct") &&+ state.marketplaceProduct === undefined+ ) {+ serialized.marketplaceProduct = null;+ }+ return serialized;+ });++export const hydrateRestorePointTransaction = (+ transaction: BuilderPatchTransaction+) =>+ transformRestorePointTransaction(transaction, (state) => {+ const serialized = serializedRestorePointState.parse(state);+ const hydrated = createBuilderStateFromSerializedSnapshot({+ ...serialized,+ marketplaceProduct: serialized.marketplaceProduct ?? undefined,+ }) as Record<string, unknown>;+ if (serialized.marketplaceProduct === null) {+ hydrated.marketplaceProduct = undefined;+ }+ return hydrated;+ });+export type ProjectSessionOptions = {projectId: string;transport: ProjectSessionTransport;@@ -615,6 +709,147 @@ export class ProjectSession {});}+ async captureRestorePointSnapshot() {+ const snapshot = structuredClone(+ await this.ensureNamespaces(restorePointNamespaces)+ );+ delete snapshot.state.assets;+ delete snapshot.freshness.assets;+ return snapshot;+ }++ async restoreSnapshot(+ target: ProjectSessionSnapshot,+ options: { dryRun?: boolean } = {}+ ) {+ return await this.enqueueMutation(async () => {+ const snapshot = await this.ensureNamespaces(restorePointNamespaces);+ await this.assertPermit("edit");+ if (target.projectId !== snapshot.projectId) {+ throw new BuilderRuntimeError(+ "BAD_REQUEST",+ "Restore point belongs to a different project"+ );+ }+ if (target.buildId !== snapshot.buildId) {+ throw new BuilderRuntimeError(+ "CONFLICT",+ "Restore point belongs to a different editable build"+ );+ }+ if (isCompatible(target, snapshot.compatibility) === false) {+ throw new BuilderRuntimeError(+ "BAD_REQUEST",+ "Restore point is incompatible with this CLI project session"+ );+ }+ const currentSerialized = createSerializedBuilderStateSnapshotFromState(+ snapshot.state+ );+ const targetSerialized = createSerializedBuilderStateSnapshotFromState(+ target.state+ );+ const payload = restorePointNamespaces.flatMap((namespace) => {+ const currentValue = snapshot.state[namespace];+ const targetValue = target.state[namespace];+ if (+ deepEqual(currentSerialized[namespace], targetSerialized[namespace])+ ) {+ return [];+ }+ if (+ namespace !== "marketplaceProduct" &&+ (currentValue === undefined || targetValue === undefined)+ ) {+ throw new BuilderRuntimeError(+ "BAD_REQUEST",+ `Restore point is missing the ${namespace} namespace`+ );+ }+ return [+ {+ namespace,+ patches: [+ {+ op: "replace" as const,+ path: [],+ value: structuredClone(targetValue),+ },+ ],+ },+ ];+ });+ const transaction: BuilderPatchTransaction = {+ id: this.#options.runtimeContext.createId(),+ payload,+ };+ const contract: ProjectSessionEnvelopeContract = {+ id: "project-session.restore-point.revert",+ readNamespaces: restorePointNamespaces,+ writeNamespaces: restorePointNamespaces,+ invalidatesNamespaces: [],+ };+ const result = {+ restoredNamespaces: payload.map((change) => change.namespace),+ };+ if (payload.length === 0) {+ return this.createEnvelope({+ source: "local",+ result,+ committed: false,+ contract,+ snapshot,+ });+ }+ if (options.dryRun === true) {+ return this.createEnvelope({+ source: "dry-run",+ result,+ committed: false,+ contract,+ snapshot,+ transaction,+ });+ }+ const commit = await this.#options.transport.commitRestorePoint({+ 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: mergeFreshness({+ current: snapshot.freshness,+ state: applied.state,+ namespaces: result.restoredNamespaces,+ version: commit.version,+ loadedAt: new Date().toISOString(),+ source: "local",+ }),+ };+ const persisted = await this.#synchronizeAfterCommit({+ snapshot: committedSnapshot,+ namespaces: restorePointNamespaces,+ diagnostics: [],+ });+ return this.createEnvelope({+ source: "local",+ result,+ committed: true,+ contract,+ snapshot: persisted.snapshot,+ transaction,+ diagnostics: persisted.diagnostics,+ });+ });+ }+async read<Result = unknown>(operationId: RuntimeOperationId,input: unknown,diff --git a/packages/project-build/src/runtime.ts b/packages/project-build/src/runtime.tsindex db1579cab1..1c209efebe 100644--- a/packages/project-build/src/runtime.ts+++ b/packages/project-build/src/runtime.ts@@ -12,6 +12,7 @@ export * from "./runtime/content-mode-permissions";export * from "./runtime/content-model";export * from "./runtime/context";export * from "./runtime/data";+export * from "./runtime/design-token-import";export * from "./runtime/errors";export * from "./runtime/expression-validation";export * from "./runtime/fragment";diff --git a/packages/project-build/src/runtime/content-model.ts b/packages/project-build/src/runtime/content-model.tsindex 696e9f7999..331c6b40bb 100644--- a/packages/project-build/src/runtime/content-model.ts+++ b/packages/project-build/src/runtime/content-model.ts@@ -102,6 +102,10 @@ const getElementChildren = (tag: undefined | string,allowedCategories: undefined | string[]) => {+ // A transparent component without a known parent imposes no constraint.+ if (tag === undefined && allowedCategories === undefined) {+ return;+ }// components without tag behave like transparent category// and pass through parent constraintslet elementChildren: string[] =diff --git a/packages/project-build/src/runtime/cutover.ts b/packages/project-build/src/runtime/cutover.tsindex 1a25e7c669..ee82fd4a76 100644--- a/packages/project-build/src/runtime/cutover.ts+++ b/packages/project-build/src/runtime/cutover.ts@@ -135,11 +135,14 @@ export const builderRuntimeCutoverManifests = ["instances.insertComponent","instances.insertCollection","instances.insertFragment",+ "slots.attach",+ "slots.extract",] as const,callers: ["appRouter.api.instances","MCP insert-collection","MCP insert-fragment",+ "MCP shared Slot authoring","Builder components panel",] as const,},@@ -206,6 +209,7 @@ export const builderRuntimeCutoverManifests = [family: "design-token-mutations",operationIds: ["designTokens.create",+ "designTokens.import","designTokens.updateStyles","designTokens.deleteStyles","designTokens.attach",diff --git a/packages/project-build/src/runtime/design-token-import.test.ts b/packages/project-build/src/runtime/design-token-import.test.tsnew file mode 100644index 0000000000..4af5e69e18--- /dev/null+++ b/packages/project-build/src/runtime/design-token-import.test.ts@@ -0,0 +1,1641 @@+import { describe, expect, test } from "vitest";+import type { BuilderState } from "../state/builder-state";+import { applyBuilderPatchTransactions } from "../state/patch";+import {+ detectDesignTokenSource,+ designTokenImportInput,+ importDesignTokens,+ normalizeDesignTokenImport,+ planDesignTokenImport,+} from "./design-token-import";++const createState = (): BuilderState => ({+ breakpoints: new Map([["base", { id: "base", label: "Base", minWidth: 0 }]]),+ pages: {+ homePageId: "home",+ rootFolderId: "root-folder",+ pages: new Map([+ [+ "home",+ {+ id: "home",+ name: "Home",+ title: "",+ path: "",+ rootInstanceId: "root",+ meta: {},+ },+ ],+ ]),+ folders: new Map(),+ },+ styles: new Map(),+ styleSources: new Map(),+ styleSourceSelections: new Map(),+});++const createId = () => {+ let id = 0;+ return () => `generated-${++id}`;+};++const setupRootStyleSource = (state: BuilderState) => {+ state.styleSources?.set("root-local", {+ id: "root-local",+ type: "local",+ });+ state.styleSourceSelections?.set("root", {+ instanceId: "root",+ values: ["root-local"],+ });+};++describe("design token import", () => {+ test("normalizes nested DTCG tokens and resolves aliases", () => {+ const tokens = normalizeDesignTokenImport({+ source: {+ format: "dtcg",+ document: {+ color: {+ $type: "color",+ primary: { $value: "#123456" },+ action: { $value: "{color.primary}" },+ },+ },+ },+ prefix: "brand",+ collision: "skip",+ });++ expect(tokens).toEqual([+ expect.objectContaining({+ path: "color.primary",+ outputName: "--brand-color-primary",+ cssValue: "#123456",+ }),+ expect.objectContaining({+ path: "color.action",+ outputName: "--brand-color-action",+ cssValue: "#123456",+ }),+ ]);+ });++ test("normalizes Figma Variables API exports and aliases", () => {+ const tokens = normalizeDesignTokenImport({+ source: {+ format: "figma",+ mode: "light",+ document: {+ meta: {+ variables: {+ primary: {+ name: "Color/Primary",+ resolvedType: "COLOR",+ valuesByMode: { light: { r: 1, g: 0, b: 0, a: 1 } },+ },+ action: {+ name: "Color/Action",+ resolvedType: "COLOR",+ valuesByMode: {+ light: { type: "VARIABLE_ALIAS", id: "primary" },+ },+ },+ },+ },+ },+ },+ collision: "skip",+ });++ expect(tokens.map((token) => [token.outputName, token.cssValue])).toEqual([+ ["--color-primary", "rgb(255 0 0 / 1)"],+ ["--color-action", "rgb(255 0 0 / 1)"],+ ]);+ });++ test("detects Figma and DTCG documents without claiming arbitrary JSON", () => {+ const dtcg = { color: { $type: "color", $value: "#123456" } };+ const dtcgRoot = {+ spacing: {+ $type: "dimension",+ $root: { $value: { value: 8, unit: "px" } },+ },+ };+ const dtcgReference = {+ alias: { $type: "color", $ref: "#/color" },+ };+ const figma = {+ meta: {+ variables: {+ primary: {+ name: "Color/Primary",+ valuesByMode: { light: "#fff" },+ },+ },+ },+ };++ expect(detectDesignTokenSource(dtcg)).toEqual({+ format: "dtcg",+ document: dtcg,+ });+ expect(detectDesignTokenSource(dtcgRoot)).toEqual({+ format: "dtcg",+ document: dtcgRoot,+ });+ expect(detectDesignTokenSource(dtcgReference)).toEqual({+ format: "dtcg",+ document: dtcgReference,+ });+ expect(detectDesignTokenSource(figma)).toEqual({+ format: "figma",+ document: figma,+ });+ expect(detectDesignTokenSource({ color: "red" })).toBeUndefined();+ expect(+ detectDesignTokenSource({+ properties: { user: { $ref: "#/definitions/User" } },+ })+ ).toBeUndefined();+ expect(+ detectDesignTokenSource({ metadata: { $value: "not-a-token" } })+ ).toBeUndefined();+ });++ test("supports DTCG root tokens, inherited types, and both alias syntaxes", () => {+ const tokens = normalizeDesignTokenImport({+ source: {+ format: "dtcg",+ document: {+ spacing: {+ $type: "dimension",+ $root: { $value: { value: 8, unit: "px" } },+ compact: { $value: "{spacing.$root}" },+ roomy: { $ref: "#/spacing/$root/$value" },+ },+ },+ },+ collision: "skip",+ });++ expect(+ tokens.map(({ path, type, cssValue }) => [path, type, cssValue])+ ).toEqual([+ ["spacing", "dimension", "8px"],+ ["spacing.compact", "dimension", "8px"],+ ["spacing.roomy", "dimension", "8px"],+ ]);+ });++ test("converts DTCG primitive values that have direct CSS equivalents", () => {+ const tokens = normalizeDesignTokenImport({+ source: {+ format: "dtcg",+ document: {+ duration: { $type: "duration", $value: { value: 150, unit: "ms" } },+ easing: { $type: "cubicBezier", $value: [0.1, 0.2, 0.3, 1] },+ firstControl: { $type: "number", $ref: "#/easing/$value/0" },+ family: { $type: "fontFamily", $value: ["Inter", "sans-serif"] },+ alpha: { $type: "number", $value: 0.5 },+ color: {+ $type: "color",+ $value: {+ colorSpace: "srgb",+ components: [0.1, 0.2, 0.3],+ alpha: { $ref: "#/alpha/$value" },+ },+ },+ },+ },+ collision: "skip",+ });++ expect(tokens.map(({ path, cssValue }) => [path, cssValue])).toEqual([+ ["duration", "150ms"],+ ["easing", "cubic-bezier(0.1, 0.2, 0.3, 1)"],+ ["firstControl", "0.1"],+ ["family", '"Inter", sans-serif'],+ ["alpha", "0.5"],+ ["color", "rgb(26 51 77 / 0.5)"],+ ]);+ });++ test.each([+ ["srgb", [0.1, 0.2, 0.3], "rgb(26 51 77 / 0.5)"],+ ["srgb-linear", [0.1, 0.2, 0.3], "color(srgb-linear 0.1 0.2 0.3 / 0.5)"],+ ["hsl", [120, 50, 60], "hsl(120 50% 60% / 0.5)"],+ ["hwb", [120, 20, 30], "hwb(120 20% 30% / 0.5)"],+ ["lab", [50, 10, -10], "lab(50% 10 -10 / 0.5)"],+ ["lch", [50, 20, 120], "lch(50% 20 120 / 0.5)"],+ ["oklab", [0.5, 0.1, -0.1], "oklab(0.5 0.1 -0.1 / 0.5)"],+ ["oklch", [0.5, 0.2, 120], "oklch(0.5 0.2 120 / 0.5)"],+ ["display-p3", [0.1, 0.2, 0.3], "color(display-p3 0.1 0.2 0.3 / 0.5)"],+ ["a98-rgb", [0.1, 0.2, 0.3], "color(a98-rgb 0.1 0.2 0.3 / 0.5)"],+ ["prophoto-rgb", [0.1, 0.2, 0.3], "color(prophoto-rgb 0.1 0.2 0.3 / 0.5)"],+ ["rec2020", [0.1, 0.2, 0.3], "color(rec2020 0.1 0.2 0.3 / 0.5)"],+ ["xyz-d65", [0.1, 0.2, 0.3], "color(xyz-d65 0.1 0.2 0.3 / 0.5)"],+ ["xyz-d50", [0.1, 0.2, 0.3], "color(xyz-d50 0.1 0.2 0.3 / 0.5)"],+ ["srgb", ["none", 0.2, 0.3], "color(srgb none 0.2 0.3 / 0.5)"],+ ["hsl", ["none", 50, 60], "hsl(none 50% 60% / 0.5)"],+ ] as const)(+ "serializes DTCG %s colors",+ (colorSpace, components, expected) => {+ const [token] = normalizeDesignTokenImport({+ source: {+ format: "dtcg",+ document: {+ color: {+ $type: "color",+ $value: { colorSpace, components, alpha: 0.5 },+ },+ },+ },+ collision: "skip",+ });++ expect(token.cssValue).toBe(expected);+ }+ );++ test("selects Figma modes by name across variable collections", () => {+ const tokens = normalizeDesignTokenImport({+ source: {+ format: "figma",+ mode: "Dark",+ document: {+ meta: {+ variableCollections: {+ palette: {+ defaultModeId: "palette-light",+ modes: [+ { modeId: "palette-light", name: "Light" },+ { modeId: "palette-dark", name: "Dark" },+ ],+ },+ semantic: {+ defaultModeId: "semantic-light",+ modes: [+ { modeId: "semantic-light", name: "Light" },+ { modeId: "semantic-dark", name: "Dark" },+ ],+ },+ },+ variables: {+ primary: {+ name: "Color/Primary",+ resolvedType: "COLOR",+ variableCollectionId: "palette",+ valuesByMode: {+ "palette-light": { r: 1, g: 1, b: 1 },+ "palette-dark": { r: 0, g: 0, b: 0 },+ },+ },+ action: {+ name: "Color/Action",+ resolvedType: "COLOR",+ variableCollectionId: "semantic",+ valuesByMode: {+ "semantic-light": {+ type: "VARIABLE_ALIAS",+ id: "primary",+ },+ "semantic-dark": {+ type: "VARIABLE_ALIAS",+ id: "primary",+ },+ },+ },+ },+ },+ },+ },+ collision: "skip",+ });++ expect(+ tokens.map(({ outputName, cssValue }) => [outputName, cssValue])+ ).toEqual([+ ["--color-primary", "rgb(0 0 0 / 1)"],+ ["--color-action", "rgb(0 0 0 / 1)"],+ ]);+ });++ test("imports every Figma mode under deterministic mode-qualified names", () => {+ const document = {+ meta: {+ variableCollections: {+ palette: {+ defaultModeId: "light",+ modes: [+ { modeId: "light", name: "Light" },+ { modeId: "dark", name: "Dark" },+ ],+ },+ },+ variables: {+ primary: {+ name: "Color/Primary",+ resolvedType: "COLOR",+ variableCollectionId: "palette",+ valuesByMode: {+ light: { r: 1, g: 1, b: 1 },+ dark: { r: 0, g: 0, b: 0 },+ },+ },+ action: {+ name: "Color/Action",+ resolvedType: "COLOR",+ variableCollectionId: "palette",+ valuesByMode: {+ light: { type: "VARIABLE_ALIAS", id: "primary" },+ dark: { type: "VARIABLE_ALIAS", id: "primary" },+ },+ },+ },+ },+ };++ expect(+ normalizeDesignTokenImport({+ source: { format: "figma", document, allModes: true },+ collision: "skip",+ }).map(({ outputName, cssValue }) => [outputName, cssValue])+ ).toEqual([+ ["--color-primary-light", "rgb(255 255 255 / 1)"],+ ["--color-primary-dark", "rgb(0 0 0 / 1)"],+ ["--color-action-light", "rgb(255 255 255 / 1)"],+ ["--color-action-dark", "rgb(0 0 0 / 1)"],+ ]);+ expect(() =>+ designTokenImportInput.parse({+ source: { format: "figma", document, mode: "Light", allModes: true },+ collision: "skip",+ })+ ).toThrow("cannot specify both mode and allModes");+ });++ test("uses Figma collection defaults and rejects unavailable explicit modes", () => {+ const document = {+ meta: {+ variableCollections: {+ palette: {+ defaultModeId: "dark",+ modes: [+ { modeId: "light", name: "Light" },+ { modeId: "dark", name: "Dark" },+ ],+ },+ },+ variables: {+ primary: {+ name: "Color/Primary",+ resolvedType: "COLOR",+ variableCollectionId: "palette",+ valuesByMode: { light: "white", dark: "black" },+ },+ },+ },+ };+ expect(+ normalizeDesignTokenImport({+ source: { format: "figma", document },+ collision: "skip",+ })[0]?.cssValue+ ).toBe("black");+ expect(() =>+ normalizeDesignTokenImport({+ source: { format: "figma", document, mode: "High contrast" },+ collision: "skip",+ })+ ).toThrow('has no value for mode "High contrast"');+ });++ test("rejects missing and circular Figma aliases", () => {+ const variable = (id: string) => ({+ name: id,+ resolvedType: "COLOR",+ valuesByMode: {+ mode: { type: "VARIABLE_ALIAS", id },+ },+ });+ expect(() =>+ normalizeDesignTokenImport({+ source: {+ format: "figma",+ document: { variables: { source: variable("missing") } },+ },+ collision: "skip",+ })+ ).toThrow("references missing alias missing");+ expect(() =>+ normalizeDesignTokenImport({+ source: {+ format: "figma",+ document: {+ variables: {+ first: variable("second"),+ second: variable("first"),+ },+ },+ },+ collision: "skip",+ })+ ).toThrow("Figma variable alias cycle");+ });++ test("resolves Figma alias chains independently for every requested mode", () => {+ const collection = (prefix: string) => ({+ defaultModeId: `${prefix}-light`,+ modes: [+ { modeId: `${prefix}-light`, name: "Light" },+ { modeId: `${prefix}-dark`, name: "Dark" },+ ],+ });+ const aliasesByMode = (collectionId: string, targetId: string) => ({+ [`${collectionId}-light`]: { type: "VARIABLE_ALIAS", id: targetId },+ [`${collectionId}-dark`]: { type: "VARIABLE_ALIAS", id: targetId },+ });+ const document = {+ meta: {+ variableCollections: {+ primitive: collection("primitive"),+ semantic: collection("semantic"),+ component: collection("component"),+ },+ variables: {+ primitive: {+ name: "Color/Primitive",+ resolvedType: "COLOR",+ variableCollectionId: "primitive",+ valuesByMode: {+ "primitive-light": { r: 1, g: 1, b: 1, a: 0.75 },+ "primitive-dark": { r: 0, g: 0, b: 0, a: 0.25 },+ },+ },+ semantic: {+ name: "Color/Semantic",+ resolvedType: "COLOR",+ variableCollectionId: "semantic",+ valuesByMode: aliasesByMode("semantic", "primitive"),+ },+ component: {+ name: "Color/Component",+ resolvedType: "COLOR",+ variableCollectionId: "component",+ valuesByMode: aliasesByMode("component", "semantic"),+ },+ },+ },+ };+ const normalizeMode = (mode: string) =>+ normalizeDesignTokenImport({+ source: { format: "figma", document, mode },+ collision: "skip",+ }).find(({ path }) => path === "Color/Component")?.cssValue;++ expect(normalizeMode("Light")).toBe("rgb(255 255 255 / 0.75)");+ expect(normalizeMode("Dark")).toBe("rgb(0 0 0 / 0.25)");+ expect(+ normalizeDesignTokenImport({+ source: { format: "figma", document, allModes: true },+ collision: "skip",+ })+ .filter(({ path }) => path.startsWith("Color/Component/"))+ .map(({ outputName, cssValue }) => [outputName, cssValue])+ ).toEqual([+ ["--color-component-light", "rgb(255 255 255 / 0.75)"],+ ["--color-component-dark", "rgb(0 0 0 / 0.25)"],+ ]);+ });++ test("preserves falsy Figma variable values", () => {+ const tokens = normalizeDesignTokenImport({+ source: {+ format: "figma",+ document: {+ variables: {+ number: {+ name: "Value/Zero",+ resolvedType: "FLOAT",+ valuesByMode: { default: 0 },+ },+ boolean: {+ name: "Value/False",+ resolvedType: "BOOLEAN",+ valuesByMode: { default: false },+ },+ string: {+ name: "Value/Empty",+ resolvedType: "STRING",+ valuesByMode: { default: "" },+ },+ },+ },+ },+ collision: "skip",+ });++ expect(tokens.map(({ cssValue }) => cssValue)).toEqual(["0", "false", ""]);+ });++ test("rejects malformed Figma aliases before converting their value", () => {+ expect(() =>+ normalizeDesignTokenImport({+ source: {+ format: "figma",+ document: {+ variables: {+ alias: {+ name: "Color/Alias",+ resolvedType: "COLOR",+ valuesByMode: { default: { type: "VARIABLE_ALIAS" } },+ },+ },+ },+ },+ collision: "skip",+ })+ ).toThrow("Figma variable Color/Alias has an invalid alias");+ });++ test("rejects Figma names that collide after CSS name normalization", () => {+ const state = createState();+ const variable = (name: string) => ({+ name,+ resolvedType: "STRING",+ valuesByMode: { default: "value" },+ });++ expect(() =>+ importDesignTokens(+ state,+ {+ source: {+ format: "figma",+ document: {+ variables: {+ first: variable("Color / Accent"),+ second: variable("color-accent"),+ },+ },+ },+ collision: "skip",+ },+ { createId: createId() }+ )+ ).toThrow("Multiple source tokens map to --color-accent");+ });++ test("supports DTCG token and property references with escaped JSON Pointers", () => {+ const tokens = normalizeDesignTokenImport({+ source: {+ format: "dtcg",+ document: {+ "palette/base": {+ $type: "color",+ $value: {+ colorSpace: "srgb",+ components: [0.2, 0.4, 0.6],+ alpha: 0.8,+ },+ },+ alias: { $type: "color", $ref: "#/palette~1base" },+ alpha: {+ $type: "number",+ $ref: "#/palette~1base/$value/alpha",+ },+ composed: {+ $type: "color",+ $value: {+ colorSpace: "srgb",+ components: [0.1, 0.2, 0.3],+ alpha: { $ref: "#/palette~1base/$value/alpha" },+ },+ },+ },+ },+ collision: "skip",+ });++ expect(tokens.map(({ path, cssValue }) => [path, cssValue])).toEqual([+ ["palette/base", "rgb(51 102 153 / 0.8)"],+ ["alias", "rgb(51 102 153 / 0.8)"],+ ["alpha", "0.8"],+ ["composed", "rgb(26 51 77 / 0.8)"],+ ]);+ });++ test("resolves DTCG group extensions with local overrides", () => {+ const tokens = normalizeDesignTokenImport({+ source: {+ format: "dtcg",+ document: {+ base: {+ $type: "dimension",+ small: { $value: { value: 4, unit: "px" } },+ medium: { $value: { value: 8, unit: "px" } },+ },+ compact: {+ $extends: "{base}",+ medium: { $value: { value: 6, unit: "px" } },+ large: { $value: { value: 12, unit: "px" } },+ },+ },+ },+ collision: "skip",+ });++ expect(tokens.map(({ path, cssValue }) => [path, cssValue])).toEqual([+ ["base.small", "4px"],+ ["base.medium", "8px"],+ ["compact.small", "4px"],+ ["compact.medium", "6px"],+ ["compact.large", "12px"],+ ]);+ });++ test("imports DTCG $root as the group token and preserves its pointer", () => {+ const tokens = normalizeDesignTokenImport({+ source: {+ format: "dtcg",+ document: {+ spacing: {+ $type: "dimension",+ $root: { $value: { value: 8, unit: "px" } },+ compact: { $ref: "#/spacing/$root" },+ },+ alias: { $ref: "#/spacing/$root" },+ },+ },+ collision: "skip",+ });++ expect(tokens.map(({ path, cssValue }) => [path, cssValue])).toEqual([+ ["spacing", "8px"],+ ["spacing.compact", "8px"],+ ["alias", "8px"],+ ]);+ });++ test("rejects missing, token, and circular DTCG group extensions", () => {+ const normalize = (document: Record<string, unknown>) =>+ normalizeDesignTokenImport({+ source: { format: "dtcg", document },+ collision: "skip",+ });++ expect(() =>+ normalize({ group: { $extends: "{missing}", token: { $value: 1 } } })+ ).toThrow("extends missing or invalid group");+ expect(() =>+ normalize({+ token: { $type: "number", $value: 1 },+ group: { $extends: "{token}", child: { $value: 2 } },+ })+ ).toThrow("extends missing or invalid group");+ expect(() =>+ normalize({+ first: { $extends: "{second}", token: { $value: 1 } },+ second: { $extends: "{first}", token: { $value: 2 } },+ })+ ).toThrow("DTCG group extension cycle");+ });++ test("resolves stable DTCG resolver sets and modifier contexts in order", () => {+ const document = {+ version: "2025.10",+ sets: {+ foundation: {+ sources: [+ {+ color: {+ $type: "color",+ text: { $value: "black" },+ },+ spacing: {+ $type: "dimension",+ small: { $value: { value: 4, unit: "px" } },+ },+ },+ ],+ },+ },+ modifiers: {+ theme: {+ default: "light",+ contexts: {+ light: [{ color: { $type: "color", text: { $value: "black" } } }],+ dark: [{ color: { $type: "color", text: { $value: "white" } } }],+ },+ },+ },+ resolutionOrder: [+ { $ref: "#/sets/foundation" },+ { $ref: "#/modifiers/theme" },+ ],+ };+ const normalize = (contexts?: Record<string, string>) =>+ normalizeDesignTokenImport({+ source: { format: "dtcg", document, contexts },+ collision: "skip",+ }).map(({ path, cssValue }) => [path, cssValue]);++ expect(normalize()).toEqual([+ ["color.text", "black"],+ ["spacing.small", "4px"],+ ]);+ expect(normalize({ theme: "dark" })).toEqual([+ ["color.text", "white"],+ ["spacing.small", "4px"],+ ]);+ });++ test("resolves bundled external DTCG resolver sources", () => {+ const tokens = normalizeDesignTokenImport({+ source: {+ format: "dtcg",+ document: {+ version: "2025.10",+ resolutionOrder: [+ {+ type: "set",+ name: "foundation",+ sources: [{ $ref: "foundation.json" }],+ },+ ],+ },+ documents: {+ "foundation.json": {+ spacing: {+ $type: "dimension",+ small: { $value: { value: 4, unit: "px" } },+ },+ },+ },+ },+ collision: "skip",+ });++ expect(tokens.map(({ path, cssValue }) => [path, cssValue])).toEqual([+ ["spacing.small", "4px"],+ ]);+ expect(() =>+ normalizeDesignTokenImport({+ source: {+ format: "dtcg",+ document: {+ version: "2025.10",+ resolutionOrder: [+ {+ type: "set",+ name: "missing",+ sources: [{ $ref: "missing.json" }],+ },+ ],+ },+ },+ collision: "skip",+ })+ ).toThrow("was not provided in source.documents");+ });++ test("serializes all DTCG composite token types without losing sub-values", () => {+ const dimension = (value: number) => ({ value, unit: "px" });+ const color = {+ colorSpace: "srgb",+ components: [0, 0, 0],+ alpha: 0.5,+ };+ const tokens = normalizeDesignTokenImport({+ source: {+ format: "dtcg",+ document: {+ stroke: {+ $type: "strokeStyle",+ $value: {+ dashArray: [dimension(2), dimension(4)],+ lineCap: "round",+ },+ },+ border: {+ $type: "border",+ $value: { color, width: dimension(1), style: "solid" },+ },+ transition: {+ $type: "transition",+ $value: {+ duration: { value: 200, unit: "ms" },+ delay: { value: 50, unit: "ms" },+ timingFunction: [0.2, 0, 0.4, 1],+ },+ },+ shadow: {+ $type: "shadow",+ $value: {+ color,+ offsetX: dimension(0),+ offsetY: dimension(2),+ blur: dimension(8),+ spread: dimension(0),+ inset: true,+ },+ },+ gradient: {+ $type: "gradient",+ $value: [+ { color, position: 0 },+ { color: "white", position: 1 },+ ],+ },+ typography: {+ $type: "typography",+ $value: {+ fontFamily: ["Inter", "sans-serif"],+ fontSize: dimension(16),+ fontWeight: "semi-bold",+ letterSpacing: dimension(1),+ lineHeight: 1.5,+ },+ },+ },+ },+ collision: "skip",+ });++ expect(+ Object.fromEntries(+ tokens.map(({ outputName, cssValue }) => [outputName, cssValue])+ )+ ).toEqual({+ "--stroke-dash-array": "2px 4px",+ "--stroke-line-cap": "round",+ "--border": "1px solid rgb(0 0 0 / 0.5)",+ "--transition": "200ms cubic-bezier(0.2, 0, 0.4, 1) 50ms",+ "--shadow": "inset 0px 2px 8px 0px rgb(0 0 0 / 0.5)",+ "--gradient": "linear-gradient(90deg, rgb(0 0 0 / 0.5) 0%, white 100%)",+ "--typography-font-family": '"Inter", sans-serif',+ "--typography-font-size": "16px",+ "--typography-font-weight": "600",+ "--typography-letter-spacing": "1px",+ "--typography-line-height": "1.5",+ });+ });++ test("resolves aliases inside DTCG composite values", () => {+ const tokens = normalizeDesignTokenImport({+ source: {+ format: "dtcg",+ document: {+ color: {+ $type: "color",+ shadow: { $value: "rgb(0 0 0 / 0.25)" },+ },+ size: {+ $type: "dimension",+ zero: { $value: { value: 0, unit: "px" } },+ medium: { $value: { value: 8, unit: "px" } },+ },+ shadow: {+ $type: "shadow",+ $value: {+ color: "{color.shadow}",+ offsetX: "{size.zero}",+ offsetY: "{size.medium}",+ blur: { $ref: "#/size/medium/$value" },+ spread: "{size.zero}",+ },+ },+ },+ },+ collision: "skip",+ });++ expect(tokens.find(({ path }) => path === "shadow")?.cssValue).toBe(+ "0px 8px 8px 0px rgb(0 0 0 / 0.25)"+ );+ });++ test("imports DTCG typography as one design token with canonical declarations", () => {+ const state = createState();+ const mutation = importDesignTokens(+ state,+ {+ source: {+ format: "dtcg",+ document: {+ body: {+ $type: "typography",+ $value: {+ fontFamily: "Inter",+ fontSize: { value: 16, unit: "px" },+ fontWeight: 500,+ letterSpacing: { value: 0, unit: "px" },+ lineHeight: 1.5,+ },+ },+ },+ },+ mapping: {+ typography: { target: "design-token", property: "font" },+ },+ collision: "skip",+ },+ { createId: createId() }+ );+ const updated = applyBuilderPatchTransactions(state, [+ { id: "import", payload: mutation.payload },+ ]).state;+ const token = Array.from(updated.styleSources?.values() ?? []).find(+ (source) => source.type === "token" && source.name === "body"+ );++ expect(mutation.result.counts).toEqual({+ create: 1,+ overwrite: 0,+ skip: 0,+ });+ expect(+ Array.from(updated.styles?.values() ?? [])+ .filter((style) => style.styleSourceId === token?.id)+ .map((style) => [style.property, style.value])+ ).toEqual(+ expect.arrayContaining([+ ["fontFamily", { type: "unparsed", value: '"Inter"' }],+ ["fontSize", { type: "unparsed", value: "16px" }],+ ["fontWeight", { type: "unparsed", value: "500" }],+ ["letterSpacing", { type: "unparsed", value: "0px" }],+ ["lineHeight", { type: "unparsed", value: "1.5" }],+ ])+ );+ });++ test("rejects unknown DTCG properties and modifier source references", () => {+ expect(() =>+ normalizeDesignTokenImport({+ source: {+ format: "dtcg",+ document: {+ group: {+ $unknown: {},+ token: { $type: "number", $value: 1 },+ },+ },+ },+ collision: "skip",+ })+ ).toThrow("has unknown property $unknown");+ expect(() =>+ normalizeDesignTokenImport({+ source: {+ format: "dtcg",+ document: {+ version: "2025.10",+ modifiers: {+ theme: {+ default: "light",+ contexts: { light: [] },+ },+ },+ resolutionOrder: [+ {+ type: "set",+ name: "invalid",+ sources: [{ $ref: "#/modifiers/theme" }],+ },+ ],+ },+ },+ collision: "skip",+ })+ ).toThrow("cannot reference a modifier");+ });++ test("validates DTCG metadata and gradient stop positions", () => {+ const normalize = (document: Record<string, unknown>) =>+ normalizeDesignTokenImport({+ source: { format: "dtcg", document },+ collision: "skip",+ });++ expect(() =>+ normalize({ token: { $type: "number", $value: 1, $unknown: true } })+ ).toThrow("has unknown property $unknown");+ expect(() =>+ normalize({+ group: {+ $description: false,+ token: { $type: "number", $value: 1 },+ },+ })+ ).toThrow("has invalid $description");+ expect(() =>+ normalize({+ gradient: {+ $type: "gradient",+ $value: [{ color: "red", position: 1.1 }],+ },+ })+ ).toThrow("has an invalid gradient value");+ });++ test("rejects circular and unresolved DTCG JSON Pointer references", () => {+ expect(() =>+ normalizeDesignTokenImport({+ source: {+ format: "dtcg",+ document: {+ first: { $type: "color", $ref: "#/second" },+ second: { $type: "color", $ref: "#/first" },+ },+ },+ collision: "skip",+ })+ ).toThrow("DTCG alias cycle");+ expect(() =>+ normalizeDesignTokenImport({+ source: {+ format: "dtcg",+ document: {+ missing: { $type: "color", $ref: "#/does-not-exist" },+ },+ },+ collision: "skip",+ })+ ).toThrow("DTCG reference #/does-not-exist does not exist");+ });++ test("inherits DTCG types through chained references", () => {+ const tokens = normalizeDesignTokenImport({+ source: {+ format: "dtcg",+ document: {+ base: { $type: "dimension", $value: { value: 4, unit: "px" } },+ semantic: { $ref: "#/base" },+ component: { $value: "{semantic}" },+ },+ },+ collision: "skip",+ });++ expect(+ tokens.map(({ path, type, cssValue }) => [path, type, cssValue])+ ).toEqual([+ ["base", "dimension", "4px"],+ ["semantic", "dimension", "4px"],+ ["component", "dimension", "4px"],+ ]);+ });++ test("does not interpret JSON Pointer-looking strings as DTCG references", () => {+ expect(+ normalizeDesignTokenImport({+ source: {+ format: "dtcg",+ document: {+ family: { $type: "fontFamily", $value: "#/docs/getting-started" },+ },+ },+ collision: "skip",+ })[0]?.cssValue+ ).toBe('"#/docs/getting-started"');+ });++ test("rejects invalid DTCG names and reference declarations", () => {+ expect(() =>+ normalizeDesignTokenImport({+ source: {+ format: "dtcg",+ document: {+ "color.primary": { $type: "color", $value: "red" },+ color: {+ primary: { $type: "color", $value: "blue" },+ },+ },+ },+ collision: "skip",+ })+ ).toThrow("DTCG token or group color.primary has an invalid name");+ expect(() =>+ normalizeDesignTokenImport({+ source: {+ format: "dtcg",+ document: {+ invalid: {+ $type: "color",+ $value: "red",+ $ref: "#/other",+ },+ },+ },+ collision: "skip",+ })+ ).toThrow("cannot define both $value and $ref");+ expect(() =>+ normalizeDesignTokenImport({+ source: {+ format: "dtcg",+ document: {+ invalid: { $type: "color", $ref: "https://example.com/tokens" },+ },+ },+ collision: "skip",+ })+ ).toThrow("is not a local JSON Pointer");+ });++ test.each([+ "{color.primary",+ "color.primary}",+ "{color..primary}",+ "{color.$invalid}",+ ])("rejects malformed DTCG reference %s", (reference) => {+ expect(() =>+ normalizeDesignTokenImport({+ source: {+ format: "dtcg",+ document: {+ alias: { $type: "color", $value: reference },+ },+ },+ collision: "skip",+ })+ ).toThrow(`DTCG reference ${JSON.stringify(reference)} is invalid`);+ });++ test("accepts numeric DTCG path segments", () => {+ expect(+ normalizeDesignTokenImport({+ source: {+ format: "dtcg",+ document: {+ color: {+ $type: "color",+ blue: { "500": { $value: "#0066cc" } },+ accent: { $value: "{color.blue.500}" },+ },+ },+ },+ collision: "skip",+ }).map(({ path, cssValue }) => [path, cssValue])+ ).toEqual([+ ["color.blue.500", "#0066cc"],+ ["color.accent", "#0066cc"],+ ]);+ });++ test.each([+ [+ "unknown type",+ { invalid: { $type: "unknown", $value: 1 } },+ "invalid $type",+ ],+ [+ "number with a string value",+ { invalid: { $type: "number", $value: "1" } },+ "invalid number value",+ ],+ [+ "color with a missing component",+ {+ invalid: {+ $type: "color",+ $value: { colorSpace: "srgb", components: [0, 0] },+ },+ },+ "invalid color value",+ ],+ [+ "color with alpha outside its range",+ {+ invalid: {+ $type: "color",+ $value: { colorSpace: "srgb", components: [0, 0, 0], alpha: 2 },+ },+ },+ "invalid color value",+ ],+ [+ "empty font family list",+ { invalid: { $type: "fontFamily", $value: [] } },+ "invalid fontFamily value",+ ],+ [+ "cubic Bezier with an invalid x coordinate",+ { invalid: { $type: "cubicBezier", $value: [2, 0, 0.5, 1] } },+ "invalid cubicBezier value",+ ],+ ])("rejects DTCG %s", (_case, document, message) => {+ expect(() =>+ normalizeDesignTokenImport({+ source: { format: "dtcg", document },+ collision: "skip",+ })+ ).toThrow(message);+ });++ test("skips collisions without changing the project", () => {+ const state = createState();+ setupRootStyleSource(state);+ state.styles?.set("root-local:base:--brand-color:", {+ styleSourceId: "root-local",+ breakpointId: "base",+ property: "--brand-color",+ value: { type: "unparsed", value: "old" },+ });+ const mutation = importDesignTokens(+ state,+ {+ source: {+ format: "dtcg",+ document: { color: { $type: "color", $value: "#123456" } },+ },+ prefix: "brand",+ collision: "skip",+ },+ { createId: createId() }+ );++ expect(mutation.payload).toEqual([]);+ expect(mutation.result.counts).toEqual({+ create: 0,+ overwrite: 0,+ skip: 1,+ });+ });++ test("preflights and deterministically renames CSS variable collisions", () => {+ const state = createState();+ setupRootStyleSource(state);+ for (const property of ["--color", "--color-1"] as const) {+ state.styles?.set(`root-local:base:${property}:`, {+ styleSourceId: "root-local",+ breakpointId: "base",+ property,+ value: { type: "unparsed", value: "old" },+ });+ }+ const input = {+ source: {+ format: "dtcg" as const,+ document: {+ color: { $type: "color", $value: "#123456" },+ "color-2": { $type: "color", $value: "#abcdef" },+ },+ },+ collision: "rename" as const,+ };++ const plan = planDesignTokenImport(state, input);++ expect(plan).toEqual([+ expect.objectContaining({ outputName: "--color-3", action: "create" }),+ expect.objectContaining({ outputName: "--color-2", action: "create" }),+ ]);+ expect(state.styles?.has("root-local:base:--color-3:")).toBe(false);++ const mutation = importDesignTokens(state, input, { createId: createId() });+ const updated = applyBuilderPatchTransactions(state, [+ { id: "import", payload: mutation.payload },+ ]).state;+ expect(updated.styles?.get("root-local:base:--color:")?.value).toEqual({+ type: "unparsed",+ value: "old",+ });+ expect(updated.styles?.get("root-local:base:--color-3:")?.value).toEqual({+ type: "unparsed",+ value: "#123456",+ });+ });++ test("renames colliding design tokens and overwrites CSS variables", () => {+ const state = createState();+ setupRootStyleSource(state);+ state.styles?.set("root-local:base:--spacing:", {+ styleSourceId: "root-local",+ breakpointId: "base",+ property: "--spacing",+ value: { type: "unparsed", value: "4px" },+ });+ state.styleSources?.set("color-token", {+ id: "color-token",+ type: "token",+ name: "color",+ });++ const overwrite = importDesignTokens(+ state,+ {+ source: {+ format: "dtcg",+ document: {+ spacing: {+ $type: "dimension",+ $value: { value: 8, unit: "px" },+ },+ },+ },+ collision: "overwrite",+ },+ { createId: createId() }+ );+ const overwritten = applyBuilderPatchTransactions(state, [+ { id: "overwrite", payload: overwrite.payload },+ ]).state;+ expect(+ overwritten.styles?.get("root-local:base:--spacing:")?.value+ ).toEqual({ type: "unparsed", value: "8px" });++ const rename = importDesignTokens(+ state,+ {+ source: {+ format: "dtcg",+ document: { color: { $type: "color", $value: "#123456" } },+ },+ mapping: { color: { target: "design-token", property: "color" } },+ collision: "rename",+ },+ { createId: createId() }+ );+ const renamed = applyBuilderPatchTransactions(state, [+ { id: "rename", payload: rename.payload },+ ]).state;+ expect(+ Array.from(renamed.styleSources?.values() ?? []).find(+ (source) => source.type === "token" && source.name === "color-1"+ )+ ).toBeDefined();+ });++ test("distinguishes matching values from conflicts during preflight", () => {+ const state = createState();+ setupRootStyleSource(state);+ state.styles?.set("root-local:base:--color:", {+ styleSourceId: "root-local",+ breakpointId: "base",+ property: "--color",+ value: { type: "unparsed", value: "#123456" },+ });+ const plan = planDesignTokenImport(state, {+ source: {+ format: "dtcg",+ document: { color: { $type: "color", $value: "#123456" } },+ },+ collision: "rename",+ });++ expect(plan).toEqual([+ expect.objectContaining({+ outputName: "--color",+ action: "skip",+ conflict: false,+ }),+ ]);+ });++ test("treats extra design token declarations as a conflict", () => {+ const state = createState();+ state.styleSources?.set("color-token", {+ id: "color-token",+ type: "token",+ name: "color",+ });+ state.styles?.set("color-token:base:color:", {+ styleSourceId: "color-token",+ breakpointId: "base",+ property: "color",+ value: { type: "unparsed", value: "#123456" },+ });+ state.styles?.set("color-token:base:backgroundColor:", {+ styleSourceId: "color-token",+ breakpointId: "base",+ property: "backgroundColor",+ value: { type: "unparsed", value: "#123456" },+ });++ const plan = planDesignTokenImport(state, {+ source: {+ format: "dtcg",+ document: { color: { $type: "color", $value: "#123456" } },+ },+ mapping: { color: { target: "design-token", property: "color" } },+ collision: "skip",+ });++ expect(plan).toEqual([+ expect.objectContaining({+ outputName: "color",+ action: "skip",+ conflict: true,+ }),+ ]);+ });++ test("imports mapped families through existing mutation operations", () => {+ const state = createState();+ const mutation = importDesignTokens(+ state,+ {+ source: {+ format: "dtcg",+ document: {+ color: {+ $type: "color",+ primary: { $value: "#123456" },+ },+ spacing: {+ $type: "dimension",+ small: { $value: { value: 8, unit: "px" } },+ },+ },+ },+ mapping: {+ color: { target: "design-token", property: "color" },+ dimension: { target: "css-variable" },+ },+ collision: "skip",+ },+ { createId: createId() }+ );+ const updated = applyBuilderPatchTransactions(state, [+ { id: "import", payload: mutation.payload },+ ]).state;++ expect(mutation.result.counts).toEqual({+ create: 2,+ overwrite: 0,+ skip: 0,+ });+ expect(+ Array.from(updated.styleSources?.values() ?? []).find(+ (source) => source.type === "token"+ )+ ).toMatchObject({ name: "color-primary" });+ expect(+ Array.from(updated.styles?.values() ?? []).map((style) => [+ style.property,+ style.value,+ ])+ ).toEqual(+ expect.arrayContaining([+ ["color", { type: "unparsed", value: "#123456" }],+ ["--spacing-small", { type: "unparsed", value: "8px" }],+ ])+ );+ });++ test("rejects missing aliases and invalid composite values", () => {+ expect(() =>+ normalizeDesignTokenImport({+ source: {+ format: "dtcg",+ document: {+ color: { $type: "color", $value: "{color.missing}" },+ },+ },+ collision: "skip",+ })+ ).toThrow("references missing alias");+ expect(() =>+ normalizeDesignTokenImport({+ source: {+ format: "dtcg",+ document: {+ typography: {+ $type: "typography",+ $value: { family: "Inter", size: 16 },+ },+ },+ },+ collision: "skip",+ })+ ).toThrow("invalid typography value");+ expect(() =>+ normalizeDesignTokenImport({+ source: {+ format: "dtcg",+ document: {+ first: { $type: "color", $value: "{second}" },+ second: { $type: "color", $value: "{first}" },+ },+ },+ collision: "skip",+ })+ ).toThrow("DTCG alias cycle");+ });++ test("rejects invalid DTCG structures, types, and units", () => {+ expect(() =>+ normalizeDesignTokenImport({+ source: {+ format: "dtcg",+ document: { missingType: { $value: 1 } },+ },+ collision: "skip",+ })+ ).toThrow("is missing $type");+ expect(() =>+ normalizeDesignTokenImport({+ source: {+ format: "dtcg",+ document: {+ color: { $type: "color", $value: "red" },+ alias: { $type: "number", $value: "{color}" },+ },+ },+ collision: "skip",+ })+ ).toThrow("has type number but aliases color");+ expect(() =>+ normalizeDesignTokenImport({+ source: {+ format: "dtcg",+ document: {+ spacing: {+ $type: "dimension",+ $value: { value: 1, unit: "em" },+ },+ },+ },+ collision: "skip",+ })+ ).toThrow("invalid dimension unit em");+ expect(() =>+ normalizeDesignTokenImport({+ source: {+ format: "dtcg",+ document: {+ invalid: {+ $type: "number",+ $value: 1,+ child: { $value: 2 },+ },+ },+ },+ collision: "skip",+ })+ ).toThrow("cannot contain child tokens or groups");+ });++ test("scopes CSS variable collisions to the root and selected breakpoint", () => {+ const state = createState();+ state.breakpoints?.set("mobile", {+ id: "mobile",+ label: "Mobile",+ maxWidth: 767,+ });+ setupRootStyleSource(state);+ state.styleSources?.set("component-local", {+ id: "component-local",+ type: "local",+ });+ state.styles?.set("component-local:base:--color:", {+ styleSourceId: "component-local",+ breakpointId: "base",+ property: "--color",+ value: { type: "unparsed", value: "component" },+ });+ state.styles?.set("root-local:mobile:--color:", {+ styleSourceId: "root-local",+ breakpointId: "mobile",+ property: "--color",+ value: { type: "unparsed", value: "mobile" },+ });++ const mutation = importDesignTokens(+ state,+ {+ source: {+ format: "dtcg",+ document: { color: { $type: "color", $value: "#123456" } },+ },+ collision: "skip",+ },+ { createId: createId() }+ );+ const updated = applyBuilderPatchTransactions(state, [+ { id: "import", payload: mutation.payload },+ ]).state;++ expect(mutation.result.counts).toEqual({+ create: 1,+ overwrite: 0,+ skip: 0,+ });+ expect(updated.styles?.get("root-local:base:--color:")?.value).toEqual({+ type: "unparsed",+ value: "#123456",+ });+ expect(updated.styles?.get("root-local:mobile:--color:")?.value).toEqual({+ type: "unparsed",+ value: "mobile",+ });+ expect(updated.styles?.get("component-local:base:--color:")?.value).toEqual(+ {+ type: "unparsed",+ value: "component",+ }+ );+ });+});diff --git a/packages/project-build/src/runtime/design-token-import.ts b/packages/project-build/src/runtime/design-token-import.tsnew file mode 100644index 0000000000..3e254ac62c--- /dev/null+++ b/packages/project-build/src/runtime/design-token-import.ts@@ -0,0 +1,1710 @@+import { z } from "zod";+import {+ color as colorEngine,+ toColorSpace,+ toValue,+ type StyleProperty,+} from "@webstudio-is/css-engine";+import { fontWeightNames } from "@webstudio-is/fonts";+import { getStyleDeclKey } from "@webstudio-is/sdk";+import type { BuilderState } from "../state/builder-state";+import { isPlainRecord as isRecord } from "../shared/type-utils";+import type { BuilderRuntimeContext } from "./context";+import { throwBuilderRuntimeError } from "./errors";+import { createRuntimeMutationAccumulator } from "./mutation";+import { getUniqueNameWithSuffix } from "./style-utils";+import {+ createDesignTokens,+ defineCssVariables,+ getCssVariableRootTarget,+ updateDesignTokenStyles,+} from "./styles";++const designTokenSourceInput = z+ .discriminatedUnion("format", [+ z.object({+ format: z.literal("dtcg"),+ document: z+ .unknown()+ .describe(+ "DTCG token document or 2025.10 resolver document. Resolver documents may use sets, modifiers, and resolutionOrder."+ ),+ contexts: z+ .record(z.string(), z.string())+ .optional()+ .describe("Resolver modifier contexts keyed by modifier name"),+ documents: z+ .record(z.string(), z.unknown())+ .optional()+ .describe("Bundled DTCG documents keyed by resolver source path"),+ }),+ z.object({+ format: z.literal("figma"),+ document: z+ .unknown()+ .describe(+ "Figma Variables API document containing variables and optional variableCollections"+ ),+ mode: z+ .string()+ .min(1)+ .optional()+ .describe("Optional Figma mode name or id"),+ allModes: z+ .boolean()+ .optional()+ .describe("Import every Figma mode under mode-qualified token names"),+ }),+ ])+ .refine(+ (source) =>+ source.format !== "figma" ||+ source.mode === undefined ||+ source.allModes !== true,+ { message: "Figma source cannot specify both mode and allModes" }+ );++const targetInput = z.discriminatedUnion("target", [+ z.object({ target: z.literal("css-variable") }),+ z.object({+ target: z.literal("design-token"),+ property: z+ .string()+ .min(1)+ .describe(+ "Style property for primitive tokens. Composite tokens use their canonical style properties."+ ),+ }),+]);++export const designTokenImportInput = z.object({+ source: designTokenSourceInput,+ mapping: z+ .record(z.string(), targetInput)+ .optional()+ .describe(+ "Optional targets keyed by token type, such as color or dimension. Keys are token types, not token paths or names."+ ),+ defaultTarget: targetInput.optional(),+ prefix: z.string().optional(),+ breakpoint: z.string().optional(),+ collision: z.enum(["skip", "overwrite", "rename"]).default("skip"),+});++export const designTokenImportPlanEntrySchema = z.object({+ path: z.string(),+ type: z.string(),+ target: z.enum(["css-variable", "design-token"]),+ outputName: z.string(),+ property: z.string().optional(),+ cssValue: z.string(),+ declarations: z.array(+ z.object({ property: z.string(), cssValue: z.string() })+ ),+ action: z.enum(["create", "overwrite", "skip"]),+ conflict: z.boolean(),+});++type NormalizedToken = {+ path: string;+ type: string;+ value: unknown;+};++type CssDeclaration = {+ key?: string;+ property?: string;+ cssValue: string;+};++type ImportPlanEntry = z.infer<typeof designTokenImportPlanEntrySchema>;+type NormalizedImportEntry = Omit<ImportPlanEntry, "action" | "conflict">;++const withDeclarationSummary = (+ entry: Omit<NormalizedImportEntry, "property" | "cssValue">+): NormalizedImportEntry => ({+ ...entry,+ property:+ entry.declarations.length === 1+ ? entry.declarations[0].property+ : undefined,+ cssValue:+ entry.declarations.length === 1+ ? entry.declarations[0].cssValue+ : entry.declarations+ .map(({ property, cssValue }) => `${property}: ${cssValue}`)+ .join("; "),+});++type ImportState = Pick<+ BuilderState,+ "breakpoints" | "pages" | "styles" | "styleSources" | "styleSourceSelections"+>;++const dtcgTokenTypeInput = z.enum([+ "color",+ "dimension",+ "fontFamily",+ "fontWeight",+ "duration",+ "cubicBezier",+ "number",+ "strokeStyle",+ "border",+ "transition",+ "shadow",+ "gradient",+ "typography",+]);++type DtcgTokenType = z.infer<typeof dtcgTokenTypeInput>;++const numberWithUnitInput = z+ .object({+ value: z.number(),+ unit: z.string(),+ })+ .strict();++const cubicBezierValueInput = z.tuple([+ z.number().min(0).max(1),+ z.number(),+ z.number().min(0).max(1),+ z.number(),+]);++const colorValueInput = z.union([+ z.string().min(1),+ z+ .object({+ colorSpace: z.enum([+ "srgb",+ "srgb-linear",+ "hsl",+ "hwb",+ "lab",+ "lch",+ "oklab",+ "oklch",+ "display-p3",+ "a98-rgb",+ "prophoto-rgb",+ "rec2020",+ "xyz-d65",+ "xyz-d50",+ ]),+ components: z.tuple([+ z.union([z.number(), z.literal("none")]),+ z.union([z.number(), z.literal("none")]),+ z.union([z.number(), z.literal("none")]),+ ]),+ alpha: z.number().min(0).max(1).optional(),+ hex: z.string().optional(),+ })+ .strict(),+]);++const fontFamilyValueInput = z.union([+ z.string().min(1),+ z.array(z.string()).min(1),+]);++const fontWeightValueInput = z.union([+ z.number().min(1).max(1000),+ z.enum([+ "thin",+ "hairline",+ "extra-light",+ "ultra-light",+ "light",+ "normal",+ "regular",+ "book",+ "medium",+ "semi-bold",+ "demi-bold",+ "bold",+ "extra-bold",+ "ultra-bold",+ "black",+ "heavy",+ "extra-black",+ "ultra-black",+ ]),+]);++const strokeStyleValueInput = z.union([+ z.enum([+ "solid",+ "dashed",+ "dotted",+ "double",+ "groove",+ "ridge",+ "outset",+ "inset",+ ]),+ z+ .object({+ dashArray: z.array(numberWithUnitInput).min(1),+ lineCap: z.enum(["round", "butt", "square"]),+ })+ .strict(),+]);++const shadowValueInput = z+ .object({+ color: colorValueInput,+ offsetX: numberWithUnitInput,+ offsetY: numberWithUnitInput,+ blur: numberWithUnitInput,+ spread: numberWithUnitInput,+ inset: z.boolean().optional(),+ })+ .strict();++const dtcgValueInputs = {+ color: colorValueInput,+ dimension: numberWithUnitInput,+ fontFamily: fontFamilyValueInput,+ fontWeight: fontWeightValueInput,+ duration: numberWithUnitInput,+ cubicBezier: cubicBezierValueInput,+ number: z.number(),+ strokeStyle: strokeStyleValueInput,+ border: z+ .object({+ color: colorValueInput,+ width: numberWithUnitInput,+ style: strokeStyleValueInput,+ })+ .strict(),+ transition: z+ .object({+ duration: numberWithUnitInput,+ delay: numberWithUnitInput,+ timingFunction: cubicBezierValueInput,+ })+ .strict(),+ shadow: z.union([shadowValueInput, z.array(shadowValueInput).min(1)]),+ gradient: z+ .array(+ z+ .object({+ color: colorValueInput,+ position: z.number().min(0).max(1),+ })+ .strict()+ )+ .min(1),+ typography: z+ .object({+ fontFamily: fontFamilyValueInput,+ fontSize: numberWithUnitInput,+ fontWeight: fontWeightValueInput,+ letterSpacing: numberWithUnitInput,+ lineHeight: z.number(),+ })+ .strict(),+} satisfies Partial<Record<DtcgTokenType, z.ZodType>>;++type DtcgColor = Exclude<z.infer<(typeof dtcgValueInputs)["color"]>, string>;++const dtcgMetadataProperties = [+ "$deprecated",+ "$description",+ "$extensions",+ "$type",+] as const;+const dtcgTokenProperties = new Set([+ ...dtcgMetadataProperties,+ "$ref",+ "$value",+]);+const dtcgGroupProperties = new Set([+ ...dtcgMetadataProperties,+ "$extends",+ "$root",+ "$schema",+]);++const getFigmaDocumentData = (document: unknown) => {+ if (isRecord(document) === false) {+ return;+ }+ const meta = isRecord(document.meta) ? document.meta : document;+ const variables = isRecord(meta.variables) ? meta.variables : undefined;+ if (variables === undefined) {+ return;+ }+ return {+ variables,+ variableCollections: isRecord(meta.variableCollections)+ ? meta.variableCollections+ : {},+ };+};++const hasDtcgToken = (+ value: unknown,+ inheritedType?: DtcgTokenType+): boolean => {+ if (isRecord(value) === false) {+ return false;+ }+ const parsedType = dtcgTokenTypeInput.safeParse(value.$type);+ const type = parsedType.success ? parsedType.data : inheritedType;+ if (+ type !== undefined &&+ ("$value" in value || typeof value.$ref === "string")+ ) {+ return true;+ }+ return Object.entries(value).some(+ ([name, child]) =>+ (name.startsWith("$") === false || name === "$root") &&+ hasDtcgToken(child, type)+ );+};++const isDtcgToken = (value: unknown) =>+ isRecord(value) &&+ ("$value" in value ||+ (Object.keys(value).every((key) => key.startsWith("$")) &&+ "$ref" in value));++const mergeDtcgDocuments = (+ target: Record<string, unknown>,+ source: Record<string, unknown>+): Record<string, unknown> => {+ const result = { ...target };+ for (const [name, value] of Object.entries(source)) {+ const previous = result[name];+ result[name] =+ isRecord(previous) &&+ isRecord(value) &&+ isDtcgToken(previous) === false &&+ isDtcgToken(value) === false+ ? mergeDtcgDocuments(previous, value)+ : value;+ }+ return result;+};++const resolveJsonPointer = (document: unknown, pointer: string) => {+ if (pointer === "#") {+ return document;+ }+ if (pointer.startsWith("#/") === false) {+ return;+ }+ let value = document;+ for (const encodedSegment of pointer.slice(2).split("/")) {+ const segment = encodedSegment.replaceAll("~1", "/").replaceAll("~0", "~");+ if (Array.isArray(value)) {+ const index = Number(segment);+ if (+ Number.isInteger(index) === false ||+ index < 0 ||+ index >= value.length+ ) {+ return;+ }+ value = value[index];+ continue;+ }+ if (isRecord(value) === false || Object.hasOwn(value, segment) === false) {+ return;+ }+ value = value[segment];+ }+ return value;+};++const resolveDtcgResolver = ({+ document,+ contexts = {},+ documents = {},+}: {+ document: Record<string, unknown>;+ contexts?: Record<string, string>;+ documents?: Record<string, unknown>;+}) => {+ if (+ document.version !== "2025.10" ||+ Array.isArray(document.resolutionOrder) === false+ ) {+ return document;+ }+ const resolveReference = (reference: string, stack: string[]): unknown => {+ const [pathname, fragment] = reference.split("#", 2);+ const sourceDocument = pathname === "" ? document : documents[pathname];+ if (sourceDocument === undefined) {+ return throwBuilderRuntimeError(+ "INVALID_INPUT",+ `DTCG resolver source ${JSON.stringify(pathname)} was not provided in source.documents`+ );+ }+ const key = `${pathname}#${fragment ?? ""}`;+ if (stack.includes(key)) {+ return throwBuilderRuntimeError(+ "INVALID_INPUT",+ `DTCG resolver reference cycle: ${[...stack, key].join(" -> ")}`+ );+ }+ const target =+ fragment === undefined+ ? sourceDocument+ : resolveJsonPointer(sourceDocument, `#${fragment}`);+ if (target === undefined) {+ return throwBuilderRuntimeError(+ "INVALID_INPUT",+ `DTCG resolver reference ${reference} does not exist`+ );+ }+ if (isRecord(target) && Array.isArray(target.sources)) {+ return resolveSources(target.sources, [...stack, key]);+ }+ if (isRecord(target) && isRecord(target.contexts)) {+ return throwBuilderRuntimeError(+ "INVALID_INPUT",+ `DTCG resolver source ${reference} cannot reference a modifier`+ );+ }+ return target;+ };+ const resolveSources = (sources: unknown[], stack: string[]) => {+ let merged: Record<string, unknown> = {};+ for (const source of sources) {+ const resolved =+ isRecord(source) &&+ typeof source.$ref === "string" &&+ Object.keys(source).every((key) => key.startsWith("$"))+ ? resolveReference(source.$ref, stack)+ : source;+ if (isRecord(resolved) === false) {+ return throwBuilderRuntimeError(+ "INVALID_INPUT",+ "DTCG resolver sources must resolve to token documents"+ );+ }+ merged = mergeDtcgDocuments(merged, resolved);+ }+ return merged;+ };+ const resolveItem = (item: unknown) => {+ if (isRecord(item) && typeof item.$ref === "string") {+ const match = item.$ref.match(/^#\/(sets|modifiers)\/([^/]+)$/);+ if (match !== null) {+ const target = resolveJsonPointer(document, item.$ref);+ if (isRecord(target)) {+ return {+ ...target,+ type: match[1] === "sets" ? "set" : "modifier",+ name: match[2].replaceAll("~1", "/").replaceAll("~0", "~"),+ };+ }+ }+ return resolveReference(item.$ref, []);+ }+ return item;+ };++ let resolvedDocument: Record<string, unknown> = {};+ const modifierNames = new Set<string>();+ for (const entry of document.resolutionOrder) {+ const item = resolveItem(entry);+ if (+ isRecord(item) === false ||+ (item.type !== "set" && item.type !== "modifier")+ ) {+ return throwBuilderRuntimeError(+ "INVALID_INPUT",+ "DTCG resolver resolutionOrder entries must resolve to sets or modifiers"+ );+ }+ if (item.type === "set") {+ if (Array.isArray(item.sources) === false) {+ return throwBuilderRuntimeError(+ "INVALID_INPUT",+ "DTCG resolver set is missing sources"+ );+ }+ resolvedDocument = mergeDtcgDocuments(+ resolvedDocument,+ resolveSources(item.sources, [])+ );+ continue;+ }+ if (+ typeof item.name !== "string" ||+ isRecord(item.contexts) === false ||+ Object.keys(item.contexts).length === 0+ ) {+ return throwBuilderRuntimeError(+ "INVALID_INPUT",+ "DTCG resolver modifier is missing name or contexts"+ );+ }+ if (modifierNames.has(item.name)) {+ return throwBuilderRuntimeError(+ "INVALID_INPUT",+ `DTCG resolver modifier ${item.name} appears more than once`+ );+ }+ modifierNames.add(item.name);+ const selectedContext = contexts[item.name] ?? item.default;+ const sources =+ selectedContext === undefined+ ? undefined+ : item.contexts[selectedContext];+ if (Array.isArray(sources) === false) {+ return throwBuilderRuntimeError(+ "INVALID_INPUT",+ selectedContext === undefined+ ? `DTCG resolver modifier ${item.name} requires a context`+ : `DTCG resolver modifier ${item.name} has no context ${JSON.stringify(selectedContext)}`+ );+ }+ resolvedDocument = mergeDtcgDocuments(+ resolvedDocument,+ resolveSources(sources, [])+ );+ }+ for (const name of Object.keys(contexts)) {+ if (modifierNames.has(name) === false) {+ return throwBuilderRuntimeError(+ "INVALID_INPUT",+ `DTCG resolver context was provided for unknown modifier ${name}`+ );+ }+ }+ return resolvedDocument;+};++const resolveDtcgGroupExtensions = (document: Record<string, unknown>) => {+ const groups = new Map<string, Record<string, unknown>>();+ const collect = (value: Record<string, unknown>, path: string[]) => {+ if (isDtcgToken(value)) {+ return;+ }+ if (path.length > 0) {+ groups.set(path.join("."), value);+ }+ for (const [name, child] of Object.entries(value)) {+ if (name.startsWith("$") === false && isRecord(child)) {+ collect(child, [...path, name]);+ }+ }+ };+ collect(document, []);++ const resolveGroup = (+ group: Record<string, unknown>,+ path: string[],+ stack: string[]+ ): Record<string, unknown> => {+ const groupReference =+ typeof group.$extends === "string"+ ? group.$extends+ : typeof group.$ref === "string" &&+ Object.keys(group).some((name) => name.startsWith("$") === false)+ ? group.$ref+ : undefined;+ let resolved = group;+ if (groupReference !== undefined) {+ const referencePath =+ groupReference.startsWith("{") && groupReference.endsWith("}")+ ? groupReference.slice(1, -1)+ : undefined;+ const target =+ referencePath === undefined+ ? resolveJsonPointer(document, groupReference)+ : groups.get(referencePath);+ if (isRecord(target) === false || isDtcgToken(target)) {+ return throwBuilderRuntimeError(+ "INVALID_INPUT",+ `DTCG group ${path.join(".")} extends missing or invalid group ${groupReference}`+ );+ }+ const targetKey = referencePath ?? groupReference;+ if (stack.includes(targetKey)) {+ return throwBuilderRuntimeError(+ "INVALID_INPUT",+ `DTCG group extension cycle: ${[...stack, targetKey].join(" -> ")}`+ );+ }+ const local = Object.fromEntries(+ Object.entries(group).filter(+ ([name]) => name !== "$extends" && name !== "$ref"+ )+ );+ resolved = mergeDtcgDocuments(+ resolveGroup(target, path, [...stack, targetKey]),+ local+ );+ }+ return Object.fromEntries(+ Object.entries(resolved).map(([name, child]) => [+ name,+ name.startsWith("$") === false && isRecord(child)+ ? resolveGroup(child, [...path, name], stack)+ : child,+ ])+ );+ };++ return resolveGroup(document, [], []);+};++export const detectDesignTokenSource = (+ document: unknown+): z.infer<typeof designTokenSourceInput> | undefined => {+ const figma = getFigmaDocumentData(document);+ if (+ figma !== undefined &&+ Object.values(figma.variables).some(+ (variable) => isRecord(variable) && isRecord(variable.valuesByMode)+ )+ ) {+ return { format: "figma", document };+ }+ if (hasDtcgToken(document)) {+ return { format: "dtcg", document };+ }+ if (+ isRecord(document) &&+ document.version === "2025.10" &&+ Array.isArray(document.resolutionOrder)+ ) {+ return { format: "dtcg", document };+ }+};++const getDtcgTokens = ({+ document: inputDocument,+ contexts,+ documents,+}: {+ document: unknown;+ contexts?: Record<string, string>;+ documents?: Record<string, unknown>;+}): NormalizedToken[] => {+ if (isRecord(inputDocument) === false) {+ return throwBuilderRuntimeError(+ "INVALID_INPUT",+ "DTCG document must be an object"+ );+ }+ const document = resolveDtcgGroupExtensions(+ resolveDtcgResolver({ document: inputDocument, contexts, documents })+ );+ type RawToken = {+ path: string;+ type?: DtcgTokenType;+ value: unknown;+ };+ const rawTokens = new Map<string, RawToken>();+ const rawTokensByAlias = new Map<string, RawToken>();+ const rawTokensByJsonPointer = new Map<string, RawToken>();+ const escapeJsonPointerSegment = (value: string) =>+ value.replaceAll("~", "~0").replaceAll("/", "~1");+ const validateName = (name: string, path: string[]) => {+ if (name.includes("{") || name.includes("}") || name.includes(".")) {+ return throwBuilderRuntimeError(+ "INVALID_INPUT",+ `DTCG token or group ${[...path, name].join(".")} has an invalid name`+ );+ }+ };+ const validateMetadata = (+ value: Record<string, unknown>,+ path: string[],+ token: boolean+ ) => {+ const location = path.join(".") || "<root>";+ const knownProperties = token ? dtcgTokenProperties : dtcgGroupProperties;+ for (const [name, metadata] of Object.entries(value)) {+ if (name.startsWith("$") === false) {+ continue;+ }+ if (knownProperties.has(name) === false) {+ return throwBuilderRuntimeError(+ "INVALID_INPUT",+ `DTCG token or group ${location} has unknown property ${name}`+ );+ }+ const valid =+ name === "$type" ||+ name === "$value" ||+ (name === "$description" && typeof metadata === "string") ||+ (name === "$deprecated" &&+ (typeof metadata === "boolean" || typeof metadata === "string")) ||+ (name === "$extensions" && isRecord(metadata)) ||+ (name === "$root" && isRecord(metadata)) ||+ ((name === "$ref" || name === "$extends" || name === "$schema") &&+ typeof metadata === "string");+ if (valid === false) {+ return throwBuilderRuntimeError(+ "INVALID_INPUT",+ `DTCG token or group ${location} has invalid ${name}`+ );+ }+ }+ };+ const visit = (+ value: Record<string, unknown>,+ path: string[],+ inheritedType: DtcgTokenType | undefined,+ pointerPath = path+ ) => {+ const parsedType =+ value.$type === undefined+ ? undefined+ : dtcgTokenTypeInput.safeParse(value.$type);+ if (parsedType !== undefined && parsedType.success === false) {+ return throwBuilderRuntimeError(+ "INVALID_INPUT",+ `DTCG token or group ${path.join(".") || "<root>"} has invalid $type ${JSON.stringify(value.$type)}`+ );+ }+ const type = parsedType?.data ?? inheritedType;+ const hasValue = "$value" in value;+ const hasReference = "$ref" in value;+ validateMetadata(value, path, hasValue || hasReference);+ if (hasValue || hasReference) {+ if (path.length === 0) {+ return throwBuilderRuntimeError(+ "INVALID_INPUT",+ "DTCG token <root> is missing a name"+ );+ }+ if (hasValue && hasReference) {+ return throwBuilderRuntimeError(+ "INVALID_INPUT",+ `DTCG token ${path.join(".")} cannot define both $value and $ref`+ );+ }+ if (hasReference && typeof value.$ref !== "string") {+ return throwBuilderRuntimeError(+ "INVALID_INPUT",+ `DTCG token ${path.join(".")} has an invalid $ref`+ );+ }+ if (+ Object.entries(value).some(+ ([name, child]) => name.startsWith("$") === false && isRecord(child)+ )+ ) {+ return throwBuilderRuntimeError(+ "INVALID_INPUT",+ `DTCG token ${path.join(".")} cannot contain child tokens or groups`+ );+ }+ const tokenPath = path.join(".");+ const token = {+ path: tokenPath,+ type,+ value: hasValue ? value.$value : { $ref: value.$ref },+ };+ rawTokens.set(tokenPath, token);+ rawTokensByAlias.set(pointerPath.join("."), token);+ const pointer = `#/${pointerPath.map(escapeJsonPointerSegment).join("/")}`;+ rawTokensByJsonPointer.set(pointer, token);+ if (hasValue) {+ rawTokensByJsonPointer.set(`${pointer}/$value`, token);+ }+ return;+ }+ for (const [name, child] of Object.entries(value)) {+ if (isRecord(child) === false) {+ continue;+ }+ if (name === "$root") {+ visit(child, path, type, [...pointerPath, name]);+ continue;+ }+ if (name.startsWith("$")) {+ continue;+ }+ validateName(name, path);+ visit(child, [...path, name], type, [...pointerPath, name]);+ }+ };+ visit(document, [], undefined);+ if (rawTokens.size === 0) {+ return throwBuilderRuntimeError(+ "INVALID_INPUT",+ "DTCG document does not contain any tokens"+ );+ }++ const getReference = (value: unknown) => {+ if (typeof value === "string") {+ const startsReference = value.startsWith("{");+ const endsReference = value.endsWith("}");+ if (startsReference === false && endsReference === false) {+ return;+ }+ const key = value.slice(1, -1);+ if (+ startsReference === false ||+ endsReference === false ||+ key.length === 0 ||+ key+ .split(".")+ .some(+ (segment) =>+ segment.length === 0 ||+ segment.includes("{") ||+ segment.includes("}") ||+ (segment.startsWith("$") && segment !== "$root")+ )+ ) {+ return throwBuilderRuntimeError(+ "INVALID_INPUT",+ `DTCG reference ${JSON.stringify(value)} is invalid`+ );+ }+ return { key, pointer: false } as const;+ }+ if (isRecord(value) && "$ref" in value) {+ if (+ typeof value.$ref !== "string" ||+ value.$ref.startsWith("#/") === false+ ) {+ return throwBuilderRuntimeError(+ "INVALID_INPUT",+ `DTCG reference ${JSON.stringify(value.$ref)} is not a local JSON Pointer`+ );+ }+ return { key: value.$ref, pointer: true } as const;+ }+ };+ let resolveToken: (+ token: RawToken,+ stack: string[]+ ) => { type: DtcgTokenType; value: unknown };+ const resolveValue = (value: unknown, stack: string[]): unknown => {+ const reference = getReference(value);+ if (reference !== undefined) {+ const targetToken = reference.pointer+ ? rawTokensByJsonPointer.get(reference.key)+ : rawTokensByAlias.get(reference.key);+ if (targetToken !== undefined) {+ if (stack.includes(targetToken.path)) {+ return throwBuilderRuntimeError(+ "INVALID_INPUT",+ `DTCG alias cycle: ${[...stack, targetToken.path].join(" -> ")}`+ );+ }+ return resolveToken(targetToken, [...stack, targetToken.path]).value;+ }+ if (reference.pointer) {+ if (stack.includes(reference.key)) {+ return throwBuilderRuntimeError(+ "INVALID_INPUT",+ `DTCG alias cycle: ${[...stack, reference.key].join(" -> ")}`+ );+ }+ const targetValue = resolveJsonPointer(document, reference.key);+ if (targetValue !== undefined) {+ return resolveValue(targetValue, [...stack, reference.key]);+ }+ }+ return throwBuilderRuntimeError(+ "INVALID_INPUT",+ reference.pointer+ ? `DTCG reference ${reference.key} does not exist`+ : `DTCG token ${stack[0]} references missing alias ${reference.key}`+ );+ }+ if (Array.isArray(value)) {+ return value.map((item) => resolveValue(item, stack));+ }+ if (isRecord(value)) {+ return Object.fromEntries(+ Object.entries(value).map(([name, item]) => [+ name,+ resolveValue(item, stack),+ ])+ );+ }+ return value;+ };+ resolveToken = (token, stack) => {+ const reference = getReference(token.value);+ const target =+ reference === undefined+ ? undefined+ : reference.pointer+ ? rawTokensByJsonPointer.get(reference.key)+ : rawTokensByAlias.get(reference.key);+ if (target === undefined) {+ const value = resolveValue(token.value, stack);+ if (token.type === undefined) {+ return throwBuilderRuntimeError(+ "INVALID_INPUT",+ `DTCG token ${token.path} is missing $type`+ );+ }+ return { type: token.type, value };+ }+ if (stack.includes(target.path)) {+ return throwBuilderRuntimeError(+ "INVALID_INPUT",+ `DTCG alias cycle: ${[...stack, target.path].join(" -> ")}`+ );+ }+ const resolved = resolveToken(target, [...stack, target.path]);+ if (token.type !== undefined && token.type !== resolved.type) {+ return throwBuilderRuntimeError(+ "INVALID_INPUT",+ `DTCG token ${token.path} has type ${token.type} but aliases ${resolved.type}`+ );+ }+ return resolved;+ };++ return Array.from(rawTokens.values(), (token) => {+ const resolved = resolveToken(token, [token.path]);+ const valueInput =+ dtcgValueInputs[resolved.type as keyof typeof dtcgValueInputs];+ if (+ valueInput !== undefined &&+ valueInput.safeParse(resolved.value).success === false+ ) {+ return throwBuilderRuntimeError(+ "INVALID_INPUT",+ `DTCG token ${token.path} has an invalid ${resolved.type} value`+ );+ }+ return { ...token, ...resolved };+ });+};++const genericFontFamilies = new Set([+ "cursive",+ "emoji",+ "fangsong",+ "fantasy",+ "math",+ "monospace",+ "sans-serif",+ "serif",+ "system-ui",+ "ui-monospace",+ "ui-rounded",+ "ui-sans-serif",+ "ui-serif",+]);++const toCssFontFamily = (value: string) =>+ genericFontFamilies.has(value) ? value : JSON.stringify(value);++const toDtcgColorCss = (color: DtcgColor) => {+ const colorSpace = toColorSpace(colorEngine.ColorSpace.get(color.colorSpace));+ const alpha = color.alpha ?? 1;+ if (color.components.every((component) => typeof component === "number")) {+ return toValue({+ type: "color",+ colorSpace,+ components: color.components as [number, number, number],+ alpha,+ });+ }+ const [c1, c2, c3] = color.components;+ const component = (value: number | "none", suffix = "") =>+ value === "none" ? value : `${value}${suffix}`;+ switch (colorSpace) {+ case "hsl":+ return `hsl(${component(c1)} ${component(c2, "%")} ${component(c3, "%")} / ${alpha})`;+ case "hwb":+ return `hwb(${component(c1)} ${component(c2, "%")} ${component(c3, "%")} / ${alpha})`;+ case "lab":+ return `lab(${component(c1, "%")} ${component(c2)} ${component(c3)} / ${alpha})`;+ case "lch":+ return `lch(${component(c1, "%")} ${component(c2)} ${component(c3)} / ${alpha})`;+ case "oklab":+ return `oklab(${component(c1)} ${component(c2)} ${component(c3)} / ${alpha})`;+ case "oklch":+ return `oklch(${component(c1)} ${component(c2)} ${component(c3)} / ${alpha})`;+ default:+ return `color(${color.colorSpace} ${component(c1)} ${component(c2)} ${component(c3)} / ${alpha})`;+ }+};++const getFigmaTokens = (+ document: unknown,+ mode?: string,+ allModes = false+): NormalizedToken[] => {+ const figma = getFigmaDocumentData(document);+ if (figma === undefined) {+ return throwBuilderRuntimeError(+ "INVALID_INPUT",+ "Figma document must contain meta.variables"+ );+ }+ const { variables, variableCollections } = figma;+ const selectValue = (+ id: string,+ variable: Record<string, unknown>,+ requestedMode: string | undefined+ ): { value: unknown; mode: string } => {+ if (isRecord(variable.valuesByMode) === false) {+ return throwBuilderRuntimeError(+ "INVALID_INPUT",+ `Figma variable ${id} is missing valuesByMode`+ );+ }+ const collectionId =+ typeof variable.variableCollectionId === "string"+ ? variable.variableCollectionId+ : undefined;+ const collection =+ collectionId === undefined ||+ isRecord(variableCollections[collectionId]) === false+ ? undefined+ : variableCollections[collectionId];+ const modes = Array.isArray(collection?.modes) ? collection.modes : [];+ const selectedMode =+ requestedMode === undefined+ ? typeof collection?.defaultModeId === "string" &&+ variable.valuesByMode[collection.defaultModeId] !== undefined+ ? collection.defaultModeId+ : Object.keys(variable.valuesByMode)[0]+ : variable.valuesByMode[requestedMode] !== undefined+ ? requestedMode+ : modes.find(+ (candidate) =>+ isRecord(candidate) && candidate.name === requestedMode+ )?.modeId;+ if (+ typeof selectedMode !== "string" ||+ variable.valuesByMode[selectedMode] === undefined+ ) {+ return throwBuilderRuntimeError(+ "INVALID_INPUT",+ `Figma variable ${typeof variable.name === "string" ? variable.name : id} has no value for mode ${JSON.stringify(requestedMode)}`+ );+ }+ const modeMetadata = modes.find(+ (candidate) => isRecord(candidate) && candidate.modeId === selectedMode+ );+ const modeName =+ isRecord(modeMetadata) && typeof modeMetadata.name === "string"+ ? modeMetadata.name+ : selectedMode;+ return {+ value: variable.valuesByMode[selectedMode],+ mode: modeName,+ };+ };+ const resolveVariable = (+ id: string,+ requestedMode: string | undefined,+ stack: string[]+ ): unknown => {+ const variable = variables[id];+ if (isRecord(variable) === false) {+ return throwBuilderRuntimeError(+ "INVALID_INPUT",+ `Figma variable references missing alias ${id}`+ );+ }+ const selected = selectValue(id, variable, requestedMode);+ const value = selected.value;+ if (isRecord(value) === false || value.type !== "VARIABLE_ALIAS") {+ return value;+ }+ if (typeof value.id !== "string") {+ return throwBuilderRuntimeError(+ "INVALID_INPUT",+ `Figma variable ${typeof variable.name === "string" ? variable.name : id} has an invalid alias`+ );+ }+ if (stack.includes(value.id)) {+ return throwBuilderRuntimeError(+ "INVALID_INPUT",+ `Figma variable alias cycle: ${[...stack, value.id].join(" -> ")}`+ );+ }+ return resolveVariable(value.id, selected.mode, [...stack, value.id]);+ };++ return Object.entries(variables).flatMap<NormalizedToken>(+ ([id, variable]) => {+ if (+ isRecord(variable) === false ||+ typeof variable.name !== "string" ||+ isRecord(variable.valuesByMode) === false+ ) {+ return throwBuilderRuntimeError(+ "INVALID_INPUT",+ `Figma variable ${id} is missing name or valuesByMode`+ );+ }+ const variableName = variable.name;+ const collectionId =+ typeof variable.variableCollectionId === "string"+ ? variable.variableCollectionId+ : undefined;+ const collection =+ collectionId === undefined ||+ isRecord(variableCollections[collectionId]) === false+ ? undefined+ : variableCollections[collectionId];+ const collectionModes = Array.isArray(collection?.modes)+ ? collection.modes+ .filter(+ (candidate): candidate is Record<string, unknown> =>+ isRecord(candidate) && typeof candidate.modeId === "string"+ )+ .map((candidate) => String(candidate.modeId))+ : [];+ const requestedModes = allModes+ ? collectionModes.length > 0+ ? collectionModes+ : Object.keys(variable.valuesByMode)+ : [mode];+ return requestedModes.map((requestedMode) => {+ const selected = selectValue(id, variable, requestedMode);+ const name = allModes+ ? `${variableName}/${selected.mode}`+ : variableName;+ return {+ path: name,+ type:+ typeof variable.resolvedType === "string"+ ? variable.resolvedType.toLowerCase()+ : "unknown",+ value: resolveVariable(id, selected.mode, [id]),+ };+ });+ }+ );+};++const toCssValue = (token: NormalizedToken) => {+ const { value } = token;+ if (token.type === "fontWeight" && typeof value === "string") {+ const weight =+ value === "book"+ ? 400+ : value === "extra-black" || value === "ultra-black"+ ? 950+ : fontWeightNames.get(value.replaceAll("-", " "));+ return String(weight ?? value);+ }+ if (+ token.type === "fontFamily" &&+ (typeof value === "string" ||+ (Array.isArray(value) && value.every((item) => typeof item === "string")))+ ) {+ const families = typeof value === "string" ? [value] : value;+ return families.map(toCssFontFamily).join(", ");+ }+ if (["string", "number", "boolean"].includes(typeof value)) {+ return String(value);+ }+ if (+ token.type === "cubicBezier" &&+ Array.isArray(value) &&+ value.length === 4 &&+ value.every((item) => typeof item === "number")+ ) {+ return `cubic-bezier(${value.join(", ")})`;+ }+ if (isRecord(value)) {+ if (typeof value.value === "number" && typeof value.unit === "string") {+ const allowedUnits =+ token.type === "dimension"+ ? ["px", "rem"]+ : token.type === "duration"+ ? ["ms", "s"]+ : undefined;+ if (+ allowedUnits !== undefined &&+ allowedUnits.includes(value.unit) === false+ ) {+ return throwBuilderRuntimeError(+ "INVALID_INPUT",+ `Token ${token.path} has invalid ${token.type} unit ${value.unit}`+ );+ }+ return `${value.value}${value.unit}`;+ }+ if (+ [value.r, value.g, value.b].every(+ (channel) => typeof channel === "number"+ )+ ) {+ const channels = [value.r, value.g, value.b].map((channel) =>+ Math.round(Number(channel) * 255)+ );+ const alpha = typeof value.a === "number" ? value.a : 1;+ return `rgb(${channels.join(" ")} / ${alpha})`;+ }+ if (+ typeof value.colorSpace === "string" &&+ Array.isArray(value.components) &&+ value.components.length === 3+ ) {+ return toDtcgColorCss(value as DtcgColor);+ }+ }+ return throwBuilderRuntimeError(+ "INVALID_INPUT",+ `Token ${token.path} has a composite value that cannot be represented as one CSS value`+ );+};++const toCssDeclarations = (token: NormalizedToken): CssDeclaration[] => {+ const value = token.value;+ const convert = (type: string, child: unknown) =>+ toCssValue({ ...token, type, value: child });+ if (token.type === "strokeStyle" && isRecord(value)) {+ return [+ {+ key: "dash-array",+ property: "stroke-dasharray",+ cssValue: (value.dashArray as unknown[])+ .map((item: unknown) => convert("dimension", item))+ .join(" "),+ },+ {+ key: "line-cap",+ property: "stroke-linecap",+ cssValue: String(value.lineCap),+ },+ ];+ }+ if (token.type === "border" && isRecord(value)) {+ if (typeof value.style === "string") {+ return [+ {+ property: "border",+ cssValue: `${convert("dimension", value.width)} ${convert("strokeStyle", value.style)} ${convert("color", value.color)}`,+ },+ ];+ }+ return [+ {+ key: "color",+ property: "border-color",+ cssValue: convert("color", value.color),+ },+ {+ key: "width",+ property: "border-width",+ cssValue: convert("dimension", value.width),+ },+ ...toCssDeclarations({+ ...token,+ type: "strokeStyle",+ value: value.style,+ }),+ ];+ }+ if (token.type === "transition" && isRecord(value)) {+ return [+ {+ property: "transition",+ cssValue: `${convert("duration", value.duration)} ${convert("cubicBezier", value.timingFunction)} ${convert("duration", value.delay)}`,+ },+ ];+ }+ if (token.type === "shadow") {+ const shadows = Array.isArray(value) ? value : [value];+ return [+ {+ property: "box-shadow",+ cssValue: shadows+ .map((shadow) => {+ if (isRecord(shadow) === false) {+ return "";+ }+ return [+ shadow.inset === true ? "inset" : undefined,+ convert("dimension", shadow.offsetX),+ convert("dimension", shadow.offsetY),+ convert("dimension", shadow.blur),+ convert("dimension", shadow.spread),+ convert("color", shadow.color),+ ]+ .filter((part) => part !== undefined)+ .join(" ");+ })+ .join(", "),+ },+ ];+ }+ if (token.type === "gradient" && Array.isArray(value)) {+ return [+ {+ property: "background-image",+ cssValue: `linear-gradient(90deg, ${value+ .map((stop) => {+ if (isRecord(stop) === false) {+ return "";+ }+ return `${convert("color", stop.color)} ${Number(stop.position) * 100}%`;+ })+ .join(", ")})`,+ },+ ];+ }+ if (token.type === "typography" && isRecord(value)) {+ return [+ {+ key: "font-family",+ property: "font-family",+ cssValue: convert("fontFamily", value.fontFamily),+ },+ {+ key: "font-size",+ property: "font-size",+ cssValue: convert("dimension", value.fontSize),+ },+ {+ key: "font-weight",+ property: "font-weight",+ cssValue: convert("fontWeight", value.fontWeight),+ },+ {+ key: "letter-spacing",+ property: "letter-spacing",+ cssValue: convert("dimension", value.letterSpacing),+ },+ {+ key: "line-height",+ property: "line-height",+ cssValue: convert("number", value.lineHeight),+ },+ ];+ }+ return [{ cssValue: toCssValue(token) }];+};++const toImportedTokenName = (name: string) => {+ const normalized = name+ .trim()+ .toLowerCase()+ .replace(/[^a-z0-9_-]/g, "-")+ .replace(/-+/g, "-")+ .replace(/^-|-$/g, "");+ if (normalized.length === 0) {+ return throwBuilderRuntimeError(+ "INVALID_INPUT",+ `Token name ${JSON.stringify(name)} cannot form an imported token name`+ );+ }+ return normalized;+};++const toCssVariableName = (name: string) => `--${toImportedTokenName(name)}`;++export const normalizeDesignTokenImport = (+ input: z.infer<typeof designTokenImportInput>+): NormalizedImportEntry[] => {+ const tokens =+ input.source.format === "dtcg"+ ? getDtcgTokens(input.source)+ : getFigmaTokens(+ input.source.document,+ input.source.mode,+ input.source.allModes+ );+ const prefix = input.prefix?.trim();+ return tokens.flatMap<NormalizedImportEntry>((token) => {+ const target =+ input.mapping?.[token.type] ??+ input.defaultTarget ??+ ({ target: "css-variable" } as const);+ const sourceName =+ prefix === undefined ? token.path : `${prefix}.${token.path}`;+ const { value: _value, ...summary } = token;+ const declarations = toCssDeclarations(token);+ if (target.target === "css-variable") {+ return declarations.map((declaration) => {+ const outputName = toCssVariableName(+ declaration.key === undefined+ ? sourceName+ : `${sourceName}.${declaration.key}`+ );+ return withDeclarationSummary({+ ...summary,+ target: target.target,+ outputName,+ declarations: [+ { property: outputName, cssValue: declaration.cssValue },+ ],+ });+ });+ }+ const normalizedDeclarations = declarations.map((declaration) => ({+ property:+ declarations.length === 1+ ? target.property+ : (declaration.property ?? target.property),+ cssValue: declaration.cssValue,+ }));+ return [+ withDeclarationSummary({+ ...summary,+ target: target.target,+ outputName: toImportedTokenName(sourceName),+ declarations: normalizedDeclarations,+ }),+ ];+ });+};++const getImportState = (state: ImportState, breakpoint: string | undefined) => {+ if (+ state.styles === undefined ||+ state.styleSources === undefined ||+ state.styleSourceSelections === undefined+ ) {+ return throwBuilderRuntimeError(+ "BAD_REQUEST",+ "Style namespaces are missing"+ );+ }+ const cssVariableTarget = getCssVariableRootTarget(state, breakpoint);+ const existingCssVariables = new Set<string>(+ Array.from(state.styles.values())+ .filter(+ (style) =>+ style.styleSourceId === cssVariableTarget.styleSourceId &&+ style.breakpointId === cssVariableTarget.breakpointId &&+ style.property.startsWith("--")+ )+ .map((style) => style.property)+ );+ const existingTokens = new Map(+ Array.from(state.styleSources.values())+ .filter((source) => source.type === "token")+ .map((source) => [source.name, source])+ );+ const propertiesByStyleSource = new Map<string, Set<string>>();+ for (const style of state.styles.values()) {+ if (+ style.breakpointId !== cssVariableTarget.breakpointId ||+ style.state !== undefined+ ) {+ continue;+ }+ const properties =+ propertiesByStyleSource.get(style.styleSourceId) ?? new Set<string>();+ properties.add(style.property);+ propertiesByStyleSource.set(style.styleSourceId, properties);+ }+ return {+ cssVariableTarget,+ existingCssVariables,+ existingTokens,+ propertiesByStyleSource,+ };+};++const isMatchingImportEntry = ({+ state,+ entry,+ importState,+}: {+ state: ImportState;+ entry: NormalizedImportEntry;+ importState: ReturnType<typeof getImportState>;+}) => {+ const { cssVariableTarget, existingTokens, propertiesByStyleSource } =+ importState;+ const styleSourceId =+ entry.target === "css-variable"+ ? cssVariableTarget.styleSourceId+ : existingTokens.get(entry.outputName)?.id;+ if (styleSourceId === undefined) {+ return false;+ }+ const declarationsMatch = entry.declarations.every((declaration) => {+ const style = state.styles?.get(+ getStyleDeclKey({+ styleSourceId,+ breakpointId: cssVariableTarget.breakpointId as string,+ property: declaration.property as StyleProperty,+ state: undefined,+ })+ );+ return style !== undefined && toValue(style.value) === declaration.cssValue;+ });+ if (entry.target === "css-variable") {+ return declarationsMatch;+ }+ return (+ declarationsMatch &&+ propertiesByStyleSource.get(styleSourceId)?.size ===+ entry.declarations.length+ );+};++const renameImportEntry = (+ entry: NormalizedImportEntry,+ outputName: string+): NormalizedImportEntry => {+ if (entry.target === "design-token") {+ return { ...entry, outputName };+ }+ return withDeclarationSummary({+ ...entry,+ outputName,+ declarations: entry.declarations.map((declaration) => ({+ ...declaration,+ property: outputName,+ })),+ });+};++const createImportPlan = (+ state: ImportState,+ input: z.infer<typeof designTokenImportInput>,+ importState: ReturnType<typeof getImportState>+): ImportPlanEntry[] => {+ const { existingCssVariables, existingTokens } = importState;+ const normalized = normalizeDesignTokenImport(input);+ const seen = new Set<string>();+ const occupiedNames = {+ "css-variable": new Set(existingCssVariables),+ "design-token": new Set(existingTokens.keys()),+ };+ for (const token of normalized) {+ const key = `${token.target}:${token.outputName}`;+ if (seen.has(key)) {+ return throwBuilderRuntimeError(+ "INVALID_INPUT",+ `Multiple source tokens map to ${token.outputName}`+ );+ }+ seen.add(key);+ occupiedNames[token.target].add(token.outputName);+ }+ return normalized.map((token) => {+ const exists =+ token.target === "css-variable"+ ? existingCssVariables.has(token.outputName)+ : existingTokens.has(token.outputName);+ const conflict =+ exists &&+ isMatchingImportEntry({+ state,+ entry: token,+ importState,+ }) === false;+ if (exists && conflict === false) {+ return { ...token, action: "skip" as const, conflict };+ }+ if (conflict && input.collision === "rename") {+ const outputName = getUniqueNameWithSuffix(+ token.outputName,+ occupiedNames[token.target]+ );+ occupiedNames[token.target].add(outputName);+ return {+ ...renameImportEntry(token, outputName),+ action: "create" as const,+ conflict,+ };+ }+ return {+ ...token,+ action: exists+ ? input.collision === "overwrite"+ ? "overwrite"+ : "skip"+ : "create",+ conflict,+ };+ });+};++export const planDesignTokenImport = (+ state: ImportState,+ input: z.infer<typeof designTokenImportInput>+) => createImportPlan(state, input, getImportState(state, input.breakpoint));++const toDesignTokenStyles = (+ entry: ImportPlanEntry,+ breakpoint: string | undefined+) =>+ entry.declarations.map(({ property, cssValue }) => ({+ property,+ value: { type: "unparsed" as const, value: cssValue },+ breakpoint,+ }));++export const importDesignTokens = (+ state: ImportState,+ input: z.infer<typeof designTokenImportInput>,+ context: BuilderRuntimeContext+) => {+ const importState = getImportState(state, input.breakpoint);+ const plan = createImportPlan(state, input, importState);+ const { existingTokens } = importState;+ const accumulator = createRuntimeMutationAccumulator(state);+ const cssVariables = Object.fromEntries(+ plan+ .filter(+ (entry) => entry.target === "css-variable" && entry.action !== "skip"+ )+ .map((entry) => [entry.outputName, entry.declarations[0].cssValue])+ );+ if (Object.keys(cssVariables).length > 0) {+ accumulator.stage(+ defineCssVariables(+ accumulator.state,+ {+ vars: cssVariables,+ overwrite: input.collision === "overwrite",+ breakpoint: input.breakpoint,+ },+ context+ )+ );+ }+ const created = plan.filter(+ (entry) => entry.target === "design-token" && entry.action === "create"+ );+ if (created.length > 0) {+ accumulator.stage(+ createDesignTokens(+ accumulator.state,+ {+ tokens: created.map((entry) => ({+ name: entry.outputName,+ declarations: toDesignTokenStyles(entry, input.breakpoint),+ })),+ },+ context+ )+ );+ }+ for (const entry of plan) {+ if (entry.target !== "design-token" || entry.action !== "overwrite") {+ continue;+ }+ const designTokenId = existingTokens.get(entry.outputName)?.id;+ if (designTokenId !== undefined) {+ accumulator.stage(+ updateDesignTokenStyles(accumulator.state, {+ designTokenId,+ updates: toDesignTokenStyles(entry, input.breakpoint),+ })+ );+ }+ }+ const counts = { create: 0, overwrite: 0, skip: 0 };+ for (const entry of plan) {+ counts[entry.action] += 1;+ }+ return accumulator.complete({ plan, counts });+};diff --git a/packages/project-build/src/runtime/output-schemas.ts b/packages/project-build/src/runtime/output-schemas.tsindex 8be9e4a9fb..11b54d21a3 100644--- a/packages/project-build/src/runtime/output-schemas.ts+++ b/packages/project-build/src/runtime/output-schemas.ts@@ -23,6 +23,7 @@ import {fragmentInsertResult,} from "./component-insert-contract";import { expressionWarningSchema } from "./expression-validation";+import { designTokenImportPlanEntrySchema } from "./design-token-import";const looseObject = <Shape extends z.ZodRawShape>(shape: Shape) =>z.looseObject(shape);@@ -410,6 +411,8 @@ export const runtimeOutputSchemas = {warnings: expressionWarnings.optional(),}),"instances.insertFragment": fragmentInsertResult,+ "slots.attach": looseObject({ slotId: id, fragmentId: id }),+ "slots.extract": looseObject({ slotId: id, fragmentId: id, instanceId: id }),"instances.move": instanceIdsResult,"instances.reparent": looseObject({instanceSelector: stringArray.optional(),@@ -489,6 +492,14 @@ export const runtimeOutputSchemas = {"styles.replaceValues": styleKeysResult,"designTokens.list": looseObject({ tokens: z.array(token), ...outputPage }),"designTokens.create": looseObject({ tokenIds: stringArray }),+ "designTokens.import": looseObject({+ plan: z.array(designTokenImportPlanEntrySchema),+ counts: looseObject({+ create: z.number().int(),+ overwrite: z.number().int(),+ skip: z.number().int(),+ }),+ }),"designTokens.createAttached": looseObject({ tokenIds: stringArray }),"designTokens.updateStyles": looseObject({designTokenId: id,diff --git a/packages/project-build/src/runtime/registry.test.ts b/packages/project-build/src/runtime/registry.test.tsindex 0e13b071a9..3d745b7e1c 100644--- a/packages/project-build/src/runtime/registry.test.ts+++ b/packages/project-build/src/runtime/registry.test.ts@@ -2097,6 +2097,8 @@ describe("builder runtime registry", () => {["instances.insertComponent", { parentInstanceId: "body" }],["instances.insertCollection", { parentInstanceId: "body" }],["instances.insertFragment", { parentInstanceId: "body" }],+ ["slots.attach", {}],+ ["slots.extract", {}],["instances.move", { moves: {} }],["instances.reparent", {}],["instances.fillGrid", {}],@@ -2123,6 +2125,7 @@ describe("builder runtime registry", () => {["styles.deleteSelectedDeclarations", { deletions: {} }],["styles.replaceValues", {}],["designTokens.create", { tokens: {} }],+ ["designTokens.import", {}],["designTokens.createAttached", { tokens: {}, instanceIds: [] }],["designTokens.updateStyles", { designTokenId: "token", updates: {} }],["designTokens.deleteStyles", { designTokenId: "token", deletions: {} }],diff --git a/packages/project-build/src/runtime/registry.ts b/packages/project-build/src/runtime/registry.tsindex 65b1c6d914..a5e3cf3644 100644--- a/packages/project-build/src/runtime/registry.ts+++ b/packages/project-build/src/runtime/registry.ts@@ -27,6 +27,8 @@ import * as projectSettings from "./project-settings";import * as props from "./props";import * as runtimeUi from "./runtime-ui";import * as search from "./search";+import * as slot from "./slot";+import * as designTokenImport from "./design-token-import";import * as audit from "./audit";import * as styles from "./styles";import { getZodValidationIssues, throwBuilderValidationError } from "./errors";@@ -950,6 +952,26 @@ export const builderRuntimeOperations = [({ state, input, context }) =>components.insertFragment(state, input, context)),+ runtimeOperation(+ "slots.attach",+ api("attach-slot", "attachSharedSlot"),+ mutationContract({+ readNamespaces: ["instances", "props"],+ writeNamespaces: ["instances"],+ }),+ slot.attachSharedSlotInput,+ ({ state, input, context }) => slot.attachSharedSlot(state, input, context)+ ),+ runtimeOperation(+ "slots.extract",+ api("extract-slot", "extractSharedSlot"),+ mutationContract({+ readNamespaces: ["instances", "props"],+ writeNamespaces: ["instances"],+ }),+ slot.extractSharedSlotInput,+ ({ state, input, context }) => slot.extractSharedSlot(state, input, context)+ ),runtimeOperation("instances.move",api("move-instance", "moveInstance"),@@ -1427,6 +1449,17 @@ export const builderRuntimeOperations = [({ state, input, context }) =>styles.createDesignTokens(state, input, context)),+ runtimeOperation(+ "designTokens.import",+ api("import-design-tokens", "importDesignTokens"),+ mutationContract({+ readNamespaces: ["pages", ...styleNamespaces, "breakpoints"],+ writeNamespaces: ["styles", "styleSources", "styleSourceSelections"],+ }),+ designTokenImport.designTokenImportInput,+ ({ state, input, context }) =>+ designTokenImport.importDesignTokens(state, input, context)+ ),runtimeOperation("designTokens.createAttached",api("create-attached-design-token", "createAttachedDesignTokens"),diff --git a/packages/project-build/src/runtime/slot.test.ts b/packages/project-build/src/runtime/slot.test.tsindex 7de67f8a34..f8bad2f59a 100644--- a/packages/project-build/src/runtime/slot.test.ts+++ b/packages/project-build/src/runtime/slot.test.ts@@ -1,6 +1,9 @@import { describe, expect, test } from "vitest";import type { Instance } from "@webstudio-is/sdk";+import { applyBuilderPatchTransactions } from "../state/patch";import {+ attachSharedSlot,+ extractSharedSlot,findClosestSlot,getDirectSharedSlotChildBoundary,getSharedSlotBoundary,@@ -40,6 +43,166 @@ const expectSlotsShareFragment = (};describe("runtime slot utilities", () => {+ test("attaches another occurrence of a shared slot", () => {+ const instances = new Map([+ ["body", instance("body", "Body", [{ type: "id", value: "source" }])],+ [+ "source",+ instance("source", "Slot", [{ type: "id", value: "fragment" }]),+ ],+ [+ "fragment",+ instance("fragment", "Fragment", [{ type: "id", value: "heading" }]),+ ],+ ["heading", instance("heading", "Heading")],+ ["target", instance("target", "Box")],+ ]);+ const mutation = attachSharedSlot(+ { instances, props: new Map() },+ { sourceSlotId: "source", parentInstanceId: "target" },+ { createId: () => "attached" }+ );+ const updated = applyBuilderPatchTransactions(+ { instances, props: new Map() },+ [{ id: "attach-slot", payload: mutation.payload }]+ ).state.instances;++ expect(mutation.result).toEqual({+ slotId: "attached",+ fragmentId: "fragment",+ });+ expect(updated?.get("attached")?.children).toEqual([+ { type: "id", value: "fragment" },+ ]);+ expect(updated?.get("target")?.children).toEqual([+ { type: "id", value: "attached" },+ ]);+ });++ test("attaches a shared slot inside another slot content fragment", () => {+ const instances = new Map([+ ["body", instance("body", "Body")],+ [+ "source",+ instance("source", "Slot", [{ type: "id", value: "source-fragment" }]),+ ],+ [+ "source-fragment",+ instance("source-fragment", "Fragment", [+ { type: "id", value: "heading" },+ ]),+ ],+ ["heading", instance("heading", "Heading")],+ [+ "target",+ instance("target", "Slot", [{ type: "id", value: "target-fragment" }]),+ ],+ ["target-fragment", instance("target-fragment", "Fragment")],+ ]);+ const mutation = attachSharedSlot(+ { instances, props: new Map() },+ { sourceSlotId: "source", parentInstanceId: "target" },+ { createId: () => "nested" }+ );+ const updated = applyBuilderPatchTransactions(+ { instances, props: new Map() },+ [{ id: "attach-nested-slot", payload: mutation.payload }]+ ).state.instances;++ expect(updated?.get("target")?.children).toEqual([+ { type: "id", value: "target-fragment" },+ ]);+ expect(updated?.get("target-fragment")?.children).toEqual([+ { type: "id", value: "nested" },+ ]);+ expect(updated?.get("nested")?.children).toEqual([+ { type: "id", value: "source-fragment" },+ ]);+ });++ test("normalizes an empty target slot before nesting a shared slot", () => {+ const instances = new Map([+ [+ "source",+ instance("source", "Slot", [{ type: "id", value: "source-fragment" }]),+ ],+ ["source-fragment", instance("source-fragment", "Fragment")],+ ["target", instance("target", "Slot")],+ ]);+ const ids = ["nested", "target-fragment"];+ const mutation = attachSharedSlot(+ { instances, props: new Map() },+ { sourceSlotId: "source", parentInstanceId: "target" },+ { createId: () => ids.shift() ?? "unexpected" }+ );+ const updated = applyBuilderPatchTransactions(+ { instances, props: new Map() },+ [{ id: "attach-empty-slot", payload: mutation.payload }]+ ).state.instances;++ expect(updated?.get("target")?.children).toEqual([+ { type: "id", value: "target-fragment" },+ ]);+ expect(updated?.get("target-fragment")?.children).toEqual([+ { type: "id", value: "nested" },+ ]);+ });++ test("extracts a subtree into canonical shared slot content", () => {+ const instances = new Map([+ ["body", instance("body", "Body", [{ type: "id", value: "section" }])],+ [+ "section",+ instance("section", "Box", [{ type: "id", value: "heading" }]),+ ],+ ["heading", instance("heading", "Heading")],+ ]);+ const ids = ["slot", "fragment"];+ const mutation = extractSharedSlot(+ { instances, props: new Map() },+ { instanceSelector: ["section", "body"], label: "Shared section" },+ { createId: () => ids.shift() ?? "unexpected" }+ );+ const updated = applyBuilderPatchTransactions(+ { instances, props: new Map() },+ [{ id: "extract-slot", payload: mutation.payload }]+ ).state.instances;++ expect(updated?.get("body")?.children).toEqual([+ { type: "id", value: "slot" },+ ]);+ expect(updated?.get("slot")).toMatchObject({+ component: "Slot",+ label: "Shared section",+ children: [{ type: "id", value: "fragment" }],+ });+ expect(updated?.get("fragment")?.children).toEqual([+ { type: "id", value: "section" },+ ]);+ });++ test("rejects attaching shared content inside itself", () => {+ const instances = new Map([+ [+ "source",+ instance("source", "Slot", [{ type: "id", value: "fragment" }]),+ ],+ [+ "fragment",+ instance("fragment", "Fragment", [{ type: "id", value: "section" }]),+ ],+ ["section", instance("section", "Box")],+ ]);++ expect(() =>+ attachSharedSlot(+ { instances, props: new Map() },+ { sourceSlotId: "source", parentInstanceId: "section" },+ { createId: () => "attached" }+ )+ ).toThrow("Shared Slot cannot be attached inside its own content");+ });+test("finds closest slot and shared slot boundary", () => {const slot = instance("slot", "Slot");expect(diff --git a/packages/project-build/src/runtime/slot.ts b/packages/project-build/src/runtime/slot.tsindex 5eb475e4c7..a5c4e1183b 100644--- a/packages/project-build/src/runtime/slot.ts+++ b/packages/project-build/src/runtime/slot.ts@@ -1,5 +1,17 @@-import type { Instance, Instances, WebstudioData } from "@webstudio-is/sdk";-import { findAvailableVariables } from "./data";+import {+ findTreeInstanceIds,+ portalComponent,+ type Instance,+ type Instances,+ type WebstudioData,+} from "@webstudio-is/sdk";+import { componentMetas } from "@webstudio-is/sdk-components-registry/metas";+import { z } from "zod";+import type { BuilderState } from "../state/builder-state";+import { findAvailableVariables, produceWebstudioDataMutation } from "./data";+import { isTreeSatisfyingContentModel } from "./content-model";+import type { BuilderRuntimeContext } from "./context";+import { throwBuilderRuntimeError } from "./errors";import {extractWebstudioFragment,insertWebstudioFragmentCopy,@@ -9,6 +21,7 @@ import type {InstancePathItem,InstanceSelector,} from "./instance-path";+import { createRuntimeMutation } from "./mutation";export type { InstancePath, InstancePathItem } from "./instance-path";@@ -17,6 +30,41 @@ type SlotDropTarget = {position: number | "end";};+const insertIndexInput = z.number().int().nonnegative();++const createSharedSlot = ({+ id,+ fragmentId,+ label,+}: {+ id: Instance["id"];+ fragmentId: Instance["id"];+ label?: string;+}) => {+ const instance: Instance = {+ type: "instance",+ id,+ component: portalComponent,+ children: [{ type: "id", value: fragmentId }],+ };+ if (label !== undefined) {+ instance.label = label;+ }+ return instance;+};++export const attachSharedSlotInput = z.object({+ sourceSlotId: z.string().min(1),+ parentInstanceId: z.string().min(1),+ insertIndex: insertIndexInput.optional(),+ label: z.string().min(1).optional(),+});++export const extractSharedSlotInput = z.object({+ instanceSelector: z.array(z.string().min(1)).min(2),+ label: z.string().min(1).optional(),+});+export type SharedSlotBoundary = {slotIndex: number;fragmentItem: InstancePathItem;@@ -88,6 +136,191 @@ export const getSlotFragmentId = (slot: undefined | Instance) => {return slot.children[0].value;};+const getRequiredSlotState = (+ state: Pick<BuilderState, "instances" | "props">+) => {+ if (state.instances === undefined) {+ return throwBuilderRuntimeError(+ "BAD_REQUEST",+ "Instances namespace is missing"+ );+ }+ if (state.props === undefined) {+ return throwBuilderRuntimeError(+ "BAD_REQUEST",+ "Props namespace is missing"+ );+ }+ return { instances: state.instances, props: state.props };+};++const assertValidSlotPlacement = ({+ instances,+ props,+ instanceSelector,+}: {+ instances: Instances;+ props: NonNullable<BuilderState["props"]>;+ instanceSelector: InstanceSelector;+}) => {+ if (+ isTreeSatisfyingContentModel({+ instances,+ props,+ metas: componentMetas,+ instanceSelector,+ }) === false+ ) {+ return throwBuilderRuntimeError(+ "BAD_REQUEST",+ "Shared Slot violates the target content model"+ );+ }+};++export const attachSharedSlot = (+ state: Pick<BuilderState, "instances" | "props">,+ input: z.infer<typeof attachSharedSlotInput>,+ context: BuilderRuntimeContext+) => {+ const before = getRequiredSlotState(state);+ const slotId = context.createId();+ let fragmentId: Instance["id"] | undefined;+ const { payload } = produceWebstudioDataMutation(before, (draft) => {+ const sourceSlot = draft.instances.get(input.sourceSlotId);+ if (sourceSlot?.component !== portalComponent) {+ return throwBuilderRuntimeError("NOT_FOUND", "Source Slot not found");+ }+ getSlotFragmentDropTargetMutable(+ draft.instances,+ { parentSelector: [sourceSlot.id], position: "end" },+ context.createId+ );+ fragmentId = getSlotFragmentId(sourceSlot);+ if (fragmentId === undefined) {+ return throwBuilderRuntimeError(+ "BAD_REQUEST",+ "Source Slot has no shareable content"+ );+ }+ const target = getSlotFragmentDropTargetMutable(+ draft.instances,+ {+ parentSelector: [input.parentInstanceId],+ position: "end",+ },+ context.createId,+ new Set([fragmentId])+ );+ const parentSelector = target?.parentSelector ?? [input.parentInstanceId];+ const parent = draft.instances.get(parentSelector[0]);+ if (parent === undefined) {+ return throwBuilderRuntimeError("NOT_FOUND", "Target parent not found");+ }+ if (findTreeInstanceIds(draft.instances, fragmentId).has(parent.id)) {+ return throwBuilderRuntimeError(+ "BAD_REQUEST",+ "Shared Slot cannot be attached inside its own content"+ );+ }+ const slot = createSharedSlot({+ id: slotId,+ fragmentId,+ label: input.label ?? sourceSlot.label,+ });+ draft.instances.set(slot.id, slot);+ if (+ input.insertIndex !== undefined &&+ input.insertIndex > parent.children.length+ ) {+ return throwBuilderRuntimeError(+ "BAD_REQUEST",+ "Insert index is outside parent children"+ );+ }+ parent.children.splice(input.insertIndex ?? parent.children.length, 0, {+ type: "id",+ value: slot.id,+ });+ assertValidSlotPlacement({+ instances: draft.instances,+ props: draft.props,+ instanceSelector: [slot.id, ...parentSelector],+ });+ });+ const sharedFragmentId =+ fragmentId ??+ throwBuilderRuntimeError(+ "BAD_REQUEST",+ "Source Slot has no shareable content"+ );+ return createRuntimeMutation({+ payload,+ result: { slotId, fragmentId: sharedFragmentId },+ invalidatesNamespaces: ["instances"],+ });+};++export const extractSharedSlot = (+ state: Pick<BuilderState, "instances" | "props">,+ input: z.infer<typeof extractSharedSlotInput>,+ context: BuilderRuntimeContext+) => {+ const before = getRequiredSlotState(state);+ const slotId = context.createId();+ const fragmentId = context.createId();+ const { payload } = produceWebstudioDataMutation(before, (draft) => {+ const [instanceId, parentId] = input.instanceSelector;+ const selected = draft.instances.get(instanceId);+ const parent = draft.instances.get(parentId);+ if (selected === undefined || parent === undefined) {+ return throwBuilderRuntimeError(+ "NOT_FOUND",+ "Instance or parent not found"+ );+ }+ if (selected.component === portalComponent) {+ return throwBuilderRuntimeError(+ "BAD_REQUEST",+ "Instance is already a Slot"+ );+ }+ const childIndex = parent.children.findIndex(+ (child) => child.type === "id" && child.value === selected.id+ );+ if (childIndex === -1) {+ return throwBuilderRuntimeError(+ "BAD_REQUEST",+ "Instance selector does not identify a direct parent"+ );+ }+ const fragment: Instance = {+ type: "instance",+ id: fragmentId,+ component: "Fragment",+ children: [{ type: "id", value: selected.id }],+ };+ const slot = createSharedSlot({+ id: slotId,+ fragmentId: fragment.id,+ label: input.label ?? selected.label,+ });+ draft.instances.set(fragment.id, fragment);+ draft.instances.set(slot.id, slot);+ parent.children[childIndex] = { type: "id", value: slot.id };+ assertValidSlotPlacement({+ instances: draft.instances,+ props: draft.props,+ instanceSelector: [slot.id, ...input.instanceSelector.slice(1)],+ });+ });+ return createRuntimeMutation({+ payload,+ result: { slotId, fragmentId, instanceId: input.instanceSelector[0] },+ invalidatesNamespaces: ["instances"],+ });+};+const getInstancePathFromInstances = (instanceSelector: InstanceSelector,instances: Instances@@ -166,7 +399,8 @@ export const findClosestSlot = (export const getSlotFragmentDropTargetMutable = (instances: Instances,dropTarget: SlotDropTarget,- createId: () => string+ createId: () => string,+ excludedFragmentIds: ReadonlySet<Instance["id"]> = new Set()): SlotDropTarget | undefined => {const [parentId] = dropTarget.parentSelector;const instance = instances.get(parentId);@@ -185,6 +419,7 @@ export const getSlotFragmentDropTargetMutable = (const fragment = instances.get(candidate.children[0].value);if (fragment?.component === "Fragment" &&+ excludedFragmentIds.has(fragment.id) === false &&areInstanceChildrenEqual(fragment.children, legacyChildren)) {return fragment.id;diff --git a/packages/project-build/src/runtime/style-copy.ts b/packages/project-build/src/runtime/style-copy.tsindex 1b8215d412..ef2252494e 100644--- a/packages/project-build/src/runtime/style-copy.ts+++ b/packages/project-build/src/runtime/style-copy.ts@@ -12,6 +12,7 @@ import {type StyleSources,type Styles,} from "@webstudio-is/sdk";+import { getUniqueNameWithSuffix } from "./style-utils";export type ConflictResolution = "ours" | "theirs" | "merge";@@ -282,21 +283,12 @@ export const insertStyleSources = ({continue;} else {// Default: add counter suffix- let maxCounter = 0;- const baseNamePattern = new RegExp(- `^${styleSource.name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}(?:-(\\d+))?$`+ const newName = getUniqueNameWithSuffix(+ styleSource.name,+ Array.from(updatedStyleSources.values())+ .filter((source) => source.type === "token")+ .map((source) => source.name));- for (const existing of updatedStyleSources.values()) {- if (existing.type !== "token") {- continue;- }- const match = existing.name.match(baseNamePattern);- if (match) {- const counter = match[1] ? parseInt(match[1], 10) : 0;- maxCounter = Math.max(maxCounter, counter);- }- }- const newName = `${styleSource.name}-${maxCounter + 1}`;const newStyleSource = {...styleSource,id: newTokenId,diff --git a/packages/project-build/src/runtime/style-utils.test.ts b/packages/project-build/src/runtime/style-utils.test.tsindex babfb50314..74053c9d1b 100644--- a/packages/project-build/src/runtime/style-utils.test.ts+++ b/packages/project-build/src/runtime/style-utils.test.ts@@ -12,12 +12,26 @@ import {collectFontFamiliesFromStyleValue,cloneStyles,createStyleClonePayload,+ getUniqueNameWithSuffix,isAutoGridPlacement,resetGridChildPlacement,serializeStyleDeclarations,traverseStyleValue,} from "./style-utils";+test("creates a unique name after the highest numeric suffix", () => {+ expect(+ getUniqueNameWithSuffix("color", [+ "color",+ "color-1",+ "color-3",+ "color-01",+ "color-copy",+ "background-color-4",+ ])+ ).toBe("color-4");+});+const createStyleDecl = (styleSourceId: string,breakpointId: string,diff --git a/packages/project-build/src/runtime/style-utils.ts b/packages/project-build/src/runtime/style-utils.tsindex 4a19a0e6ce..e638620c4e 100644--- a/packages/project-build/src/runtime/style-utils.ts+++ b/packages/project-build/src/runtime/style-utils.ts@@ -11,6 +11,32 @@ import type {import { getStyleDeclKey } from "@webstudio-is/sdk";import type { BuilderPatchChange } from "../contracts/patch";+export const getUniqueNameWithSuffix = (+ name: string,+ existingNames: Iterable<string>+) => {+ const prefix = `${name}-`;+ let maxCounter = 0;+ for (const existingName of existingNames) {+ if (existingName === name) {+ continue;+ }+ if (existingName.startsWith(prefix) === false) {+ continue;+ }+ const suffix = existingName.slice(prefix.length);+ const counter = Number(suffix);+ if (+ Number.isInteger(counter) &&+ counter > 0 &&+ String(counter) === suffix+ ) {+ maxCounter = Math.max(maxCounter, counter);+ }+ }+ return `${name}-${maxCounter + 1}`;+};+export const traverseStyleValue = (value: StyleValue,callback: (value: StyleValue) => voiddiff --git a/packages/project-build/src/runtime/styles.test.ts b/packages/project-build/src/runtime/styles.test.tsindex 554c08490c..fbdf66a629 100644--- a/packages/project-build/src/runtime/styles.test.ts+++ b/packages/project-build/src/runtime/styles.test.ts@@ -812,6 +812,28 @@ describe("css variable usage", () => {]);});+ test("scopes css variable conflicts to the root source and breakpoint", () => {+ const result = createCssVariableRootDefinePayload({+ rootInstanceId: "body",+ vars: { "--color": "blue" },+ styleSources: new Map([+ ["root-local", { id: "root-local", type: "local" }],+ ]),+ styleSourceSelections: [{ instanceId: "body", values: ["root-local"] }],+ styles: [+ createCssVariableStyleDecl("component-local", "--color", "red"),+ {+ ...createCssVariableStyleDecl("root-local", "--color", "green"),+ breakpointId: "mobile",+ },+ ],+ createId: createCssVariableId,+ });++ expect(result.conflicts).toEqual([]);+ expect(result.styleKeys).toEqual(["root-local:base:--color:"]);+ });+test("creates css variable delete patches and reports references", () => {const styles = [createCssVariableStyleDecl("local", "--color", "red"),diff --git a/packages/project-build/src/runtime/styles.ts b/packages/project-build/src/runtime/styles.tsindex 5045a26a34..3e80d716b3 100644--- a/packages/project-build/src/runtime/styles.ts+++ b/packages/project-build/src/runtime/styles.ts@@ -261,6 +261,36 @@ const withValidatedBreakpoint = <Input extends { breakpoint?: string }>(: input.breakpoint,});+export const getCssVariableRootTarget = (+ state: Pick<+ BuilderState,+ "breakpoints" | "pages" | "styleSources" | "styleSourceSelections"+ >,+ breakpoint?: string+) => {+ const rootInstanceId =+ state.pages === undefined+ ? undefined+ : getHomePageRootInstanceId(state.pages);+ if (rootInstanceId === undefined) {+ return throwBuilderRuntimeError("NOT_FOUND", "Home page not found");+ }+ return {+ rootInstanceId,+ breakpointId: withValidatedBreakpoint({ breakpoint }, state.breakpoints)+ .breakpoint,+ styleSourceId:+ state.styleSources === undefined ||+ state.styleSourceSelections === undefined+ ? undefined+ : getLocalStyleSourceId({+ styleSources: state.styleSources,+ styleSourceSelection:+ state.styleSourceSelections.get(rootInstanceId),+ }),+ };+};+const styleStateInput = z.string().superRefine((state, context) => {const result = validateSelector(state);if (result.success === false) {@@ -416,6 +446,7 @@ export const cssVariableValueInput = z.union([z.string(), styleValue]);export const cssVariableDefineInput = z.object({vars: z.record(z.string(), cssVariableValueInput),overwrite: z.boolean().optional(),+ breakpoint: z.string().optional(),});export const cssVariableDeleteInput = z.object({@@ -692,7 +723,10 @@ const createCssVariableDefinePayload = ({for (const [property, value] of Object.entries(vars)) {const existingDeclarations = stylesList.filter(- (declaration) => declaration.property === property+ (declaration) =>+ declaration.styleSourceId === rootStyleSourceId &&+ declaration.breakpointId === breakpointId &&+ declaration.property === property);if (existingDeclarations.length > 0 && overwrite !== true) {conflicts.push(property);@@ -3403,25 +3437,19 @@ export const defineCssVariables = (input: z.infer<typeof cssVariableDefineInput>,context: { createId: () => string }) => {- const rootInstanceId =- state.pages === undefined- ? undefined- : getHomePageRootInstanceId(state.pages);- if (rootInstanceId === undefined) {- return throwBuilderRuntimeError("NOT_FOUND", "Home page not found");- }+ const target = getCssVariableRootTarget(state, input.breakpoint);for (const [property] of Object.entries(input.vars)) {assertCssVariableName(property);}const styleState = getRequiredStyleState(state);const resultPayload = createCssVariableRootDefinePayload({- rootInstanceId,+ rootInstanceId: target.rootInstanceId,vars: input.vars,styleSources: styleState.styleSources,styleSourceSelections: styleState.styleSourceSelections.values(),styles: styleState.styles.values(),overwrite: input.overwrite,- breakpointId: getBaseBreakpointId(state.breakpoints),+ breakpointId: target.breakpointId,createId: context.createId,});if (resultPayload.missingRootStyleSource) {diff --git a/packages/project-build/src/schema.ts b/packages/project-build/src/schema.tsindex ca1789c90c..e6ebcaa4ce 100644--- a/packages/project-build/src/schema.ts+++ b/packages/project-build/src/schema.ts@@ -64,3 +64,18 @@ const serializedBuildShape = {// API packages compose this schema; they should not copy or maintain it.export const serializedBuild: z.ZodObject<typeof serializedBuildShape> =z.object(serializedBuildShape);++const serializedBuilderState = serializedBuild+ .omit({+ id: true,+ projectId: true,+ version: true,+ createdAt: true,+ updatedAt: true,+ deployment: true,+ })+ .partial();++export const serializedRestorePointState = serializedBuilderState.extend({+ marketplaceProduct: marketplaceProduct.nullable().optional(),+});diff --git a/packages/project-build/src/state/patch.test.ts b/packages/project-build/src/state/patch.test.tsindex 5e2e78a179..c44af60855 100644--- a/packages/project-build/src/state/patch.test.ts+++ b/packages/project-build/src/state/patch.test.ts@@ -9,6 +9,34 @@ import {MissingBuilderStateNamespaceError,} from "./patch";+test("root-replaces an optional marketplace product from missing state", () => {+ const state: BuilderState = {};+ const marketplaceProduct = {+ category: "sectionTemplates" as const,+ name: "Example section",+ thumbnailAssetId: "thumbnail",+ author: "Webstudio",+ email: "[email protected]",+ website: "",+ issues: "",+ description: "Example marketplace product",+ };++ expect(+ applyBuilderPatchTransactions(state, [+ {+ id: "restore-marketplace-product",+ payload: [+ {+ namespace: "marketplaceProduct",+ patches: [{ op: "replace", path: [], value: marketplaceProduct }],+ },+ ],+ },+ ]).state.marketplaceProduct+ ).toEqual(marketplaceProduct);+});+test("applies namespace patches", () => {const nextProps = applyBuilderNamespacePatches<Props>(new Map(build.props), [{@@ -168,6 +196,27 @@ test("fails when replacing a missing patch target", () => {).toThrow('Cannot replace missing patch path "missing"');});+test("replaces a complete namespace at its root", () => {+ const replacement = new Map([+ [+ "replacement",+ {+ id: "replacement",+ instanceId: "instance-root",+ name: "Title",+ type: "string" as const,+ value: "Restored",+ },+ ],+ ]);++ expect(+ applyBuilderNamespacePatches<Props>(new Map(build.props), [+ { op: "replace", path: [], value: replacement },+ ])+ ).toEqual(replacement);+});+test("applies transactions without mutating the input state object", () => {const state: BuilderState = {props: new Map(build.props),diff --git a/packages/project-build/src/state/patch.ts b/packages/project-build/src/state/patch.tsindex 9b782f67f1..142b714bc3 100644--- a/packages/project-build/src/state/patch.ts+++ b/packages/project-build/src/state/patch.ts@@ -172,6 +172,9 @@ const assertReplacePatchTargetsExistingPath = (if (patch.op !== "replace") {return;}+ if (patch.path.length === 0) {+ return;+ }const { parent, key } = getPatchParent(namespaceData, patch);if (hasPathValue(parent, key) === false) {throw Error(`Cannot replace missing patch path "${String(key)}"`);@@ -226,6 +229,18 @@ export const applyBuilderPatchTransactions = (}const namespaceState = nextState[change.namespace];if (namespaceState === undefined) {+ const patch = change.patches[0];+ if (+ change.namespace === "marketplaceProduct" &&+ change.patches.length === 1 &&+ patch?.op === "replace" &&+ patch.path.length === 0+ ) {+ (nextState as Record<string, unknown>).marketplaceProduct =+ structuredClone(patch.value);+ changedNamespaces.add(change.namespace);+ continue;+ }throw new MissingBuilderStateNamespaceError(change.namespace);}(nextState as Record<string, unknown>)[change.namespace] =diff --git a/packages/project/src/db/build-patch-core.ts b/packages/project/src/db/build-patch-core.tsindex 14cbfa4c63..b617d9b25f 100644--- a/packages/project/src/db/build-patch-core.ts+++ b/packages/project/src/db/build-patch-core.ts@@ -424,11 +424,13 @@ export const createBuildPatchUpdate = async ({update.styles = serializeStyles(stylesData);}- if (buildData.marketplaceProduct) {- const marketplaceProductData = buildData.marketplaceProduct;- update.marketplaceProduct = serializeConfig<MarketplaceProduct>(- marketplaceProduct.parse(marketplaceProductData)- );+ if (Object.hasOwn(buildData, "marketplaceProduct")) {+ update.marketplaceProduct =+ buildData.marketplaceProduct === undefined+ ? serializeConfig({})+ : serializeConfig<MarketplaceProduct>(+ marketplaceProduct.parse(buildData.marketplaceProduct)+ );}if (buildData.projectSettings) {diff --git a/packages/project/src/db/build-patch.test.ts b/packages/project/src/db/build-patch.test.tsindex 8db0712f27..eb4746edac 100644--- a/packages/project/src/db/build-patch.test.ts+++ b/packages/project/src/db/build-patch.test.ts@@ -335,6 +335,42 @@ describe("patchBuild", () => {}});+ test("persists an explicitly cleared marketplace product", async () => {+ const result = await createBuildPatchUpdate({+ build: {+ ...buildRow,+ marketplaceProduct: JSON.stringify({+ category: "sectionTemplates",+ name: "Example section",+ thumbnailAssetId: "thumbnail",+ author: "Webstudio",+ email: "[email protected]",+ website: "",+ issues: "",+ description: "Example marketplace product",+ }),+ },+ clientVersion: 3,+ transactions: [+ transaction({+ payload: [+ {+ namespace: "marketplaceProduct",+ patches: [{ op: "replace", path: [], value: undefined }],+ },+ ],+ }),+ ],+ });++ expect(result.status).toBe("ok");+ if (result.status === "ok") {+ expect(JSON.parse(result.update?.marketplaceProduct ?? "null")).toEqual(+ {}+ );+ }+ });+test("validates only touched props while preserving untouched props", async () => {const buildWithInvalidUntouchedProp = {...buildRow,diff --git a/packages/protocol/src/builder-api/operation-docs.ts b/packages/protocol/src/builder-api/operation-docs.tsindex 34dcbce1ad..ecc8f2f07d 100644--- a/packages/protocol/src/builder-api/operation-docs.ts+++ b/packages/protocol/src/builder-api/operation-docs.ts@@ -332,6 +332,22 @@ const curatedPublicApiOperationDocumentation = ['MCP tool: insert-fragment {"parentInstanceId":"parent-id","fragment":"<ws.element ws:tag=\\"section\\" />"}',],},+ {+ command: "attach-slot",+ description:+ "Attach another Slot occurrence that references the same shared content; use this for headers, footers, and other content edited once across pages",+ examples: [+ 'MCP tool: attach-slot {"sourceSlotId":"slot-id","parentInstanceId":"parent-id"}',+ ],+ },+ {+ command: "extract-slot",+ description:+ "Convert an existing instance subtree into shared Slot content without cloning it",+ examples: [+ 'MCP tool: extract-slot {"instanceSelector":["instance-id","parent-id","root-id"],"label":"Site header"}',+ ],+ },{command: "move-instance",description: "Move element instances to another parent or position",@@ -451,6 +467,15 @@ const curatedPublicApiOperationDocumentation = [requiredOptions: ["input", "json"],examples: ["webstudio create-design-token --input tokens.json --json"],},+ {+ command: "import-design-tokens",+ description:+ "Import DTCG and Figma Variables as design tokens or CSS variables; mapping keys are token types such as color or dimension, not token paths",+ requiredOptions: ["input", "json"],+ examples: [+ "webstudio import-design-tokens --input brand-tokens.json --json",+ ],+ },{command: "update-design-token-styles",description: "Create or update declarations on a reusable style token",diff --git a/packages/protocol/src/schema.test.ts b/packages/protocol/src/schema.test.tsindex bdd7eac2da..660a4a1fa1 100644--- a/packages/protocol/src/schema.test.ts+++ b/packages/protocol/src/schema.test.ts@@ -15,6 +15,7 @@ import {buildPatchTransaction,getPublicBuildIncludes,publicBuildIncludes,+ projectSessionRestorePointPath,} from "./schema";import { createPublishedProjectBundleFixture } from "./fixtures";@@ -22,6 +23,7 @@ describe("project bundle contract", () => {test("defines staged upload transport details", () => {expect(stagedUploadPath).toBe("/rest/staged-upload");expect(stagedUploadProjectIdHeader).toBe("x-webstudio-project-id");+ expect(projectSessionRestorePointPath).toBe("build.restorePoint");});test("validates asset file names", () => {diff --git a/packages/protocol/src/schema.ts b/packages/protocol/src/schema.tsindex a40fb397dd..b4c2f37e06 100644--- a/packages/protocol/src/schema.ts+++ b/packages/protocol/src/schema.ts@@ -3,6 +3,7 @@ import { builderNamespaces } from "@webstudio-is/project-build/contracts";import {builderPatchSchema as internalBuilderPatchSchema,builderPatchTransactionSchema as internalBuilderPatchTransactionSchema,+ restorePointPatchTransactionSchema as internalRestorePointPatchTransactionSchema,} from "@webstudio-is/project-build/contracts";import { serializedBuild } from "@webstudio-is/project-build/contracts";import { wsAuthConfig } from "@webstudio-is/wsauth/schema";@@ -17,6 +18,7 @@ import { createContractVersion } from "./contract-version";export const maxProjectBundleSize = 20 * 1024 * 1024;export const stagedUploadPath = "/rest/staged-upload";export const stagedUploadProjectIdHeader = "x-webstudio-project-id";+export const projectSessionRestorePointPath = "build.restorePoint";const assetFileName = z.string()@@ -147,6 +149,11 @@ export const buildPatch: z.ZodType<BuildPatch, unknown> =export const buildPatchTransaction: z.ZodType<BuildPatchTransaction, unknown> =internalBuilderPatchTransactionSchema;+export const restorePointPatchTransaction: z.ZodType<+ BuildPatchTransaction,+ unknown+> = internalRestorePointPatchTransactionSchema;+export const bundleVersion = createContractVersion(publishedProjectBundle, [wsAuthConfig,]);