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
fix: Bring back import command (#5841)
Oleg Isonene1dec8c45696
diff --git a/.gitmodules b/.gitmodulesindex 76cab76f46..6251a291e9 100644--- a/.gitmodules+++ b/.gitmodules@@ -1,4 +1,4 @@[submodule "packages/sdk-components-animation/private-src"]path = packages/sdk-components-animation/private-src- url = [email protected]:webstudio-is/sdk-components-animation.git+ url = https://github.com/webstudio-is/sdk-components-animation.gitbranch = maindiff --git a/packages/cli/src/asset-files.test.ts b/packages/cli/src/asset-files.test.tsindex 1e3d6871bf..330220cddf 100644--- a/packages/cli/src/asset-files.test.ts+++ b/packages/cli/src/asset-files.test.ts@@ -10,7 +10,11 @@ import {import { join } from "node:path";import { tmpdir } from "node:os";import type { Asset } from "@webstudio-is/sdk";-import { getLocalAssetPath, materializeAssetFile } from "./asset-files";+import {+ createLocalAssetDataReader,+ getLocalAssetPath,+ materializeAssetFile,+} from "./asset-files";const originalCwd = process.cwd();let tempDir: string;@@ -46,6 +50,18 @@ test("rejects asset paths outside the asset directory", () => {);});+test("creates a local asset data reader", async () => {+ await mkdir(".webstudio/assets", { recursive: true });+ await writeFile(".webstudio/assets/image.png", "asset", "utf8");++ const readAssetData = createLocalAssetDataReader(readFile);+ const data = await readAssetData({ name: "image.png" });++ expect(+ Buffer.from(data.buffer, data.byteOffset, data.byteLength).toString()+ ).toBe("asset");+});+test("materializes asset files from the synced asset cache before fetching", async () => {await mkdir(".webstudio/assets", { recursive: true });await writeFile(".webstudio/assets/image.png", "synced", "utf8");diff --git a/packages/cli/src/asset-files.ts b/packages/cli/src/asset-files.tsindex 8cd90c46be..a5e7dbc60e 100644--- a/packages/cli/src/asset-files.ts+++ b/packages/cli/src/asset-files.ts@@ -54,6 +54,13 @@ export const getLocalAssetPath = (throw new Error(`Asset path escapes ${assetsDirectory}: ${assetName}`);};+export const createLocalAssetDataReader =+ (readFile: (path: string) => Promise<unknown>, assetsDirectory?: string) =>+ async (asset: { name: string }) =>+ (await readFile(+ getLocalAssetPath(asset.name, assetsDirectory)+ )) as ArrayBufferView<ArrayBuffer>;+const downloadUrlToFile = async (url: string, filePath: string) => {const tempFilePath = `${filePath}.tmp`;diff --git a/packages/cli/src/cli.test.ts b/packages/cli/src/cli.test.tsindex a9109ba9b7..3d518d21ae 100644--- a/packages/cli/src/cli.test.ts+++ b/packages/cli/src/cli.test.ts@@ -92,6 +92,7 @@ describe("registerCommands", () => {expect.arrayContaining(["preview","screenshot <url>",+ "import","permissions","publish","domains",@@ -143,6 +144,7 @@ describe("registerCommands", () => {test("keeps grouped subcommands out of top-level help", async () => {const rootHelp = await getHelpOutput(["--help"]);+ expect(rootHelp).toContain("webstudio import");expect(rootHelp).toContain("webstudio publish");expect(rootHelp).toContain("webstudio domains");expect(rootHelp).not.toContain("webstudio publish deploy");diff --git a/packages/cli/src/cli.ts b/packages/cli/src/cli.tsindex bc1c745413..62f474576c 100644--- a/packages/cli/src/cli.ts+++ b/packages/cli/src/cli.ts@@ -4,6 +4,7 @@ import { GLOBAL_CONFIG_FILE } from "./config";import { createFileIfNotExists } from "./fs-utils";import { link, linkOptions } from "./commands/link";import { sync, syncOptions } from "./commands/sync";+import { importOptions, importProject } from "./commands/import";import { build, buildOptions } from "./commands/build";import { man, manOptions } from "./commands/man";import { mcp, mcpOptions } from "./commands/mcp";@@ -75,6 +76,12 @@ export const registerCommands = (cmd: CommonYargsArgv) => {);cmd.command(["link"], "Link the project with the cloud", linkOptions, link);cmd.command(["sync"], "Sync your project", syncOptions, sync);+ cmd.command(+ ["import"],+ "Import the synced project bundle into another project",+ importOptions,+ importProject+ );cmd.command(["preview"],"Run the generated project dev server for visual verification",diff --git a/packages/cli/src/commands/api-command-docs.test.ts b/packages/cli/src/commands/api-command-docs.test.tsindex 52a42e2310..9e96487431 100644--- a/packages/cli/src/commands/api-command-docs.test.ts+++ b/packages/cli/src/commands/api-command-docs.test.ts@@ -95,6 +95,7 @@ test("documents every MCP session and vision tool in use-case scenarios", () =>"meta.index","meta.guide","meta.get_more_tools",+ "import","status","refresh","reset-session",diff --git a/packages/cli/src/commands/api-command-metadata.test.ts b/packages/cli/src/commands/api-command-metadata.test.tsindex 6810f0f406..f2bce96029 100644--- a/packages/cli/src/commands/api-command-metadata.test.ts+++ b/packages/cli/src/commands/api-command-metadata.test.ts@@ -58,6 +58,7 @@ test("describes root CLI commands once for help-oriented docs", () => {"init","link","sync",+ "import","build","preview","screenshot",diff --git a/packages/cli/src/commands/api-command-metadata.ts b/packages/cli/src/commands/api-command-metadata.tsindex 2e59d3c4fc..68f94c5a54 100644--- a/packages/cli/src/commands/api-command-metadata.ts+++ b/packages/cli/src/commands/api-command-metadata.ts@@ -54,6 +54,12 @@ export const topLevelCliCommandMetadata = ["Download the configured project bundle and asset files into .webstudio",examples: ["webstudio sync"],},+ {+ command: "import",+ description:+ "Import the synced .webstudio/data.json project bundle into a destination project",+ examples: ["webstudio import --to <destination-share-link>"],+ },{command: "build",description: "Build the synced project with the selected template",diff --git a/packages/cli/src/commands/api-command.ts b/packages/cli/src/commands/api-command.tsindex ca277f8b48..d1605c6e95 100644--- a/packages/cli/src/commands/api-command.ts+++ b/packages/cli/src/commands/api-command.ts@@ -2,7 +2,7 @@ import { readFile } from "node:fs/promises";import * as httpClient from "@webstudio-is/http-client";import { isFileExists } from "../fs-utils";import { HandledCliError } from "../errors";-import { getLocalAssetPath, LOCAL_ASSETS_DIR } from "../asset-files";+import { createLocalAssetDataReader, LOCAL_ASSETS_DIR } from "../asset-files";import { createCliProjectSession } from "../project-session";import { getStableErrorCode } from "../error-codes";import { printJson } from "../json-output";@@ -1465,13 +1465,6 @@ const readInputArray = async <Value>(options: ApiCommandOptions) => (await readJsonArray(dependencies, options.input, "--input")) as Value;-const readAssetData =- (dependencies: ApiCommandDependencies, assetsDirectory?: string) =>- async (asset: { name: string }) =>- (await dependencies.readFile(- getLocalAssetPath(asset.name, assetsDirectory)- )) as unknown as ArrayBufferView<ArrayBuffer>;-const parseVariableValue = (type: ApiCommandOptions["valueType"],value: string | undefined@@ -2534,7 +2527,10 @@ const apiCommandHandlers = {"upload-asset": async (options, connection, dependencies) => {const input = {asset: await readInputObject<UploadAssetInput>(dependencies, options),- readAssetData: readAssetData(dependencies, options.assetsDir),+ readAssetData: createLocalAssetDataReader(+ dependencies.readFile,+ options.assetsDir+ ),};return runProjectSessionCommand("upload-asset",@@ -2546,7 +2542,10 @@ const apiCommandHandlers = {"upload-assets": async (options, connection, dependencies) => {const input = {assets: await readInputArray<UploadAssetsInput>(dependencies, options),- readAssetData: readAssetData(dependencies, options.assetsDir),+ readAssetData: createLocalAssetDataReader(+ dependencies.readFile,+ options.assetsDir+ ),};return runProjectSessionCommand("upload-assets",diff --git a/packages/cli/src/commands/import.test.ts b/packages/cli/src/commands/import.test.tsnew file mode 100644index 0000000000..3516c9f338--- /dev/null+++ b/packages/cli/src/commands/import.test.ts@@ -0,0 +1,268 @@+import { afterEach, beforeEach, expect, test, vi } from "vitest";+import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";+import { join } from "node:path";+import { tmpdir } from "node:os";+import makeCLI from "yargs";+import { bundleVersion } from "@webstudio-is/protocol";+import {+ createImageAssetFixture,+ createPublishedProjectBundleFixture,+} from "@webstudio-is/protocol/fixtures";+import { createAuthConfigContentFromBundle } from "../auth-config";+import { loadJSONFile } from "../fs-utils";+import { importOptions, importProject } from "./import";+import type { CommonYargsArgv } from "./yargs-types";++const originalCwd = process.cwd();+let tempDir: string;+const destinationProjectId = "090e6e14-ae50-4b2e-bd22-71733cec05bb";+const destinationShareLink = `https://p-${destinationProjectId}-dot-example.com/?authToken=token-1`;+const imageAsset = createImageAssetFixture({+ name: "image.png",+ size: 5,+ meta: { width: 1, height: 1 },+});+const log = {+ info: vi.fn(),+};+const indicator = {+ start: vi.fn(),+ message: vi.fn(),+ stop: vi.fn(),+};+const importProjectBundleWithAssets = vi.fn();+const readFile = vi.fn();+const promptText = vi.fn();+const dependencies = {+ importProjectBundleWithAssets,+ loadJSONFile,+ readFile,+ text: promptText,+ isInteractive: false,+ log,+ spinner: () => indicator,+};++const createSyncedData = (data = {}) =>+ createPublishedProjectBundleFixture({+ assets: [],+ projectDomain: "example.com",+ ...data,+ });++const writeSyncedData = async (data = {}) => {+ const syncedData = createSyncedData(data);+ await writeFile(".webstudio/data.json", JSON.stringify(syncedData), "utf8");+ return syncedData;+};++beforeEach(async () => {+ tempDir = await mkdtemp(join(tmpdir(), "webstudio-import-"));+ process.chdir(tempDir);+ await mkdir(".webstudio", { recursive: true });+ importProjectBundleWithAssets.mockResolvedValue({ version: 1 });+ readFile.mockResolvedValue(Buffer.from("asset data"));+ promptText.mockResolvedValue(destinationShareLink);+ importProjectBundleWithAssets.mockClear();+ readFile.mockClear();+ promptText.mockClear();+ log.info.mockClear();+ indicator.start.mockClear();+ indicator.message.mockClear();+ indicator.stop.mockClear();+});++afterEach(async () => {+ process.chdir(originalCwd);+ await rm(tempDir, { recursive: true, force: true });+ vi.clearAllMocks();+});++test("imports local synced data into destination project", async () => {+ const syncedData = await writeSyncedData();++ await importProject({ to: destinationShareLink }, dependencies);++ expect(importProjectBundleWithAssets).toHaveBeenCalledWith(+ expect.objectContaining({+ projectId: destinationProjectId,+ authToken: "token-1",+ origin: "https://example.com",+ data: syncedData,+ ignoreVersionCheck: undefined,+ readAssetData: expect.any(Function),+ headers: expect.objectContaining({ "x-webstudio-client": "cli" }),+ })+ );+ expect(indicator.message).toHaveBeenCalledWith(+ "Reading .webstudio/data.json"+ );+ expect(log.info).toHaveBeenCalledWith("Read .webstudio/data.json");+ expect(indicator.stop).toHaveBeenCalledWith("Project imported successfully");+});++test("uses configured asset directory when reading local asset files", async () => {+ await writeSyncedData({ assets: [imageAsset] });++ await importProject(+ { to: destinationShareLink, assetsDir: "custom-assets" },+ dependencies+ );++ const call = importProjectBundleWithAssets.mock.calls[0]?.[0];+ await call.readAssetData(imageAsset);++ expect(readFile).toHaveBeenCalledWith(+ expect.stringContaining("custom-assets/image.png")+ );+});++test("passes skip-assets to http client", async () => {+ await writeSyncedData({ assets: [imageAsset] });++ await importProject(+ { to: destinationShareLink, skipAssets: true },+ dependencies+ );++ expect(importProjectBundleWithAssets).toHaveBeenCalledWith(+ expect.objectContaining({+ skipAssets: true,+ })+ );+ expect(+ importProjectBundleWithAssets.mock.calls[0]?.[0].readAssetData+ ).toBeUndefined();+ expect(log.info).toHaveBeenCalledWith("Skipped asset upload and asset rows");+});++test("prompts for destination share link when running interactively", async () => {+ await writeSyncedData();++ await importProject(+ {},+ {+ ...dependencies,+ isInteractive: true,+ }+ );++ expect(promptText).toHaveBeenCalledWith({+ message: "Please paste a destination share link with build permissions",+ validate: expect.any(Function),+ });+ expect(importProjectBundleWithAssets).toHaveBeenCalledWith(+ expect.objectContaining({+ projectId: destinationProjectId,+ })+ );+});++test("stops when destination share link is missing in non-interactive mode", async () => {+ const loadJSONFile = vi.fn();++ await expect(+ importProject(+ {},+ {+ ...dependencies,+ loadJSONFile,+ }+ )+ ).rejects.toThrow("Handled CLI error");++ expect(loadJSONFile).not.toHaveBeenCalled();+ expect(importProjectBundleWithAssets).not.toHaveBeenCalled();+ expect(indicator.stop).toHaveBeenCalledWith(+ "Please specify a destination share link with --to",+ 2+ );+});++test("requires destination share link before running non-interactive command", async () => {+ const parser = importOptions(+ makeCLI([])+ .exitProcess(false)+ .fail((message, error) => {+ throw error ?? new Error(message);+ }) as CommonYargsArgv+ );++ expect(() => parser.parse([])).toThrow(+ "Please specify a destination share link with --to"+ );+});++test("stops with sync instruction when local data is missing", async () => {+ await expect(+ importProject({ to: destinationShareLink }, dependencies)+ ).rejects.toThrow("Handled CLI error");++ expect(importProjectBundleWithAssets).not.toHaveBeenCalled();+ expect(indicator.stop).toHaveBeenCalledWith(+ "Project bundle is missing. Please run webstudio sync before importing.",+ 2+ );+});++test("stops before API request when local data is from old format", async () => {+ await writeSyncedData({ bundleVersion: undefined });++ await expect(+ importProject({ to: destinationShareLink }, dependencies)+ ).rejects.toThrow("Handled CLI error");++ expect(importProjectBundleWithAssets).not.toHaveBeenCalled();+ expect(indicator.stop).toHaveBeenCalledWith(+ `Project bundle format is incompatible. Expected version ${bundleVersion}, received missing. Sync with a compatible API/CLI version and retry, or pass --ignore-version-check if you know the source and target data formats are compatible.`,+ 2+ );+});++test("validates exported auth config before importing", async () => {+ const syncedData = await writeSyncedData();+ await writeFile(+ ".webstudio/auth.json",+ createAuthConfigContentFromBundle(syncedData),+ "utf8"+ );++ await importProject({ to: destinationShareLink }, dependencies);++ expect(importProjectBundleWithAssets).toHaveBeenCalledWith(+ expect.objectContaining({+ data: syncedData,+ })+ );+ expect(log.info).toHaveBeenCalledWith("Read .webstudio/auth.json");+});++test("stops before API request when destination link is invalid", async () => {+ await writeSyncedData();++ await expect(+ importProject({ to: "https://example.com" }, dependencies)+ ).rejects.toThrow("Handled CLI error");++ expect(importProjectBundleWithAssets).not.toHaveBeenCalled();+ expect(indicator.stop).toHaveBeenCalledWith(+ "Destination share link is invalid.",+ 2+ );+});++test("forwards import errors through the spinner", async () => {+ await writeSyncedData();+ importProjectBundleWithAssets.mockRejectedValue(+ new Error("Version mismatch")+ );++ await expect(+ importProject({ to: destinationShareLink }, dependencies)+ ).rejects.toThrow("Handled CLI error");++ expect(indicator.stop).toHaveBeenCalledWith(+ expect.stringContaining("Version mismatch"),+ 2+ );+});diff --git a/packages/cli/src/commands/import.ts b/packages/cli/src/commands/import.tsnew file mode 100644index 0000000000..bbc3b50972--- /dev/null+++ b/packages/cli/src/commands/import.ts@@ -0,0 +1,247 @@+import { cwd, stdin, stdout } from "node:process";+import { join } from "node:path";+import { readFile } from "node:fs/promises";+import { cancel, isCancel, log, spinner, text } from "@clack/prompts";+import {+ bundleVersion,+ getBundleVersion,+ getBundleVersionMismatchMessage,+ publishedProjectBundle,+} from "@webstudio-is/protocol";+import { importProjectBundleWithAssets } from "@webstudio-is/http-client";+import { LOCAL_DATA_FILE } from "../config";+import { createLocalAssetDataReader, LOCAL_ASSETS_DIR } from "../asset-files";+import { loadJSONFile } from "../fs-utils";+import { HandledCliError } from "../errors";+import { LOCAL_AUTH_FILE, validateAuthConfigFile } from "../auth-config";+import { apiCompatibilityHeaders, stopSpinnerWithError } from "./api";+import { parseShareLink, validateShareLink } from "./link";+import { formatZodIssues } from "../zod-utils";+import type {+ CommonYargsArgv,+ StrictYargsOptionsToInterface,+} from "./yargs-types";++type ImportProjectDependencies = {+ importProjectBundleWithAssets: typeof importProjectBundleWithAssets;+ loadJSONFile: typeof loadJSONFile;+ readFile: typeof readFile;+ text: typeof text;+ isInteractive: boolean;+ log: Pick<typeof log, "info">;+ spinner: typeof spinner;+};++const isInteractiveTerminal = () =>+ stdin.isTTY === true && stdout.isTTY === true;++const defaultDependencies: ImportProjectDependencies = {+ importProjectBundleWithAssets,+ loadJSONFile,+ readFile,+ text,+ isInteractive: isInteractiveTerminal(),+ log,+ spinner,+};++const missingDestinationMessage =+ "Please specify a destination share link with --to";+const missingProjectBundleMessage =+ "Project bundle is missing. Please run webstudio sync before importing.";+const invalidProjectBundleMessage =+ "Project bundle is invalid. Please run webstudio sync before importing.";+const invalidAuthConfigMessage =+ "Project bundle auth config is invalid. Please run webstudio build before importing.";+const invalidDestinationMessage = "Destination share link is invalid.";++export const importOptions = (yargs: CommonYargsArgv) =>+ yargs+ .option("to", {+ type: "string",+ describe: "Share link with build permissions to import synced data into",+ })+ .option("assets-dir", {+ type: "string",+ default: LOCAL_ASSETS_DIR,+ describe:+ "Directory containing local asset files referenced by the bundle",+ })+ .option("ignore-version-check", {+ type: "boolean",+ describe:+ "Import data without a compatible data version; import may fail if source and target API data formats differ",+ })+ .option("skip-assets", {+ type: "boolean",+ describe:+ "Import project data without uploading or importing asset files; referenced assets may be missing in the target project",+ })+ .check((options) => {+ if (options.to === undefined && isInteractiveTerminal() === false) {+ return missingDestinationMessage;+ }+ return true;+ });++type ImportOptions = Pick<+ Partial<StrictYargsOptionsToInterface<typeof importOptions>>,+ "assetsDir" | "ignoreVersionCheck" | "skipAssets"+> & {+ to?: string;+};++export const importProject = async (+ options: ImportOptions,+ dependencies = defaultDependencies+) => {+ const importing = dependencies.spinner();+ importing.start("Importing project bundle");++ if (options.to === undefined && dependencies.isInteractive === false) {+ importing.stop(missingDestinationMessage, 2);+ throw new HandledCliError();+ }++ importing.message(`Reading ${LOCAL_DATA_FILE}`);++ let data: unknown | null;+ try {+ data = await dependencies.loadJSONFile<unknown>(+ join(cwd(), LOCAL_DATA_FILE)+ );+ } catch {+ importing.stop(invalidProjectBundleMessage, 2);+ throw new HandledCliError();+ }+ if (data === null) {+ importing.stop(missingProjectBundleMessage, 2);+ throw new HandledCliError();+ }++ const localBundleVersion = getBundleVersion(data);+ if (+ localBundleVersion !== bundleVersion &&+ options.ignoreVersionCheck !== true+ ) {+ importing.stop(+ getBundleVersionMismatchMessage({+ ignoreVersionCheckHint:+ "pass --ignore-version-check if you know the source and target data formats are compatible",+ receivedVersion: localBundleVersion,+ }),+ 2+ );+ throw new HandledCliError();+ }++ const parsedData = publishedProjectBundle.safeParse(data);+ if (parsedData.success === false) {+ importing.stop(+ `${invalidProjectBundleMessage} Invalid fields: ${formatZodIssues(+ parsedData.error.issues+ )}`,+ 2+ );+ throw new HandledCliError();+ }+ const importData = parsedData.data;++ importing.message(`Reading ${LOCAL_AUTH_FILE}`);+ try {+ if (+ await validateAuthConfigFile({+ data: importData,+ filePath: join(cwd(), LOCAL_AUTH_FILE),+ })+ ) {+ dependencies.log.info(`Read ${LOCAL_AUTH_FILE}`);+ }+ } catch (error) {+ importing.stop(+ error instanceof Error+ ? `${invalidAuthConfigMessage} ${error.message}`+ : invalidAuthConfigMessage,+ 2+ );+ throw new HandledCliError();+ }++ let destinationShareLink = options.to;+ if (+ destinationShareLink === undefined &&+ dependencies.isInteractive === true+ ) {+ importing.stop(`Read ${LOCAL_DATA_FILE}`);+ const shareLink = await dependencies.text({+ message: "Please paste a destination share link with build permissions",+ validate: validateShareLink,+ });+ if (isCancel(shareLink)) {+ cancel("Project import is cancelled");+ throw new HandledCliError();+ }+ destinationShareLink = shareLink;+ importing.start("Importing project bundle");+ }+ if (destinationShareLink === undefined) {+ importing.stop(missingDestinationMessage, 2);+ throw new HandledCliError();+ }++ let destination;+ try {+ destination = parseShareLink(destinationShareLink);+ } catch {+ importing.stop(invalidDestinationMessage, 2);+ throw new HandledCliError();+ }++ dependencies.log.info(`Read ${LOCAL_DATA_FILE}`);+ dependencies.log.info(`Destination project: ${destination.projectId}`);+ dependencies.log.info(`Destination origin: ${destination.origin}`);++ const destinationRequest = {+ projectId: destination.projectId,+ authToken: destination.token,+ origin: destination.origin,+ headers: apiCompatibilityHeaders,+ };++ try {+ await dependencies.importProjectBundleWithAssets({+ ...destinationRequest,+ data: importData,+ ignoreVersionCheck: options.ignoreVersionCheck,+ ...(options.skipAssets === true+ ? { skipAssets: true }+ : {+ readAssetData: createLocalAssetDataReader(+ dependencies.readFile,+ options.assetsDir+ ),+ }),+ onUploadAssets: (assets) =>+ importing.message(`Uploading ${assets.length} assets`),+ onMissingAssets: (assets) =>+ importing.message(`Re-uploading ${assets.length} missing assets`),+ onImportAttempt: () =>+ importing.message(+ `Waiting for API response while importing into ${destination.projectId}`+ ),+ });+ } catch (error) {+ stopSpinnerWithError(+ importing,+ error,+ "Unable to import project bundle",+ "import"+ );+ throw new HandledCliError();+ }++ if (options.skipAssets === true) {+ dependencies.log.info("Skipped asset upload and asset rows");+ }+ importing.stop("Project imported successfully");+};diff --git a/packages/cli/src/commands/man.test.ts b/packages/cli/src/commands/man.test.tsindex 6a68149f7e..81cac70c87 100644--- a/packages/cli/src/commands/man.test.ts+++ b/packages/cli/src/commands/man.test.ts@@ -82,6 +82,7 @@ test("prints api manual as json", () => {"init","link","sync",+ "import","build","preview","screenshot",@@ -126,6 +127,7 @@ test("prints api manual as json", () => {output.useCaseScenarios.map(({ useCase }: { useCase: string }) => useCase)).toEqual(["Link/configure one project",+ "Import synced project bundle into another project","Identify current token","Check token permissions","Inspect project/build/version",diff --git a/packages/cli/src/commands/mcp.ts b/packages/cli/src/commands/mcp.tsindex 803e839f3d..e7a2202255 100644--- a/packages/cli/src/commands/mcp.ts+++ b/packages/cli/src/commands/mcp.ts@@ -1,12 +1,16 @@import { stdin, stdout } from "node:process";+import { readFile } from "node:fs/promises";import {connectProjectSessionMcpServer,createMcpStdioTransport,} from "@webstudio-is/project-build/mcp";import { diffPngFiles } from "@webstudio-is/project-build/visual/screenshot-diff";import { publicApiOperations } from "@webstudio-is/protocol";+import { importProjectBundleWithAssets } from "@webstudio-is/http-client";import { resolveApiConnection } from "../api-connection";import { getStableErrorCode } from "../error-codes";+import { isHandledCliError } from "../errors";+import { loadJSONFile } from "../fs-utils";import { createCliProjectSession } from "../project-session";import { executeProjectSessionApiOperation } from "../project-session-api";import { createPreviewController } from "../preview-server";@@ -20,6 +24,7 @@ import {visualVerificationRule,} from "../mcp-guidance";import { apiCompatibilityHeaders } from "./api";+import { importProject as importProjectCommand } from "./import";import type { CommonYargsArgv } from "./yargs-types";export const mcpOptions = (yargs: CommonYargsArgv) =>@@ -50,6 +55,16 @@ export const mcp = async () => {...connection,headers: apiCompatibilityHeaders,};+ let importErrorMessage = "Project import failed.";+ const silentImportIndicator = {+ start: () => undefined,+ message: () => undefined,+ stop: (message?: string) => {+ if (message !== undefined) {+ importErrorMessage = message;+ }+ },+ };const session = createCliProjectSession({ connection: apiConnection });const preview = createPreviewController({ host: "127.0.0.1", port: 5173 });await connectProjectSessionMcpServer({@@ -63,6 +78,36 @@ export const mcp = async () => {createProjectSession: () => session,dryRun,}),+ async importProject(input) {+ importErrorMessage = "Project import failed.";+ try {+ await importProjectCommand(+ {+ to: input.to,+ assetsDir: input.assetsDir,+ ignoreVersionCheck: input.ignoreVersionCheck,+ skipAssets: input.skipAssets,+ },+ {+ importProjectBundleWithAssets,+ loadJSONFile,+ readFile,+ text: async () => {+ throw new Error("MCP import requires to.");+ },+ isInteractive: false,+ log: { info: () => undefined },+ spinner: () => silentImportIndicator,+ }+ );+ } catch (error) {+ if (isHandledCliError(error)) {+ throw new Error(importErrorMessage);+ }+ throw error;+ }+ return { imported: true };+ },async startPreview(input) {return preview.startAndWait(input);},diff --git a/packages/cli/src/commands/schema.test.ts b/packages/cli/src/commands/schema.test.tsindex 5d97825d6b..6bbfffcca9 100644--- a/packages/cli/src/commands/schema.test.ts+++ b/packages/cli/src/commands/schema.test.ts@@ -19,6 +19,7 @@ test("prints api command schema as json", () => {"init","link","sync",+ "import","build","preview","screenshot",diff --git a/packages/cli/src/docs.generated.ts b/packages/cli/src/docs.generated.tsindex 7c896f01f4..894006390a 100644--- a/packages/cli/src/docs.generated.ts+++ b/packages/cli/src/docs.generated.ts@@ -2,7 +2,7 @@// Edit markdown files in src/docs instead.export const cliDocs = {"api-use-cases":- '# CLI API Use Cases\n\n## Link/configure one project\n\nCommands:\n\n- webstudio init --link <api-share-link> --json\n\nNotes:\n\n- Writes local project id and global origin/token config.\n\n## Identify current token\n\nCommands:\n\n- MCP tool: whoami {}\n\n## Check token permissions\n\nCommands:\n\n- webstudio permissions --json\n\n## Inspect project/build/version\n\nCommands:\n\n- MCP tool: inspect {}\n- MCP tool: snapshot {"include":["pages","instances","styles"]}\n\n## Discover CLI/API capabilities\n\nCommands:\n\n- webstudio schema api --json\n- webstudio man api --json\n- webstudio man llm --json\n- webstudio man mcp --json\n- MCP tool: meta.index {}\n- MCP tool: meta.guide {"brief":"Create a pricing page"}\n- MCP tool: meta.get_more_tools {"brief":"update-styles"}\n\nNotes:\n\n- Use `tools/list` for machine-readable MCP tool schemas.\n- Use `resources/list` and `resources/read` for longer MCP resources such as `webstudio://project/tools` and `webstudio://project/guide`.\n\n## Inspect and refresh MCP session cache\n\nCommands:\n\n- MCP tool: status {}\n- MCP tool: refresh {"namespaces":["pages","instances","styles"]}\n- MCP tool: reset-session {}\n\nNotes:\n\n- Use status before a task to understand the cached ProjectSession state.\n- Use refresh when project data may have changed outside the current MCP session.\n- Use reset-session when local cached state is corrupt or incompatible.\n\n## Visually verify rendered work with AI vision\n\nCommands:\n\n- MCP tool: preview.start {"host":"127.0.0.1","port":5173}\n- MCP tool: preview.status {}\n- MCP tool: screenshot {"path":"/","output":"current.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot.diff {"baselinePath":"before.png","currentPath":"current.png","outputDir":".webstudio/screenshots"}\n- MCP tool: vision.install-ocr {"confirm":true}\n\nNotes:\n\n- Use this after page/content/style mutations and after generated project files are current so a vision-capable AI can see what was actually built.\n- Use waitForSelector when the rendered app has a reliable ready marker, waitUntil:"networkidle" for network-heavy pages, and waitForTimeout only for final visual settling.\n- For a fresh checkout, copied fixture, or newly generated app, run npm install or pnpm install in the generated project before preview.start or webstudio preview.\n- If preview fails with a missing generated-app command/package such as react-router or vite, install the generated app dependencies and retry.\n- When a baseline exists, use screenshot.diff to get changed regions, OCR textAnalysis, and diff artifact paths before deciding whether the result matches.\n- If screenshot.diff reports OCR unavailable and the user agrees to install it, call vision.install-ocr {"confirm":true}; otherwise continue with pixel diff and visual inspection.\n- Compare the PNG, OCR text evidence, and diff artifacts against the user\'s intent for layout, typography, colors, spacing, imagery, and responsive framing; then iterate with focused mutations.\n- Root CLI equivalent: webstudio preview --template ssg, then webstudio screenshot <url> --output current.png.\n\n## List pages\n\nCommands:\n\n- MCP tool: list-pages {"includeFolders":true}\n\n## Read page by id\n\nCommands:\n\n- MCP tool: get-page {"pageId":"<pageId>"}\n\n## Read page by path\n\nCommands:\n\n- MCP tool: get-page-by-path {"path":"/pricing"}\n\n## Create page\n\nCommands:\n\n- MCP tool: create-page {"name":"Pricing","path":"/pricing"}\n\n## Update page settings/metadata\n\nCommands:\n\n- MCP tool: update-page {"pageId":"<pageId>","title":"Pricing","description":"Plans","status":"200"}\n- MCP tool: update-page {"pageId":"<pageId>","auth":{"login":"<login>","password":"<password>"}}\n\n## Read project settings\n\nCommands:\n\n- MCP tool: get-project-settings {}\n\n## Update project settings\n\nCommands:\n\n- MCP tool: update-project-settings {"settings":"project-settings.json contents"}\n\n## List redirects\n\nCommands:\n\n- MCP tool: list-redirects {}\n\n## Create redirect\n\nCommands:\n\n- MCP tool: create-redirect {"oldPath":"/old","newPath":"/new","status":301}\n\n## Update redirect\n\nCommands:\n\n- MCP tool: update-redirect {"oldPath":"/old","newPath":"/newer","status":302}\n- MCP tool: update-redirect {"oldPath":"/old","status":null}\n\n## Delete redirect\n\nCommands:\n\n- MCP tool: delete-redirect {"oldPath":"/old"}\n\n## List breakpoints\n\nCommands:\n\n- MCP tool: list-breakpoints {}\n\n## Create breakpoint\n\nCommands:\n\n- MCP tool: create-breakpoint {"breakpointId":"tablet","label":"Tablet","maxWidth":991}\n\n## Update breakpoint\n\nCommands:\n\n- MCP tool: update-breakpoint {"breakpointId":"tablet","label":"Tablet","maxWidth":1023}\n- MCP tool: update-breakpoint {"breakpointId":"tablet","condition":null,"minWidth":768}\n- MCP tool: update-breakpoint {"breakpointId":"tablet","minWidth":null,"maxWidth":null,"condition":"(hover: hover)"}\n\n## Delete breakpoint\n\nCommands:\n\n- MCP tool: delete-breakpoint {"breakpointId":"tablet","confirm":true}\n\n## Duplicate page\n\nCommands:\n\n- MCP tool: duplicate-page {"pageId":"<pageId>","name":"Pricing Copy","path":"/pricing-copy"}\n\n## List page templates\n\nCommands:\n\n- MCP tool: list-page-templates {}\n\n## Create page from template\n\nCommands:\n\n- MCP tool: create-page-from-template {"templateId":"<templateId>","name":"Landing","path":"/landing"}\n\n## Delete page\n\nCommands:\n\n- MCP tool: delete-page {"pageId":"<pageId>"}\n\n## List folders\n\nCommands:\n\n- MCP tool: list-folders {"includePages":true}\n\n## Create folder\n\nCommands:\n\n- MCP tool: create-folder {"name":"Blog","slug":"blog"}\n\n## Update folder\n\nCommands:\n\n- MCP tool: update-folder {"folderId":"<folderId>","name":"Blog","slug":"blog"}\n\n## Delete folder\n\nCommands:\n\n- MCP tool: delete-folder {"folderId":"<folderId>"}\n\n## List element instances\n\nCommands:\n\n- MCP tool: list-instances {"pagePath":"/","maxDepth":3}\n\n## Inspect one element instance\n\nCommands:\n\n- MCP tool: inspect-instance {"instanceId":"<instanceId>","include":["props","styles","children"]}\n\n## Append/prepend/replace child elements\n\nCommands:\n\n- MCP tool: append-instance {"parentInstanceId":"<instanceId>","children":"children.json contents"}\n\n## Move elements\n\nCommands:\n\n- MCP tool: move-instance {"moves":"moves.json contents"}\n\n## Clone element subtree\n\nCommands:\n\n- MCP tool: clone-instance {"sourceInstanceId":"<instanceId>","parentInstanceId":"<targetParentId>"}\n\n## Delete element subtree\n\nCommands:\n\n- MCP tool: delete-instance {"instanceId":"<instanceId>"}\n\n## List text/expression children\n\nCommands:\n\n- MCP tool: list-texts {"pagePath":"/"}\n\n## Update text child\n\nCommands:\n\n- MCP tool: update-text {"instanceId":"<instanceId>","childIndex":0,"text":"Launch faster"}\n\n## Update props\n\nCommands:\n\n- MCP tool: update-props {"updates":"props.json contents"}\n\n## Delete props\n\nCommands:\n\n- MCP tool: delete-props {"deletions":"props.json contents"}\n\n## Bind props to expressions/resources/actions\n\nCommands:\n\n- MCP tool: bind-props {"bindings":"bindings.json contents"}\n\n## Read styles\n\nCommands:\n\n- MCP tool: get-styles {"instanceId":"<instanceId>","includeTokens":true}\n\n## Update local styles\n\nCommands:\n\n- MCP tool: update-styles {"updates":"styles.json contents"}\n\n## Delete local styles\n\nCommands:\n\n- MCP tool: delete-styles {"deletions":"styles.json contents"}\n\n## Replace matching style values\n\nCommands:\n\n- MCP tool: replace-styles {"replacements":"replace.json contents"}\n\n## List design tokens\n\nCommands:\n\n- MCP tool: list-design-tokens {"withUsage":true}\n\n## Create design tokens\n\nCommands:\n\n- MCP tool: create-design-token {"tokens":"tokens.json contents"}\n\n## Update design token styles\n\nCommands:\n\n- MCP tool: update-design-token-styles {"styleSourceId":"<tokenId>","updates":"styles.json contents"}\n\n## Delete design token styles\n\nCommands:\n\n- MCP tool: delete-design-token-styles {"styleSourceId":"<tokenId>","deletions":"styles.json contents"}\n\n## Attach design token to instances\n\nCommands:\n\n- MCP tool: attach-design-token {"styleSourceId":"<tokenId>","instanceIds":"instances.json contents"}\n\n## Detach design token from instances\n\nCommands:\n\n- MCP tool: detach-design-token {"styleSourceId":"<tokenId>","instanceIds":"instances.json contents"}\n\n## Extract design token from local styles\n\nCommands:\n\n- MCP tool: extract-design-token {"token":"token.json contents"}\n\n## List CSS variables\n\nCommands:\n\n- MCP tool: list-css-variables {"withUsage":true}\n\n## Define CSS variables\n\nCommands:\n\n- MCP tool: define-css-variable {"variables":"vars.json contents"}\n\n## Delete CSS variables\n\nCommands:\n\n- MCP tool: delete-css-variable {"names":"names.json contents","confirm":true}\n\n## Rewrite CSS variable references\n\nCommands:\n\n- MCP tool: rewrite-css-variable-refs {"variables":"variables.json contents"}\n\n## List data variables\n\nCommands:\n\n- MCP tool: list-variables {}\n\n## Create data variable\n\nCommands:\n\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"title","value":{"type":"string","value":"Hello"}}\n\n## Update data variable\n\nCommands:\n\n- MCP tool: update-variable {"variableId":"<variableId>","value":{"type":"json","value":{"count":1}}}\n\n## Delete data variable\n\nCommands:\n\n- MCP tool: delete-variable {"variableId":"<variableId>"}\n\n## List resources\n\nCommands:\n\n- MCP tool: list-resources {}\n\n## Create resource\n\nCommands:\n\n- MCP tool: create-resource {"name":"Posts","method":"get","url":"https://api.example.com/posts"}\n\n## Update resource\n\nCommands:\n\n- MCP tool: update-resource {"resourceId":"<resourceId>","url":"https://api.example.com/posts"}\n\n## Delete resource\n\nCommands:\n\n- MCP tool: delete-resource {"resourceId":"<resourceId>"}\n\n## List assets\n\nCommands:\n\n- MCP tool: list-assets {"withUsage":true}\n\n## Upload one asset\n\nCommands:\n\n- MCP tool: upload-asset {"asset":"asset.json contents","assetsDir":".webstudio/assets"}\n\n## Upload asset batch\n\nCommands:\n\n- MCP tool: upload-assets {"assets":"assets.json contents","assetsDir":".webstudio/assets"}\n\n## Find asset usage\n\nCommands:\n\n- MCP tool: find-asset-usage {"assetId":"<assetId>"}\n\n## Replace asset references\n\nCommands:\n\n- MCP tool: replace-asset {"fromAssetId":"<oldAssetId>","toAssetId":"<newAssetId>","confirm":true}\n\n## Delete assets\n\nCommands:\n\n- MCP tool: delete-asset {"assetId":"<assetId>","confirm":true}\n\n## Publish project\n\nCommands:\n\n- webstudio publish deploy --target production --json\n\n## List publishes\n\nCommands:\n\n- webstudio publish list --json\n\n## Check publish job\n\nCommands:\n\n- webstudio publish status --job <buildId> --json\n\n## Unpublish\n\nCommands:\n\n- webstudio publish unpublish --target production --confirm --json\n\n## List domains\n\nCommands:\n\n- webstudio domains list --json\n\n## Create domain\n\nCommands:\n\n- webstudio domains create --domain example.com --json\n\n## Update domain\n\nCommands:\n\n- webstudio domains update --domain-id <domainId> --domain www.example.com --json\n\n## Delete domain\n\nCommands:\n\n- webstudio domains delete --domain-id <domainId> --confirm --json\n\n## Verify domain\n\nCommands:\n\n- webstudio domains verify --domain-id <domainId> --json\n\n## Make arbitrary store-level changes\n\nCommands:\n\n- MCP tool: inspect {}\n- MCP tool: snapshot {"include":["<namespace>"]}\n- MCP tool: apply-patch {"baseVersion":"<version>","transactions":"patch.json contents"}\n\nNotes:\n\n- Use only when no semantic command exists.\n\n## Manage marketplace metadata\n\nCommands:\n\n- MCP tool: snapshot {"include":["marketplaceProduct"]}\n- MCP tool: apply-patch {"baseVersion":"<version>","transactions":"patch.json contents"}\n\nPatch namespaces:\n\n- marketplaceProduct\n\n## Search and inspect safely\n\nCommands:\n\n- MCP tool: list-instances {"pagePath":"/","maxDepth":5}\n- MCP tool: inspect-instance {"instanceId":"<instanceId>","include":["props","styles","children"]}\n- MCP tool: list-texts {"pagePath":"/"}\n- MCP tool: list-assets {"withUsage":true}\n- MCP tool: find-asset-usage {"assetId":"<assetId>"}\n- MCP tool: snapshot {"include":["pages","instances","props","resources","assets"]}\n\nNotes:\n\n- Use this for finding elements by label, type, href/resource patterns, HTML snippets, missing accessibility metadata, or asset usage.\n\n## Refactor targeted content\n\nCommands:\n\n- MCP tool: list-instances {"pagePath":"/"}\n- MCP tool: list-texts {"pagePath":"/"}\n- MCP tool: update-text {"instanceId":"<instanceId>","childIndex":0,"text":"Launch faster"}\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: update-page {"pageId":"<pageId>","title":"Pricing","description":"Plans"}\n- MCP tool: update-resource {"resourceId":"<resourceId>","url":"https://api.example.com/posts"}\n- MCP tool: replace-asset {"fromAssetId":"<oldAssetId>","toAssetId":"<newAssetId>","confirm":true}\n- MCP tool: replace-styles {"replacements":"replace.json contents"}\n- MCP tool: rewrite-css-variable-refs {"variables":"variables.json contents"}\n\nNotes:\n\n- Use focused reads first, then mutate only matching instances, props, metadata, resource URLs, assets, or style references.\n\n## Optimize existing project\n\nCommands:\n\n- MCP tool: list-pages {"includeFolders":true}\n- MCP tool: update-page {"pageId":"<pageId>","title":"Pricing","description":"Plans"}\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: list-breakpoints {}\n- MCP tool: update-breakpoint {"breakpointId":"tablet","maxWidth":1023}\n- MCP tool: get-styles {"instanceId":"<instanceId>","includeTokens":true}\n- MCP tool: update-styles {"updates":"styles.json contents"}\n- MCP tool: attach-design-token {"styleSourceId":"<tokenId>","instanceIds":"instances.json contents"}\n- MCP tool: update-project-settings {"settings":"project-settings.json contents"}\n\nNotes:\n\n- Use this for SEO metadata, accessibility labels, responsive behavior, token consistency, and project settings.\n\n## Connect external data\n\nCommands:\n\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"title","value":{"type":"string","value":"Hello"}}\n- MCP tool: create-resource {"name":"Posts","method":"get","url":"https://api.example.com/posts"}\n- MCP tool: update-resource {"resourceId":"<resourceId>","url":"https://api.example.com/posts"}\n- MCP tool: bind-props {"bindings":"bindings.json contents"}\n- MCP tool: append-instance {"parentInstanceId":"<instanceId>","children":"children.json contents"}\n\nNotes:\n\n- Use this for CMS sections, blog listings, Ghost/headless CMS pages, n8n-style integrations, and API URLs built from variables.\n\n## Support dynamic runtime behavior\n\nCommands:\n\n- MCP tool: append-instance {"parentInstanceId":"<instanceId>","children":"children.json contents"}\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: bind-props {"bindings":"bindings.json contents"}\n- MCP tool: create-resource {"name":"Seats","method":"get","url":"https://api.example.com/seats"}\n- MCP tool: snapshot {"include":["instances","props","resources"]}\n- MCP tool: apply-patch {"baseVersion":"<version>","transactions":"patch.json contents"}\n\nNotes:\n\n- Use existing scripts/resources for behavior, then move presentational structure into editable Webstudio instances where possible.\n- There is no dedicated semantic command yet for converting script-generated UI into editable Webstudio structure.\n\n## Build authenticated pages\n\nCommands:\n\n- MCP tool: create-page {"name":"Account","path":"/account"}\n- MCP tool: update-page {"pageId":"<pageId>","auth":{"login":"<login>","password":"<password>"}}\n- MCP tool: create-resource {"name":"Session","method":"get","url":"https://api.example.com/session"}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"user","value":{"type":"json","value":{}}}\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: bind-props {"bindings":"bindings.json contents"}\n\nNotes:\n\n- Basic auth is semantic today. Provider-specific Supabase/Firebase setup still requires manual resources, props, embeds, or patches.\n\n## Generate from design input\n\nCommands:\n\n- MCP tool: create-page {"name":"Landing","path":"/landing"}\n- MCP tool: create-design-token {"tokens":"tokens.json contents"}\n- MCP tool: define-css-variable {"variables":"vars.json contents"}\n- MCP tool: append-instance {"parentInstanceId":"<instanceId>","children":"children.json contents"}\n- MCP tool: update-styles {"updates":"styles.json contents"}\n- MCP tool: preview.start {"host":"127.0.0.1","port":5173}\n- MCP tool: screenshot {"path":"/","output":"current.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n\nNotes:\n\n- Use this after external design interpretation. There is no dedicated import command for Figma, screenshots, Inception output, or design.md yet.\n\n## Cross-project maintenance\n\nCommands:\n\n- webstudio init --link <api-share-link> --json\n- webstudio permissions --json\n- webstudio mcp\n\nNotes:\n\n- Public API and CLI intentionally operate on one configured project at a time. Use an external script to loop over projects.\n\n# Known CLI Gaps\n\n## General project search and audit\n\nMissing:\nNo single semantic command searches across instance labels, props, hrefs, resource URLs, HTML embeds, asset references, and missing accessibility metadata.\n\nCurrent fallback:\nUse focused MCP reads such as list-instances, list-texts, list-assets, find-asset-usage, and snapshot.\n\nSuggested commands:\n\n- search-project\n- audit-accessibility\n- find-prop-usage\n\n## Save and manage page templates\n\nMissing:\nCLI can list page templates and create pages from existing templates, but cannot save a page as a template or update/delete templates semantically.\n\nCurrent fallback:\nUse MCP snapshot and apply-patch only when the template data model is understood.\n\nSuggested commands:\n\n- create-page-template\n- update-page-template\n- delete-page-template\n\n## Semantic marketplace metadata\n\nMissing:\nMarketplace metadata is only available through MCP snapshot/apply-patch, not dedicated semantic commands.\n\nCurrent fallback:\nUse MCP snapshot --include marketplaceProduct and apply-patch.\n\nSuggested commands:\n\n- get-marketplace\n- update-marketplace\n\n## Provider-specific authenticated pages\n\nMissing:\nCLI supports page basic auth and generic resources/props/embeds, but not guided Supabase/Firebase auth setup.\n\nCurrent fallback:\nCreate the page, resources, variables, props, and embeds manually with existing MCP semantic tools.\n\nSuggested commands:\n\n- setup-auth-page\n\n## Dynamic script/runtime integration helpers\n\nMissing:\nCLI can manipulate props/resources/embeds, but has no semantic workflow for converting script-generated UI into editable Webstudio structures.\n\nCurrent fallback:\nUse MCP append-instance, props, resources, and raw patch where necessary.\n\nSuggested commands:\n\n- integrate-runtime-ui\n\n## Generate from design input\n\nMissing:\nNo command imports Figma, screenshots, Inception output, or design.md and turns it into pages/tokens/layout.\n\nCurrent fallback:\nUse external generation, then apply semantic CLI commands or apply-patch.\n\nSuggested commands:\n\n- generate-from-design\n\n## Built-in cross-project maintenance\n\nMissing:\nPublic API and CLI intentionally operate on one configured project at a time; there is no built-in multi-project discovery or loop runner.\n\nCurrent fallback:\nRun the CLI from an external script that reconfigures one project/session at a time.\n\nSuggested commands:\n\n- none\n',+ '# CLI API Use Cases\n\n## Link/configure one project\n\nCommands:\n\n- webstudio init --link <api-share-link> --json\n\nNotes:\n\n- Writes local project id and global origin/token config.\n\n## Import synced project bundle into another project\n\nCommands:\n\n- webstudio sync\n- webstudio import --to <destination-share-link>\n- MCP tool: import {"to":"<destination-share-link>"}\n\nNotes:\n\n- Imports local `.webstudio/data.json` into the destination project.\n- Destination share link must allow build/import access.\n- Use `--skip-assets` only when asset rows and files should not be imported.\n\n## Identify current token\n\nCommands:\n\n- MCP tool: whoami {}\n\n## Check token permissions\n\nCommands:\n\n- webstudio permissions --json\n\n## Inspect project/build/version\n\nCommands:\n\n- MCP tool: inspect {}\n- MCP tool: snapshot {"include":["pages","instances","styles"]}\n\n## Discover CLI/API capabilities\n\nCommands:\n\n- webstudio schema api --json\n- webstudio man api --json\n- webstudio man llm --json\n- webstudio man mcp --json\n- MCP tool: meta.index {}\n- MCP tool: meta.guide {"brief":"Create a pricing page"}\n- MCP tool: meta.get_more_tools {"brief":"update-styles"}\n\nNotes:\n\n- Use `tools/list` for machine-readable MCP tool schemas.\n- Use `resources/list` and `resources/read` for longer MCP resources such as `webstudio://project/tools` and `webstudio://project/guide`.\n\n## Inspect and refresh MCP session cache\n\nCommands:\n\n- MCP tool: status {}\n- MCP tool: refresh {"namespaces":["pages","instances","styles"]}\n- MCP tool: reset-session {}\n\nNotes:\n\n- Use status before a task to understand the cached ProjectSession state.\n- Use refresh when project data may have changed outside the current MCP session.\n- Use reset-session when local cached state is corrupt or incompatible.\n\n## Visually verify rendered work with AI vision\n\nCommands:\n\n- MCP tool: preview.start {"host":"127.0.0.1","port":5173}\n- MCP tool: preview.status {}\n- MCP tool: screenshot {"path":"/","output":"current.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot.diff {"baselinePath":"before.png","currentPath":"current.png","outputDir":".webstudio/screenshots"}\n- MCP tool: vision.install-ocr {"confirm":true}\n\nNotes:\n\n- Use this after page/content/style mutations and after generated project files are current so a vision-capable AI can see what was actually built.\n- Use waitForSelector when the rendered app has a reliable ready marker, waitUntil:"networkidle" for network-heavy pages, and waitForTimeout only for final visual settling.\n- For a fresh checkout, copied fixture, or newly generated app, run npm install or pnpm install in the generated project before preview.start or webstudio preview.\n- If preview fails with a missing generated-app command/package such as react-router or vite, install the generated app dependencies and retry.\n- When a baseline exists, use screenshot.diff to get changed regions, OCR textAnalysis, and diff artifact paths before deciding whether the result matches.\n- If screenshot.diff reports OCR unavailable and the user agrees to install it, call vision.install-ocr {"confirm":true}; otherwise continue with pixel diff and visual inspection.\n- Compare the PNG, OCR text evidence, and diff artifacts against the user\'s intent for layout, typography, colors, spacing, imagery, and responsive framing; then iterate with focused mutations.\n- Root CLI equivalent: webstudio preview --template ssg, then webstudio screenshot <url> --output current.png.\n\n## List pages\n\nCommands:\n\n- MCP tool: list-pages {"includeFolders":true}\n\n## Read page by id\n\nCommands:\n\n- MCP tool: get-page {"pageId":"<pageId>"}\n\n## Read page by path\n\nCommands:\n\n- MCP tool: get-page-by-path {"path":"/pricing"}\n\n## Create page\n\nCommands:\n\n- MCP tool: create-page {"name":"Pricing","path":"/pricing"}\n\n## Update page settings/metadata\n\nCommands:\n\n- MCP tool: update-page {"pageId":"<pageId>","title":"Pricing","description":"Plans","status":"200"}\n- MCP tool: update-page {"pageId":"<pageId>","auth":{"login":"<login>","password":"<password>"}}\n\n## Read project settings\n\nCommands:\n\n- MCP tool: get-project-settings {}\n\n## Update project settings\n\nCommands:\n\n- MCP tool: update-project-settings {"settings":"project-settings.json contents"}\n\n## List redirects\n\nCommands:\n\n- MCP tool: list-redirects {}\n\n## Create redirect\n\nCommands:\n\n- MCP tool: create-redirect {"oldPath":"/old","newPath":"/new","status":301}\n\n## Update redirect\n\nCommands:\n\n- MCP tool: update-redirect {"oldPath":"/old","newPath":"/newer","status":302}\n- MCP tool: update-redirect {"oldPath":"/old","status":null}\n\n## Delete redirect\n\nCommands:\n\n- MCP tool: delete-redirect {"oldPath":"/old"}\n\n## List breakpoints\n\nCommands:\n\n- MCP tool: list-breakpoints {}\n\n## Create breakpoint\n\nCommands:\n\n- MCP tool: create-breakpoint {"breakpointId":"tablet","label":"Tablet","maxWidth":991}\n\n## Update breakpoint\n\nCommands:\n\n- MCP tool: update-breakpoint {"breakpointId":"tablet","label":"Tablet","maxWidth":1023}\n- MCP tool: update-breakpoint {"breakpointId":"tablet","condition":null,"minWidth":768}\n- MCP tool: update-breakpoint {"breakpointId":"tablet","minWidth":null,"maxWidth":null,"condition":"(hover: hover)"}\n\n## Delete breakpoint\n\nCommands:\n\n- MCP tool: delete-breakpoint {"breakpointId":"tablet","confirm":true}\n\n## Duplicate page\n\nCommands:\n\n- MCP tool: duplicate-page {"pageId":"<pageId>","name":"Pricing Copy","path":"/pricing-copy"}\n\n## List page templates\n\nCommands:\n\n- MCP tool: list-page-templates {}\n\n## Create page from template\n\nCommands:\n\n- MCP tool: create-page-from-template {"templateId":"<templateId>","name":"Landing","path":"/landing"}\n\n## Delete page\n\nCommands:\n\n- MCP tool: delete-page {"pageId":"<pageId>"}\n\n## List folders\n\nCommands:\n\n- MCP tool: list-folders {"includePages":true}\n\n## Create folder\n\nCommands:\n\n- MCP tool: create-folder {"name":"Blog","slug":"blog"}\n\n## Update folder\n\nCommands:\n\n- MCP tool: update-folder {"folderId":"<folderId>","name":"Blog","slug":"blog"}\n\n## Delete folder\n\nCommands:\n\n- MCP tool: delete-folder {"folderId":"<folderId>"}\n\n## List element instances\n\nCommands:\n\n- MCP tool: list-instances {"pagePath":"/","maxDepth":3}\n\n## Inspect one element instance\n\nCommands:\n\n- MCP tool: inspect-instance {"instanceId":"<instanceId>","include":["props","styles","children"]}\n\n## Append/prepend/replace child elements\n\nCommands:\n\n- MCP tool: append-instance {"parentInstanceId":"<instanceId>","children":"children.json contents"}\n\n## Move elements\n\nCommands:\n\n- MCP tool: move-instance {"moves":"moves.json contents"}\n\n## Clone element subtree\n\nCommands:\n\n- MCP tool: clone-instance {"sourceInstanceId":"<instanceId>","parentInstanceId":"<targetParentId>"}\n\n## Delete element subtree\n\nCommands:\n\n- MCP tool: delete-instance {"instanceId":"<instanceId>"}\n\n## List text/expression children\n\nCommands:\n\n- MCP tool: list-texts {"pagePath":"/"}\n\n## Update text child\n\nCommands:\n\n- MCP tool: update-text {"instanceId":"<instanceId>","childIndex":0,"text":"Launch faster"}\n\n## Update props\n\nCommands:\n\n- MCP tool: update-props {"updates":"props.json contents"}\n\n## Delete props\n\nCommands:\n\n- MCP tool: delete-props {"deletions":"props.json contents"}\n\n## Bind props to expressions/resources/actions\n\nCommands:\n\n- MCP tool: bind-props {"bindings":"bindings.json contents"}\n\n## Read styles\n\nCommands:\n\n- MCP tool: get-styles {"instanceId":"<instanceId>","includeTokens":true}\n\n## Update local styles\n\nCommands:\n\n- MCP tool: update-styles {"updates":"styles.json contents"}\n\n## Delete local styles\n\nCommands:\n\n- MCP tool: delete-styles {"deletions":"styles.json contents"}\n\n## Replace matching style values\n\nCommands:\n\n- MCP tool: replace-styles {"replacements":"replace.json contents"}\n\n## List design tokens\n\nCommands:\n\n- MCP tool: list-design-tokens {"withUsage":true}\n\n## Create design tokens\n\nCommands:\n\n- MCP tool: create-design-token {"tokens":"tokens.json contents"}\n\n## Update design token styles\n\nCommands:\n\n- MCP tool: update-design-token-styles {"styleSourceId":"<tokenId>","updates":"styles.json contents"}\n\n## Delete design token styles\n\nCommands:\n\n- MCP tool: delete-design-token-styles {"styleSourceId":"<tokenId>","deletions":"styles.json contents"}\n\n## Attach design token to instances\n\nCommands:\n\n- MCP tool: attach-design-token {"styleSourceId":"<tokenId>","instanceIds":"instances.json contents"}\n\n## Detach design token from instances\n\nCommands:\n\n- MCP tool: detach-design-token {"styleSourceId":"<tokenId>","instanceIds":"instances.json contents"}\n\n## Extract design token from local styles\n\nCommands:\n\n- MCP tool: extract-design-token {"token":"token.json contents"}\n\n## List CSS variables\n\nCommands:\n\n- MCP tool: list-css-variables {"withUsage":true}\n\n## Define CSS variables\n\nCommands:\n\n- MCP tool: define-css-variable {"variables":"vars.json contents"}\n\n## Delete CSS variables\n\nCommands:\n\n- MCP tool: delete-css-variable {"names":"names.json contents","confirm":true}\n\n## Rewrite CSS variable references\n\nCommands:\n\n- MCP tool: rewrite-css-variable-refs {"variables":"variables.json contents"}\n\n## List data variables\n\nCommands:\n\n- MCP tool: list-variables {}\n\n## Create data variable\n\nCommands:\n\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"title","value":{"type":"string","value":"Hello"}}\n\n## Update data variable\n\nCommands:\n\n- MCP tool: update-variable {"variableId":"<variableId>","value":{"type":"json","value":{"count":1}}}\n\n## Delete data variable\n\nCommands:\n\n- MCP tool: delete-variable {"variableId":"<variableId>"}\n\n## List resources\n\nCommands:\n\n- MCP tool: list-resources {}\n\n## Create resource\n\nCommands:\n\n- MCP tool: create-resource {"name":"Posts","method":"get","url":"https://api.example.com/posts"}\n\n## Update resource\n\nCommands:\n\n- MCP tool: update-resource {"resourceId":"<resourceId>","url":"https://api.example.com/posts"}\n\n## Delete resource\n\nCommands:\n\n- MCP tool: delete-resource {"resourceId":"<resourceId>"}\n\n## List assets\n\nCommands:\n\n- MCP tool: list-assets {"withUsage":true}\n\n## Upload one asset\n\nCommands:\n\n- MCP tool: upload-asset {"asset":"asset.json contents","assetsDir":".webstudio/assets"}\n\n## Upload asset batch\n\nCommands:\n\n- MCP tool: upload-assets {"assets":"assets.json contents","assetsDir":".webstudio/assets"}\n\n## Find asset usage\n\nCommands:\n\n- MCP tool: find-asset-usage {"assetId":"<assetId>"}\n\n## Replace asset references\n\nCommands:\n\n- MCP tool: replace-asset {"fromAssetId":"<oldAssetId>","toAssetId":"<newAssetId>","confirm":true}\n\n## Delete assets\n\nCommands:\n\n- MCP tool: delete-asset {"assetId":"<assetId>","confirm":true}\n\n## Publish project\n\nCommands:\n\n- webstudio publish deploy --target production --json\n\n## List publishes\n\nCommands:\n\n- webstudio publish list --json\n\n## Check publish job\n\nCommands:\n\n- webstudio publish status --job <buildId> --json\n\n## Unpublish\n\nCommands:\n\n- webstudio publish unpublish --target production --confirm --json\n\n## List domains\n\nCommands:\n\n- webstudio domains list --json\n\n## Create domain\n\nCommands:\n\n- webstudio domains create --domain example.com --json\n\n## Update domain\n\nCommands:\n\n- webstudio domains update --domain-id <domainId> --domain www.example.com --json\n\n## Delete domain\n\nCommands:\n\n- webstudio domains delete --domain-id <domainId> --confirm --json\n\n## Verify domain\n\nCommands:\n\n- webstudio domains verify --domain-id <domainId> --json\n\n## Make arbitrary store-level changes\n\nCommands:\n\n- MCP tool: inspect {}\n- MCP tool: snapshot {"include":["<namespace>"]}\n- MCP tool: apply-patch {"baseVersion":"<version>","transactions":"patch.json contents"}\n\nNotes:\n\n- Use only when no semantic command exists.\n\n## Manage marketplace metadata\n\nCommands:\n\n- MCP tool: snapshot {"include":["marketplaceProduct"]}\n- MCP tool: apply-patch {"baseVersion":"<version>","transactions":"patch.json contents"}\n\nPatch namespaces:\n\n- marketplaceProduct\n\n## Search and inspect safely\n\nCommands:\n\n- MCP tool: list-instances {"pagePath":"/","maxDepth":5}\n- MCP tool: inspect-instance {"instanceId":"<instanceId>","include":["props","styles","children"]}\n- MCP tool: list-texts {"pagePath":"/"}\n- MCP tool: list-assets {"withUsage":true}\n- MCP tool: find-asset-usage {"assetId":"<assetId>"}\n- MCP tool: snapshot {"include":["pages","instances","props","resources","assets"]}\n\nNotes:\n\n- Use this for finding elements by label, type, href/resource patterns, HTML snippets, missing accessibility metadata, or asset usage.\n\n## Refactor targeted content\n\nCommands:\n\n- MCP tool: list-instances {"pagePath":"/"}\n- MCP tool: list-texts {"pagePath":"/"}\n- MCP tool: update-text {"instanceId":"<instanceId>","childIndex":0,"text":"Launch faster"}\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: update-page {"pageId":"<pageId>","title":"Pricing","description":"Plans"}\n- MCP tool: update-resource {"resourceId":"<resourceId>","url":"https://api.example.com/posts"}\n- MCP tool: replace-asset {"fromAssetId":"<oldAssetId>","toAssetId":"<newAssetId>","confirm":true}\n- MCP tool: replace-styles {"replacements":"replace.json contents"}\n- MCP tool: rewrite-css-variable-refs {"variables":"variables.json contents"}\n\nNotes:\n\n- Use focused reads first, then mutate only matching instances, props, metadata, resource URLs, assets, or style references.\n\n## Optimize existing project\n\nCommands:\n\n- MCP tool: list-pages {"includeFolders":true}\n- MCP tool: update-page {"pageId":"<pageId>","title":"Pricing","description":"Plans"}\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: list-breakpoints {}\n- MCP tool: update-breakpoint {"breakpointId":"tablet","maxWidth":1023}\n- MCP tool: get-styles {"instanceId":"<instanceId>","includeTokens":true}\n- MCP tool: update-styles {"updates":"styles.json contents"}\n- MCP tool: attach-design-token {"styleSourceId":"<tokenId>","instanceIds":"instances.json contents"}\n- MCP tool: update-project-settings {"settings":"project-settings.json contents"}\n\nNotes:\n\n- Use this for SEO metadata, accessibility labels, responsive behavior, token consistency, and project settings.\n\n## Connect external data\n\nCommands:\n\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"title","value":{"type":"string","value":"Hello"}}\n- MCP tool: create-resource {"name":"Posts","method":"get","url":"https://api.example.com/posts"}\n- MCP tool: update-resource {"resourceId":"<resourceId>","url":"https://api.example.com/posts"}\n- MCP tool: bind-props {"bindings":"bindings.json contents"}\n- MCP tool: append-instance {"parentInstanceId":"<instanceId>","children":"children.json contents"}\n\nNotes:\n\n- Use this for CMS sections, blog listings, Ghost/headless CMS pages, n8n-style integrations, and API URLs built from variables.\n\n## Support dynamic runtime behavior\n\nCommands:\n\n- MCP tool: append-instance {"parentInstanceId":"<instanceId>","children":"children.json contents"}\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: bind-props {"bindings":"bindings.json contents"}\n- MCP tool: create-resource {"name":"Seats","method":"get","url":"https://api.example.com/seats"}\n- MCP tool: snapshot {"include":["instances","props","resources"]}\n- MCP tool: apply-patch {"baseVersion":"<version>","transactions":"patch.json contents"}\n\nNotes:\n\n- Use existing scripts/resources for behavior, then move presentational structure into editable Webstudio instances where possible.\n- There is no dedicated semantic command yet for converting script-generated UI into editable Webstudio structure.\n\n## Build authenticated pages\n\nCommands:\n\n- MCP tool: create-page {"name":"Account","path":"/account"}\n- MCP tool: update-page {"pageId":"<pageId>","auth":{"login":"<login>","password":"<password>"}}\n- MCP tool: create-resource {"name":"Session","method":"get","url":"https://api.example.com/session"}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"user","value":{"type":"json","value":{}}}\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: bind-props {"bindings":"bindings.json contents"}\n\nNotes:\n\n- Basic auth is semantic today. Provider-specific Supabase/Firebase setup still requires manual resources, props, embeds, or patches.\n\n## Generate from design input\n\nCommands:\n\n- MCP tool: create-page {"name":"Landing","path":"/landing"}\n- MCP tool: create-design-token {"tokens":"tokens.json contents"}\n- MCP tool: define-css-variable {"variables":"vars.json contents"}\n- MCP tool: append-instance {"parentInstanceId":"<instanceId>","children":"children.json contents"}\n- MCP tool: update-styles {"updates":"styles.json contents"}\n- MCP tool: preview.start {"host":"127.0.0.1","port":5173}\n- MCP tool: screenshot {"path":"/","output":"current.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n\nNotes:\n\n- Use this after external design interpretation. There is no dedicated import command for Figma, screenshots, Inception output, or design.md yet.\n\n## Cross-project maintenance\n\nCommands:\n\n- webstudio init --link <api-share-link> --json\n- webstudio permissions --json\n- webstudio mcp\n\nNotes:\n\n- Public API and CLI intentionally operate on one configured project at a time. Use an external script to loop over projects.\n\n# Known CLI Gaps\n\n## General project search and audit\n\nMissing:\nNo single semantic command searches across instance labels, props, hrefs, resource URLs, HTML embeds, asset references, and missing accessibility metadata.\n\nCurrent fallback:\nUse focused MCP reads such as list-instances, list-texts, list-assets, find-asset-usage, and snapshot.\n\nSuggested commands:\n\n- search-project\n- audit-accessibility\n- find-prop-usage\n\n## Save and manage page templates\n\nMissing:\nCLI can list page templates and create pages from existing templates, but cannot save a page as a template or update/delete templates semantically.\n\nCurrent fallback:\nUse MCP snapshot and apply-patch only when the template data model is understood.\n\nSuggested commands:\n\n- create-page-template\n- update-page-template\n- delete-page-template\n\n## Semantic marketplace metadata\n\nMissing:\nMarketplace metadata is only available through MCP snapshot/apply-patch, not dedicated semantic commands.\n\nCurrent fallback:\nUse MCP snapshot --include marketplaceProduct and apply-patch.\n\nSuggested commands:\n\n- get-marketplace\n- update-marketplace\n\n## Provider-specific authenticated pages\n\nMissing:\nCLI supports page basic auth and generic resources/props/embeds, but not guided Supabase/Firebase auth setup.\n\nCurrent fallback:\nCreate the page, resources, variables, props, and embeds manually with existing MCP semantic tools.\n\nSuggested commands:\n\n- setup-auth-page\n\n## Dynamic script/runtime integration helpers\n\nMissing:\nCLI can manipulate props/resources/embeds, but has no semantic workflow for converting script-generated UI into editable Webstudio structures.\n\nCurrent fallback:\nUse MCP append-instance, props, resources, and raw patch where necessary.\n\nSuggested commands:\n\n- integrate-runtime-ui\n\n## Generate from design input\n\nMissing:\nNo command imports Figma, screenshots, Inception output, or design.md and turns it into pages/tokens/layout.\n\nCurrent fallback:\nUse external generation, then apply semantic CLI commands or apply-patch.\n\nSuggested commands:\n\n- generate-from-design\n\n## Built-in cross-project maintenance\n\nMissing:\nPublic API and CLI intentionally operate on one configured project at a time; there is no built-in multi-project discovery or loop runner.\n\nCurrent fallback:\nRun the CLI from an external script that reconfigures one project/session at a time.\n\nSuggested commands:\n\n- none\n',"manual-api":'# Webstudio API CLI Manual\n\nThe API commands operate on the single project configured by:\n\n- .webstudio/config.json: projectId\n- global Webstudio config: origin and token\n\nRules:\n\n- Always pass --json.\n- Never pass a project id. Commands use configured project only.\n- Read ids before writing. Do not invent ids for existing records.\n- stdout is one JSON object. stderr is diagnostics.\n- Prefer MCP semantic tools for detailed project edits. Use MCP apply-patch only when no semantic tool exists.\n\n## Start\n\n{{start}}\n\n## Read First\n\n{{readFirst}}\n\n## Project Session Cache\n\n- CLI commands use one local ProjectSession snapshot for the configured project.\n- Local-capable reads use cached namespaces when compatible and fetch only missing or stale namespaces.\n- Local-capable mutations build patches from the local snapshot, then commit with the cached build version.\n- Successful mutation commits update the local snapshot only after the remote commit succeeds.\n- Server-only commands run remotely and invalidate/refetch namespaces declared by the operation catalog.\n- Use --refresh on local-capable commands to refresh required namespaces before running.\n- Successful JSON responses include meta.session with operationId, buildId, version, source, committed, compatibility, namespace freshness, and diagnostics.\n\n## CLI Capability Inventory\n\n### Top-Level Commands\n\n{{topLevelCapabilityIndex}}\n\n### High-Level API Commands By Area\n\n{{apiCapabilityIndex}}\n\n### MCP-Only Operations\n\nThese are intentionally exposed through `webstudio mcp`, not as top-level shell commands:\n\n{{mcpOnlyCommandIndex}}\n\n## Task Recipes\n\n{{taskRecipeIndex}}\n\n## Use Case Index\n\n{{useCaseIndex}}\n\n## Known CLI Gaps\n\n{{knownCliGapIndex}}\n\n## Input File Shapes\n\n{{inputFileShapeIndex}}\n\n## Raw Patch Fallback\n\napply-patch accepts either BuildPatchTransaction[] or { "transactions": BuildPatchTransaction[] }.\n\nEach transaction has:\n\n{\n"id": "unique-client-transaction-id",\n"payload": [\n{\n"namespace": "pages",\n"patches": [\n{ "op": "replace", "path": ["meta", "siteName"], "value": "New Site" }\n]\n}\n]\n}\n\nPatch paths are JSON-patch-like paths into Builder store data. Map-like namespaces use ids as the first path item.\n\nSupported namespaces:\n\n- pages: site metadata, redirects, page records, folders, compiler settings\n- instances: element instances and children, including text/expression children\n- props: element props, bindings, page references, resource bindings\n- styles: CSS declarations keyed by style declaration key\n- styleSources: local style sources and reusable design tokens\n- styleSourceSelections: instance-to-style-source connections\n- dataSources: data variables, parameters, and resource data sources\n- resources: data resource definitions\n- assets: project asset records handled by the existing asset patch path\n- breakpoints: responsive breakpoints\n- marketplaceProduct: marketplace metadata\n\nCommit raw patch:\n\nMCP tool: apply-patch\n\n## Raw Patch Examples\n\nRename the site:\n\n[\n{\n"id": "tx-site-name",\n"payload": [\n{\n"namespace": "pages",\n"patches": [\n{ "op": "add", "path": ["meta", "siteName"], "value": "Acme Studio" }\n]\n}\n]\n}\n]\n\nUpdate page title metadata:\n\n[\n{\n"id": "tx-page-title",\n"payload": [\n{\n"namespace": "pages",\n"patches": [\n{ "op": "replace", "path": ["pages", "page-id", "meta", "title"], "value": "Pricing" }\n]\n}\n]\n}\n]\n\nUpdate a text child on an element:\n\n[\n{\n"id": "tx-text",\n"payload": [\n{\n"namespace": "instances",\n"patches": [\n{ "op": "replace", "path": ["instance-id", "children", 0, "value"], "value": "Launch faster" }\n]\n}\n]\n}\n]\n\nCreate a data variable:\n\n[\n{\n"id": "tx-variable",\n"payload": [\n{\n"namespace": "dataSources",\n"patches": [\n{\n"op": "add",\n"path": ["variable-id"],\n"value": {\n"type": "variable",\n"id": "variable-id",\n"scopeInstanceId": "instance-id",\n"name": "headline",\n"value": { "type": "string", "value": "Launch faster" }\n}\n}\n]\n}\n]\n}\n]\n\nCreate a design token:\n\n[\n{\n"id": "tx-token",\n"payload": [\n{\n"namespace": "styleSources",\n"patches": [\n{ "op": "add", "path": ["token-id"], "value": { "type": "token", "id": "token-id", "name": "Brand Primary" } }\n]\n},\n{\n"namespace": "styles",\n"patches": [\n{\n"op": "add",\n"path": ["token-id:base:color:"],\n"value": {\n"styleSourceId": "token-id",\n"breakpointId": "base",\n"property": "color",\n"value": { "type": "keyword", "value": "red" }\n}\n}\n]\n}\n]\n}\n]\n\n## Safety Rules\n\n- For MCP apply-patch, read the latest version with MCP snapshot before writing.\n- Reuse ids from MCP snapshot output when updating existing records.\n- Generate new unique ids when adding records.\n- If apply-patch reports a version conflict, read the latest build and regenerate the patch.\n- Prefer semantic MCP read tools for discovery, then use MCP snapshot for exact patch paths.\n\n## Command Index\n\n{{commandIndex}}\n',"manual-llm":diff --git a/packages/cli/src/docs/api-use-cases.md b/packages/cli/src/docs/api-use-cases.mdindex e5dd3c04de..f4c5d7afeb 100644--- a/packages/cli/src/docs/api-use-cases.md+++ b/packages/cli/src/docs/api-use-cases.md@@ -10,6 +10,20 @@ Notes:- Writes local project id and global origin/token config.+## Import synced project bundle into another project++Commands:++- webstudio sync+- webstudio import --to <destination-share-link>+- MCP tool: import {"to":"<destination-share-link>"}++Notes:++- Imports local `.webstudio/data.json` into the destination project.+- Destination share link must allow build/import access.+- Use `--skip-assets` only when asset rows and files should not be imported.+## Identify current tokenCommands:diff --git a/packages/project-build/src/mcp.test.ts b/packages/project-build/src/mcp.test.tsindex ea7704c824..77d9d42abf 100644--- a/packages/project-build/src/mcp.test.ts+++ b/packages/project-build/src/mcp.test.ts@@ -247,6 +247,19 @@ describe("project session mcp adapter", () => {).toContain("vision.install-ocr");});+ test("lists import only when host provides importer", () => {+ expect(+ listProjectSessionMcpTools(publicMcpOperations).map((tool) => tool.name)+ ).not.toContain("import");+ const tools = listProjectSessionMcpTools(publicMcpOperations, {+ includeImport: true,+ });+ const importTool = tools.find((tool) => tool.name === "import");+ expect(importTool).toBeDefined();+ expect(importTool?.annotations.invalidatesNamespaces).toEqual([]);+ expect(tools.map((tool) => tool.name)).toContain("import");+ });+test("does not expose CLI-only required options as MCP tool schemas", () => {const operationWithCliOptions = {...publicMcpOperations[0]!,@@ -322,6 +335,67 @@ describe("project session mcp adapter", () => {});});+ test("calls import through injected project importer", async () => {+ const importProject = vi.fn(async () => ({ imported: true as const }));+ const adapter = createProjectSessionMcpCore({+ operations: publicMcpOperations,+ createProjectSession: createSessionFactory(),+ executeOperation: createExecuteOperation(),+ importProject,+ });++ const result = await adapter.callTool({+ name: "import",+ input: {+ to: "https://p-destination.wstd.dev/?authToken=token",+ assetsDir: "assets",+ ignoreVersionCheck: true,+ skipAssets: true,+ },+ });++ expect(importProject).toHaveBeenCalledWith({+ to: "https://p-destination.wstd.dev/?authToken=token",+ assetsDir: "assets",+ ignoreVersionCheck: true,+ skipAssets: true,+ });+ expect(result.structuredContent.data).toEqual({ imported: true });+ });++ test("includes import in capability index when importer is provided", async () => {+ const adapter = createProjectSessionMcpCore({+ operations: publicMcpOperations,+ createProjectSession: createSessionFactory(),+ executeOperation: createExecuteOperation(),+ importProject: vi.fn(async () => ({ imported: true as const })),+ });++ const index = await adapter.callTool({ name: "meta.index" });+ const capabilities = (+ index.structuredContent.data as {+ capabilities: { tools: string[] }[];+ }+ ).capabilities;++ expect(capabilities.flatMap((capability) => capability.tools)).toContain(+ "import"+ );+ });++ test("rejects import without destination share link", async () => {+ const adapter = createProjectSessionMcpCore({+ operations: publicMcpOperations,+ createProjectSession: createSessionFactory(),+ executeOperation: createExecuteOperation(),+ importProject: vi.fn(),+ });++ await expect(+ adapter.callTool({ name: "import", input: {} })+ ).rejects.toThrow("import requires destination share link in to.");+ });+test("delegates catalog operation tools without creating core session", async () => {const createProjectSession = createSessionFactory();const executeOperation: ExecuteOperation = vi.fn(async () =>@@ -1293,10 +1367,12 @@ describe("project session mcp adapter", () => {result: [{ id: "home" }],}));+ const importProject = vi.fn(async () => ({ imported: true as const }));const server = await createProjectSessionMcpServer({operations: publicMcpOperations,createProjectSession: createSessionFactory(session),executeOperation,+ importProject,});const { client, close } = await createConnectedClient(server);@@ -1328,6 +1404,26 @@ describe("project session mcp adapter", () => {input: { includeFolders: true },dryRun: false,});+ await expect(+ client.callTool({+ name: "import",+ arguments: {+ to: "https://p-destination.wstd.dev/?authToken=token",+ },+ })+ ).resolves.toEqual(+ expect.objectContaining({+ structuredContent: expect.objectContaining({+ data: { imported: true },+ }),+ })+ );+ expect(importProject).toHaveBeenCalledWith({+ to: "https://p-destination.wstd.dev/?authToken=token",+ assetsDir: undefined,+ ignoreVersionCheck: false,+ skipAssets: false,+ });await expect(client.readResource({ uri: "webstudio://project/status" })diff --git a/packages/project-build/src/mcp.ts b/packages/project-build/src/mcp.tsindex 00c06ad3f6..88fa3a5634 100644--- a/packages/project-build/src/mcp.ts+++ b/packages/project-build/src/mcp.ts@@ -136,6 +136,21 @@ type StartPreview = () => Promise<ProjectSessionPreviewResult>;type GetPreviewStatus = () => Promise<ProjectSessionPreviewResult>;+export type ProjectSessionImportInput = {+ to: string;+ assetsDir?: string;+ ignoreVersionCheck?: boolean;+ skipAssets?: boolean;+};++export type ProjectSessionImportResult = {+ imported: true;+};++type ImportProject = (+ input: ProjectSessionImportInput+) => Promise<ProjectSessionImportResult>;+export type ProjectSessionMcpGuidance = {visualVerificationRule: string;getVisionVerificationLoop: (options: {@@ -334,6 +349,34 @@ const previewInputSchema = {},} as const satisfies ProjectSessionMcpInputSchema;+const importInputSchema = {+ ...emptyInputSchema,+ description:+ "Import local .webstudio/data.json into another project using a destination share link with build permissions.",+ properties: {+ to: {+ type: "string",+ description: "Destination Builder share link with build permissions.",+ },+ assetsDir: {+ type: "string",+ description:+ "Directory containing local asset files referenced by the bundle.",+ },+ ignoreVersionCheck: {+ type: "boolean",+ description:+ "Import even when local bundle version differs from the current CLI/API contract.",+ },+ skipAssets: {+ type: "boolean",+ description:+ "Import project data without uploading or importing asset files.",+ },+ },+ required: ["to"],+} as const satisfies ProjectSessionMcpInputSchema;+export type ProjectSessionMcpTool = {name: string;description: string;@@ -360,6 +403,11 @@ export const mcpArgumentExamples: Record<string, readonly unknown[]> = {"meta.guide": [{ brief: "Create a pricing page and style the hero" }],"meta.get_more_tools": [{ brief: "update-styles" }],refresh: [{ namespaces: ["pages", "instances", "styles"] }],+ import: [+ {+ to: "https://p-destination-project-id.wstd.dev/?authToken=destination-token",+ },+ ],"preview.start": [{ host: "127.0.0.1", port: 5173 }],"preview.status": [{}],"list-pages": [{ includeFolders: true }],@@ -647,6 +695,27 @@ const installOcrTool = {},} as const satisfies ProjectSessionMcpTool;+const importTool = {+ name: "import",+ description:+ "Import the local synced project bundle into a destination project. Run sync first; pass a destination share link with build permissions.",+ inputSchema: importInputSchema,+ mcpExamples: getMcpExamples("import"),+ annotations: {+ command: "import",+ operationId: "project.import",+ method: "session",+ permit: "build",+ inputFields: ["to", "assetsDir", "ignoreVersionCheck", "skipAssets"],+ localCapable: false,+ serverOnly: true,+ readNamespaces: [],+ writeNamespaces: [],+ invalidatesNamespaces: [],+ retryOnConflict: false,+ },+} as const satisfies ProjectSessionMcpTool;+const previewTools = [{name: "preview.start",@@ -728,6 +797,7 @@ type SdkTool = {export const listProjectSessionMcpTools = (operations: readonly PublicMcpOperation[],options: {+ includeImport?: boolean;includeScreenshot?: boolean;includeScreenshotDiff?: boolean;includeInstallOcr?: boolean;@@ -759,6 +829,7 @@ export const listProjectSessionMcpTools = (...tool,mcpExamples: getMcpExamples(tool.name),})),+ ...(options.includeImport ? [importTool] : []),...(options.includeScreenshot ? [screenshotTool] : []),...(options.includeScreenshotDiff ? [screenshotDiffTool] : []),...(options.includeInstallOcr ? [installOcrTool] : []),@@ -802,6 +873,11 @@ const capabilityAreas = ["inspect",],},+ {+ area: "project-lifecycle",+ goal: "Refresh local project state and move synced project bundles between projects.",+ tools: ["refresh", "reset-session", "import"],+ },{area: "pages",goal: "Create, inspect, update, duplicate, delete, and organize pages and folders.",@@ -1364,10 +1440,30 @@ const getPreviewInput = (input: unknown): ProjectSessionPreviewInput => {};};+const getImportInput = (input: unknown): ProjectSessionImportInput => {+ if (isRecord(input) === false) {+ throw new Error("import input must be an object.");+ }+ if (typeof input.to !== "string" || input.to.length === 0) {+ throw new Error("import requires destination share link in to.");+ }+ const assetsDir =+ typeof input.assetsDir === "string" && input.assetsDir.length > 0+ ? input.assetsDir+ : undefined;+ return {+ to: input.to,+ assetsDir,+ ignoreVersionCheck: input.ignoreVersionCheck === true,+ skipAssets: input.skipAssets === true,+ };+};+export const createProjectSessionMcpCore = <Command extends string = string>({operations,createProjectSession,executeOperation,+ importProject,captureScreenshot,diffScreenshots,installOcr,@@ -1378,6 +1474,7 @@ export const createProjectSessionMcpCore = <Command extends string = string>({operations: readonly (PublicMcpOperation & { command: Command })[];createProjectSession: CreateProjectSession;executeOperation: ExecuteMcpOperation<Command>;+ importProject?: ImportProject;captureScreenshot?: CaptureScreenshot;diffScreenshots?: DiffScreenshots;installOcr?: InstallOcr;@@ -1391,6 +1488,7 @@ export const createProjectSessionMcpCore = <Command extends string = string>({);const listTools = () =>listProjectSessionMcpTools(operations, {+ includeImport: importProject !== undefined,includeScreenshot: captureScreenshot !== undefined,includeScreenshotDiff: diffScreenshots !== undefined,includeInstallOcr: installOcr !== undefined,@@ -1476,6 +1574,9 @@ export const createProjectSessionMcpCore = <Command extends string = string>({const session = getSession();return toCallResult(await session.reset());}+ if (name === "import" && importProject !== undefined) {+ return toMetaResult(await importProject(getImportInput(input)));+ }if (name === "screenshot" && captureScreenshot !== undefined) {return toMetaResult(await captureScreenshot(getScreenshotInput(input)));}@@ -1555,6 +1656,7 @@ export const createProjectSessionMcpServer = async <operations,createProjectSession,executeOperation,+ importProject,captureScreenshot,diffScreenshots,installOcr,@@ -1566,6 +1668,7 @@ export const createProjectSessionMcpServer = async <operations: readonly (PublicMcpOperation & { command: Command })[];createProjectSession: CreateProjectSession;executeOperation: ExecuteMcpOperation<Command>;+ importProject?: ImportProject;captureScreenshot?: CaptureScreenshot;diffScreenshots?: DiffScreenshots;installOcr?: InstallOcr;@@ -1578,6 +1681,7 @@ export const createProjectSessionMcpServer = async <operations,createProjectSession,executeOperation,+ importProject,captureScreenshot,diffScreenshots,installOcr,diff --git a/packages/sdk-components-animation/private-src b/packages/sdk-components-animation/private-srcindex 29181fed16..60076fa043 160000--- a/packages/sdk-components-animation/private-src+++ b/packages/sdk-components-animation/private-src@@ -1 +1 @@-Subproject commit 29181fed16686af08e67123a7931e8ef00a81f7d+Subproject commit 60076fa0430cb32866ca2bc0f16bae46fcae3262