Skip to content

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.

fix: restore Marketplace settings and optimize Assets publishing (#5964)

Oleg Isonen3ccb46cec782
diff --git a/apps/builder/app/builder/features/publish/content-database-publish-warning-view.tsx b/apps/builder/app/builder/features/publish/content-database-publish-warning-view.tsx
new file mode 100644
index 0000000000..7462210e44
--- /dev/null
+++ b/apps/builder/app/builder/features/publish/content-database-publish-warning-view.tsx
@@ -0,0 +1,45 @@
+import type { ContentDatabasePublishDiagnostics } from "~/services/content-database.server";
+
+export const ContentDatabasePublishWarning = ({
+ diagnostics,
+}: {
+ diagnostics: ContentDatabasePublishDiagnostics;
+}) => {
+ const { stats } = diagnostics;
+ const totalDocumentCount =
+ stats.includedDocumentCount + stats.omittedDocumentCount;
+ const omittedFileLabel = stats.omittedDocumentCount === 1 ? "file" : "files";
+ const dynamicResourceNames = diagnostics.affectedResources.flatMap(
+ ({ name, kind }) => (kind === "dynamic" ? [name] : [])
+ );
+ const staticResourceNames = diagnostics.affectedResources.flatMap(
+ ({ name, kind }) => (kind === "static" ? [name] : [])
+ );
+ return (
+ <>
+ The merged published content database will include{" "}
+ {stats.includedDocumentCount} of {totalDocumentCount} files (
+ {Math.ceil(stats.usedBytes / 1024)} of {Math.ceil(stats.maxBytes / 1024)}{" "}
+ KiB). {stats.omittedDocumentCount} {omittedFileLabel} will be omitted{" "}
+ {stats.omissionReason === "size"
+ ? "because the complete database exceeds the size limit"
+ : "because the required content could not be embedded"}
+ .
+ {dynamicResourceNames.length > 0 && (
+ <>
+ {" "}
+ Assets resources with route or variable values cannot be checked
+ exactly and may return incomplete results:{" "}
+ {dynamicResourceNames.join(", ")}.
+ </>
+ )}
+ {staticResourceNames.length > 0 && (
+ <>
+ {" "}
+ Potentially affected Assets resources:{" "}
+ {staticResourceNames.join(", ")}.
+ </>
+ )}
+ </>
+ );
+};
diff --git a/apps/builder/app/builder/features/publish/content-database-publish-warning.test.ts b/apps/builder/app/builder/features/publish/content-database-publish-warning.test.ts
index 215acc77dc..39d3b7cb27 100644
--- a/apps/builder/app/builder/features/publish/content-database-publish-warning.test.ts
+++ b/apps/builder/app/builder/features/publish/content-database-publish-warning.test.ts
@@ -1,67 +1,9 @@
import { describe, expect, test } from "vitest";
-import { getContentDatabasePublishWarning } from "./content-database-publish-warning";
+import { shouldShowContentDatabasePublishWarningToast } from "./content-database-publish-warning";
describe("content database publish warning", () => {
- test("reports bounded files and dynamic resources", () => {
- expect(
- getContentDatabasePublishWarning({
- stats: {
- usedBytes: 500 * 1024,
- maxBytes: 500 * 1024,
- includedDocumentCount: 80,
- omittedDocumentCount: 20,
- truncated: true,
- },
- potentiallyAffectedResources: [
- { id: "overview", name: "Blog overview" },
- { id: "detail", name: "Blog article" },
- ],
- hasDynamicValues: true,
- })
- ).toEqual({
- includedDocumentCount: 80,
- totalDocumentCount: 100,
- omittedDocumentCount: 20,
- usedKiB: 500,
- maxKiB: 500,
- affectedResourceNames: ["Blog overview", "Blog article"],
- affectedResourceKind: "dynamic",
- });
- });
-
- test("does not warn for a complete database", () => {
- expect(
- getContentDatabasePublishWarning({
- stats: {
- usedBytes: 100,
- maxBytes: 500 * 1024,
- includedDocumentCount: 5,
- omittedDocumentCount: 0,
- truncated: false,
- },
- potentiallyAffectedResources: [],
- hasDynamicValues: false,
- })
- ).toBeUndefined();
- });
-
- test("identifies statically affected resources", () => {
- expect(
- getContentDatabasePublishWarning({
- stats: {
- usedBytes: 1025,
- maxBytes: 2048,
- includedDocumentCount: 1,
- omittedDocumentCount: 1,
- truncated: true,
- },
- potentiallyAffectedResources: [{ id: "overview", name: "Overview" }],
- hasDynamicValues: false,
- })
- ).toMatchObject({
- usedKiB: 2,
- affectedResourceNames: ["Overview"],
- affectedResourceKind: "static",
- });
+ test("shows a toast only when the publish popover is closed", () => {
+ expect(shouldShowContentDatabasePublishWarningToast(false)).toBe(true);
+ expect(shouldShowContentDatabasePublishWarningToast(true)).toBe(false);
});
});
diff --git a/apps/builder/app/builder/features/publish/content-database-publish-warning.ts b/apps/builder/app/builder/features/publish/content-database-publish-warning.ts
deleted file mode 100644
index a7af779359..0000000000
--- a/apps/builder/app/builder/features/publish/content-database-publish-warning.ts
+++ /dev/null
@@ -1,48 +0,0 @@
-type ContentDatabasePublishDiagnostics = {
- stats: {
- usedBytes: number;
- maxBytes: number;
- includedDocumentCount: number;
- omittedDocumentCount: number;
- truncated: boolean;
- };
- potentiallyAffectedResources: { id: string; name: string }[];
- hasDynamicValues: boolean;
-};
-
-export type ContentDatabasePublishWarning = {
- includedDocumentCount: number;
- totalDocumentCount: number;
- omittedDocumentCount: number;
- usedKiB: number;
- maxKiB: number;
- affectedResourceNames: string[];
- affectedResourceKind: "dynamic" | "static" | undefined;
-};
-
-export const getContentDatabasePublishWarning = (
- diagnostics: ContentDatabasePublishDiagnostics | undefined
-) => {
- if (diagnostics?.stats.truncated !== true) {
- return;
- }
- const { stats } = diagnostics;
- const affectedResourceNames = diagnostics.potentiallyAffectedResources.map(
- ({ name }) => name
- );
- return {
- includedDocumentCount: stats.includedDocumentCount,
- totalDocumentCount:
- stats.includedDocumentCount + stats.omittedDocumentCount,
- omittedDocumentCount: stats.omittedDocumentCount,
- usedKiB: Math.ceil(stats.usedBytes / 1024),
- maxKiB: Math.ceil(stats.maxBytes / 1024),
- affectedResourceNames,
- affectedResourceKind:
- affectedResourceNames.length === 0
- ? undefined
- : diagnostics.hasDynamicValues
- ? "dynamic"
- : "static",
- } satisfies ContentDatabasePublishWarning;
-};
diff --git a/apps/builder/app/builder/features/publish/content-database-publish-warning.tsx b/apps/builder/app/builder/features/publish/content-database-publish-warning.tsx
new file mode 100644
index 0000000000..fd2b28fa03
--- /dev/null
+++ b/apps/builder/app/builder/features/publish/content-database-publish-warning.tsx
@@ -0,0 +1,38 @@
+import { toast } from "@webstudio-is/design-system";
+import type { Project } from "@webstudio-is/project";
+import { $publishDialog } from "../../shared/nano-states";
+import { nativeClient } from "~/shared/trpc/trpc-client";
+import { ContentDatabasePublishWarning } from "./content-database-publish-warning-view";
+
+export const shouldShowContentDatabasePublishWarningToast = (
+ isPublishPopoverOpen: boolean
+) => isPublishPopoverOpen === false;
+
+export const showContentDatabasePublishWarning = async ({
+ projectId,
+ setWarning,
+}: {
+ projectId: Project["id"];
+ setWarning: (warning: JSX.Element) => void;
+}) => {
+ const diagnostics =
+ await nativeClient.build.contentDatabasePublishDiagnostics.query({
+ projectId,
+ });
+ if (
+ diagnostics === undefined ||
+ diagnostics.stats.truncated === false ||
+ diagnostics.stats.omissionReason === undefined
+ ) {
+ return;
+ }
+ const message = <ContentDatabasePublishWarning diagnostics={diagnostics} />;
+ if (
+ shouldShowContentDatabasePublishWarningToast(
+ $publishDialog.get() !== "none"
+ )
+ ) {
+ toast.warn(message);
+ }
+ setWarning(message);
+};
diff --git a/apps/builder/app/builder/features/publish/publish.tsx b/apps/builder/app/builder/features/publish/publish.tsx
index cc0aa8ddea..41ad925100 100644
--- a/apps/builder/app/builder/features/publish/publish.tsx
+++ b/apps/builder/app/builder/features/publish/publish.tsx
@@ -75,10 +75,7 @@ import {
import { AddDomain } from "./add-domain";
import { humanizeString } from "~/shared/string-utils";
import { trpcClient, nativeClient } from "~/shared/trpc/trpc-client";
-import {
- createReachableAssetContentCompilationPlan,
- type Templates,
-} from "@webstudio-is/sdk";
+import type { Templates } from "@webstudio-is/sdk";
import { DomainCheckbox, domainToPublishName } from "./domain-checkbox";
import { CopyToClipboard } from "~/shared/copy-to-clipboard";
import { $openProjectSettings } from "~/shared/nano-states/project-settings";
@@ -105,10 +102,7 @@ import {
runPrePublishAudit,
type PrePublishAuditFinding,
} from "@webstudio-is/project-build/runtime";
-import {
- getContentDatabasePublishWarning,
- type ContentDatabasePublishWarning,
-} from "./content-database-publish-warning";
+import { showContentDatabasePublishWarning } from "./content-database-publish-warning";
const PrePublishAuditMessage = ({
finding,
@@ -190,64 +184,6 @@ const getPrePublishAuditMessages = () => {
};
};
-const loadContentDatabasePublishWarning = async (projectId: string) => {
- const plan = createReachableAssetContentCompilationPlan({
- props: [...$props.get().values()],
- dataSources: [...$dataSources.get().values()],
- resources: [...$resources.get().values()],
- });
- if (plan === undefined) {
- return;
- }
- return getContentDatabasePublishWarning(
- await nativeClient.build.contentDatabasePublishDiagnostics.query({
- projectId,
- })
- );
-};
-
-const ContentDatabasePublishWarningMessage = ({
- warning,
-}: {
- warning: ContentDatabasePublishWarning;
-}) => (
- <>
- The published content database will include {warning.includedDocumentCount}{" "}
- of {warning.totalDocumentCount} files ({warning.usedKiB} of {warning.maxKiB}{" "}
- KiB). {warning.omittedDocumentCount} files will be omitted.
- {warning.affectedResourceKind === "dynamic" && (
- <>
- {" "}
- Queries with route or variable values may be incomplete in:{" "}
- {warning.affectedResourceNames.join(", ")}.
- </>
- )}
- {warning.affectedResourceKind === "static" && (
- <>
- {" "}
- Potentially affected Assets resources:{" "}
- {warning.affectedResourceNames.join(", ")}.
- </>
- )}
- </>
-);
-
-const showContentDatabasePublishWarning = async ({
- projectId,
- setWarning,
-}: {
- projectId: Project["id"];
- setWarning: (warning: JSX.Element) => void;
-}) => {
- const warning = await loadContentDatabasePublishWarning(projectId);
- if (warning === undefined) {
- return;
- }
- const message = <ContentDatabasePublishWarningMessage warning={warning} />;
- toast.warn(message);
- setWarning(message);
-};
-
type ChangeProjectDomainProps = {
project: Project;
projectState: "idle" | "submitting";
diff --git a/apps/builder/app/builder/features/settings-panel/content-database-diagnostics.test.ts b/apps/builder/app/builder/features/settings-panel/content-database-diagnostics.test.ts
index 0d99654610..a2075c6a72 100644
--- a/apps/builder/app/builder/features/settings-panel/content-database-diagnostics.test.ts
+++ b/apps/builder/app/builder/features/settings-panel/content-database-diagnostics.test.ts
@@ -1,5 +1,8 @@
import { describe, expect, test } from "vitest";
-import { isDatabaseSizeNearLimit } from "./content-database-diagnostics";
+import {
+ getContentDatabaseDiagnosticRows,
+ isDatabaseSizeNearLimit,
+} from "./content-database-diagnostics";
describe("content database diagnostics", () => {
test("warns when the database reaches 90% of its limit", () => {
@@ -13,4 +16,43 @@ describe("content database diagnostics", () => {
true
);
});
+
+ test("shows query and merged published database sizes separately", () => {
+ expect(
+ getContentDatabaseDiagnosticRows({
+ scope: "query-preview",
+ query: {
+ usedBytes: 20_000,
+ maxBytes: 500_000,
+ unboundedBytes: 20_000,
+ includedDocumentCount: 5,
+ omittedDocumentCount: 0,
+ truncated: false,
+ },
+ database: {
+ usedBytes: 35_000,
+ maxBytes: 500_000,
+ unboundedBytes: 600_000,
+ includedDocumentCount: 5,
+ omittedDocumentCount: 1,
+ truncated: true,
+ },
+ })
+ ).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ label: "This query",
+ value: "20 kB",
+ }),
+ expect.objectContaining({
+ label: "Published database",
+ value: "35 kB",
+ }),
+ expect.objectContaining({
+ label: "Published database full size",
+ value: "600 kB",
+ }),
+ ])
+ );
+ });
});
diff --git a/apps/builder/app/builder/features/settings-panel/content-database-diagnostics.tsx b/apps/builder/app/builder/features/settings-panel/content-database-diagnostics.tsx
index 1f86e15e8d..1261e56667 100644
--- a/apps/builder/app/builder/features/settings-panel/content-database-diagnostics.tsx
+++ b/apps/builder/app/builder/features/settings-panel/content-database-diagnostics.tsx
@@ -12,57 +12,84 @@ const databaseSizeWarningRatio = 0.9;
export const isDatabaseSizeNearLimit = ({
usedBytes,
maxBytes,
-}: Pick<AssetQueryPreviewDiagnostics, "usedBytes" | "maxBytes">) =>
+}: Pick<AssetQueryPreviewDiagnostics["database"], "usedBytes" | "maxBytes">) =>
usedBytes >= maxBytes * databaseSizeWarningRatio;
+export const getContentDatabaseDiagnosticRows = (
+ value: AssetQueryPreviewDiagnostics
+) => [
+ {
+ label: "This query",
+ value: prettyBytes(value.query.usedBytes),
+ description:
+ "Temporary query-only footprint. It is not a separate allowance and is not added to the published database size.",
+ },
+ {
+ label: "This query full size",
+ value: prettyBytes(value.query.unboundedBytes),
+ },
+ {
+ label: "Published database",
+ value: prettyBytes(value.database.usedBytes),
+ description:
+ "Merged footprint of all reachable Assets queries. This is the size that counts toward the database limit.",
+ },
+ {
+ label: "Published database full size",
+ value: prettyBytes(value.database.unboundedBytes),
+ },
+];
+
export const ContentDatabaseDiagnostics = ({
value,
}: {
value: AssetQueryPreviewDiagnostics;
}) => {
const totalDocumentCount =
- value.includedDocumentCount + value.omittedDocumentCount;
+ value.database.includedDocumentCount + value.database.omittedDocumentCount;
const candidateFilesLabel = `${totalDocumentCount} candidate ${totalDocumentCount === 1 ? "file" : "files"}`;
- const omittedFilesLabel = `${value.omittedDocumentCount} ${value.omittedDocumentCount === 1 ? "file" : "files"}`;
- const isNearLimit = isDatabaseSizeNearLimit(value);
+ const omittedFilesLabel = `${value.database.omittedDocumentCount} ${value.database.omittedDocumentCount === 1 ? "file" : "files"}`;
+ const isNearLimit = isDatabaseSizeNearLimit(value.database);
+ const rows = getContentDatabaseDiagnosticRows(value);
return (
<RequestDiagnosticsContent>
- <PanelBanner variant={value.truncated ? "warning" : "success"}>
+ <PanelBanner variant={value.database.truncated ? "warning" : "success"}>
<Text>
- {value.truncated
- ? `${value.includedDocumentCount} of ${candidateFilesLabel} fit in the content database. ${omittedFilesLabel} may be omitted from published query results.`
+ {value.database.truncated
+ ? `${value.database.includedDocumentCount} of ${candidateFilesLabel} fit in the merged published content database. ${omittedFilesLabel} may be omitted from published query results.`
: totalDocumentCount === 1
- ? "The candidate file fits in the content database."
- : `All ${candidateFilesLabel} fit in the content database.`}
+ ? "The candidate file fits in the merged published content database."
+ : `All ${candidateFilesLabel} fit in the merged published content database.`}
</Text>
</PanelBanner>
<RequestDiagnosticsTable>
<RequestDiagnosticsRow label="Scope" value="Query preview" />
<RequestDiagnosticsRow
- label="Status"
- value={value.truncated ? "Truncated" : "Complete"}
- />
- <RequestDiagnosticsRow
- label="Database size"
- value={prettyBytes(value.usedBytes)}
- valueColor={isNearLimit ? "destructive" : undefined}
- description="To reduce the database size, select only the output fields your pages use, narrow filters to fewer files, and avoid full file content when a byte range is enough."
+ label="Published database status"
+ value={value.database.truncated ? "Truncated" : "Complete"}
/>
+ {rows.map((row) => (
+ <RequestDiagnosticsRow
+ key={row.label}
+ {...row}
+ valueColor={
+ row.label === "Published database" && isNearLimit
+ ? "destructive"
+ : undefined
+ }
+ />
+ ))}
<RequestDiagnosticsRow
label="Database limit"
- value={prettyBytes(value.maxBytes)}
- />
- <RequestDiagnosticsRow
- label="Estimated full size"
- value={prettyBytes(value.unboundedBytes)}
+ value={prettyBytes(value.database.maxBytes)}
/>
<RequestDiagnosticsRow
- label="Included files"
- value={value.includedDocumentCount}
+ label="Published included files"
+ value={value.database.includedDocumentCount}
/>
<RequestDiagnosticsRow
- label="Omitted files"
- value={value.omittedDocumentCount}
+ label="Published omitted files"
+ value={value.database.omittedDocumentCount}
/>
</RequestDiagnosticsTable>
</RequestDiagnosticsContent>
diff --git a/apps/builder/app/builder/shared/expression-editor.tsx b/apps/builder/app/builder/shared/expression-editor.tsx
index 338c06428d..d5bae17a2d 100644
--- a/apps/builder/app/builder/shared/expression-editor.tsx
+++ b/apps/builder/app/builder/shared/expression-editor.tsx
@@ -558,6 +558,12 @@ const linterTooltipTheme = EditorView.theme({
},
});
+const fullSizeEditorTheme = EditorView.theme({
+ ".cm-scroller": {
+ overflow: "auto",
+ },
+});
+
const expressionLinter = linter((view) => {
const [{ scope }] = view.state.facet(VariablesData);
return lintExpression({
@@ -657,8 +663,9 @@ export const ExpressionEditor = ({
keymap.of([...closeBracketsKeymap, ...completionKeymap]),
expressionLinter,
linterTooltipTheme,
+ ...(size === "full" ? [fullSizeEditorTheme] : []),
],
- [scopeWithUnsetVariables, aliasesWithUnsetVariables]
+ [scopeWithUnsetVariables, aliasesWithUnsetVariables, size]
);
// prevent clicking on autocomplete options propagating to body
diff --git a/apps/builder/app/builder/shared/query-builder.test.tsx b/apps/builder/app/builder/shared/query-builder.test.tsx
index 4d8e00908f..468c4062d1 100644
--- a/apps/builder/app/builder/shared/query-builder.test.tsx
+++ b/apps/builder/app/builder/shared/query-builder.test.tsx
@@ -29,9 +29,11 @@ afterEach(() => {
const renderQueryBuilder = <Query extends Record<string, unknown>>({
value,
capabilities,
+ sourceContainer,
}: {
value: Query;
capabilities: QueryDefinition<string, string>;
+ sourceContainer?: Element | null;
}) => {
const container = document.createElement("div");
document.body.appendChild(container);
@@ -43,6 +45,7 @@ const renderQueryBuilder = <Query extends Record<string, unknown>>({
capabilities={capabilities}
scope={scope}
aliases={aliases}
+ sourceContainer={sourceContainer}
onChange={() => {}}
/>
);
@@ -139,3 +142,31 @@ test("shows an evaluated value for a bound number input", () => {
expect(input?.step).toBe("1");
expect(input?.disabled).toBe(true);
});
+
+test("allows the full-size query source to scroll in both directions", () => {
+ const sourceContainer = document.createElement("div");
+ document.body.appendChild(sourceContainer);
+ const capabilities = {
+ version: 1,
+ fields: [],
+ operators: [],
+ source: {
+ fieldPathSchema: {
+ type: "array",
+ items: { type: "string" },
+ minItems: 1,
+ },
+ controls: [],
+ },
+ } as const satisfies QueryDefinition<string, string>;
+
+ renderQueryBuilder({
+ value: {},
+ capabilities,
+ sourceContainer,
+ });
+
+ const scroller = sourceContainer.querySelector(".cm-scroller");
+ expect(scroller).not.toBeNull();
+ expect(getComputedStyle(scroller as Element).overflow).toBe("auto");
+});
diff --git a/apps/builder/app/services/api-router.server.test.ts b/apps/builder/app/services/api-router.server.test.ts
index f2e004c385..035dc64c5f 100644
--- a/apps/builder/app/services/api-router.server.test.ts
+++ b/apps/builder/app/services/api-router.server.test.ts
@@ -21,6 +21,7 @@ import { blockComponent } from "@webstudio-is/sdk";
import { AssetIndexRevisionError } from "@webstudio-is/content-engine";
import * as assetUploader from "@webstudio-is/asset-uploader/server";
import { apiRouter, __testing__ } from "./api-router.server";
+import * as assetQueryPreview from "./asset-query-preview.server";
import {
getApiRouterProcedures,
getProcedureInputSchemaMetadata,
@@ -75,10 +76,62 @@ const createCaller = (context: AppContext) =>
apiRouter.createCaller(context) as ApiRouterCaller & RuntimeApiCaller;
describe("api router build operation adapters", () => {
+ test("submits only configured marketplace products for review", async () => {
+ vi.spyOn(authDb, "getTokenInfo").mockResolvedValue(createToken());
+ vi.spyOn(authorizeProject, "hasProjectPermit").mockResolvedValue(true);
+ const loadBuild = vi
+ .spyOn(projectBuild, "loadDevBuildByProjectId")
+ .mockResolvedValueOnce({ marketplaceProduct: undefined } as never)
+ .mockResolvedValueOnce({
+ marketplaceProduct: {
+ category: "pageTemplates",
+ name: "Acme Template",
+ thumbnailAssetId: "asset-id",
+ author: "Acme Studio",
+ email: "[email protected]",
+ website: "https://example.com",
+ issues: "",
+ description: "Reusable template project for Acme landing pages.",
+ },
+ } as never);
+ const setApprovalStatus = vi
+ .spyOn(projectApi, "setMarketplaceApprovalStatus")
+ .mockResolvedValue({ marketplaceApprovalStatus: "PENDING" } as never);
+ const caller = createCaller(createContext(true));
+
+ await expect(
+ caller.projects.submitMarketplaceProduct({
+ projectId: "project-1",
+ acknowledgePublicSubmission: true,
+ })
+ ).rejects.toThrow("Complete the marketplace product metadata");
+ expect(setApprovalStatus).not.toHaveBeenCalled();
+
+ await expect(
+ caller.projects.submitMarketplaceProduct({
+ projectId: "project-1",
+ acknowledgePublicSubmission: true,
+ })
+ ).resolves.toEqual({ marketplaceApprovalStatus: "PENDING" });
+ expect(loadBuild).toHaveBeenCalledTimes(2);
+ expect(setApprovalStatus).toHaveBeenCalledWith(
+ {
+ projectId: "project-1",
+ marketplaceApprovalStatus: "PENDING",
+ },
+ expect.anything()
+ );
+ });
+
test("exposes query validation and persisted asset query reads to API clients", async () => {
vi.spyOn(authDb, "getTokenInfo").mockResolvedValue(createToken());
vi.spyOn(authorizeProject, "hasProjectPermit").mockResolvedValue(true);
- vi.spyOn(assetUploader, "previewAssetResourceQuery").mockResolvedValue({
+ vi.spyOn(projectBuild, "loadDevBuildByProjectId").mockResolvedValue({
+ props: [],
+ dataSources: [],
+ resources: [],
+ } as never);
+ vi.spyOn(assetQueryPreview, "previewProjectAssetQuery").mockResolvedValue({
data: {
items: [{ id: "post" }],
totalCount: 1,
@@ -86,12 +139,22 @@ describe("api router build operation adapters", () => {
},
__diagnostics__: {
scope: "query-preview",
- usedBytes: 100,
- maxBytes: 512_000,
- unboundedBytes: 100,
- includedDocumentCount: 1,
- omittedDocumentCount: 0,
- truncated: false,
+ query: {
+ usedBytes: 100,
+ maxBytes: 512_000,
+ unboundedBytes: 100,
+ includedDocumentCount: 1,
+ omittedDocumentCount: 0,
+ truncated: false,
+ },
+ database: {
+ usedBytes: 200,
+ maxBytes: 512_000,
+ unboundedBytes: 200,
+ includedDocumentCount: 2,
+ omittedDocumentCount: 0,
+ truncated: false,
+ },
},
} as never);
vi.spyOn(assetUploader, "loadBuilderAssetFieldCatalog").mockResolvedValue({
@@ -159,12 +222,20 @@ describe("api router build operation adapters", () => {
items: [{ id: "post" }],
totalCount: 1,
},
- __diagnostics__: { scope: "query-preview", truncated: false },
+ __diagnostics__: {
+ scope: "query-preview",
+ query: { truncated: false },
+ database: { truncated: false },
+ },
});
- expect(assetUploader.previewAssetResourceQuery).toHaveBeenCalledWith(
- expect.objectContaining({ contentDatabaseMaxBytes: 512_000 })
- );
- vi.mocked(assetUploader.previewAssetResourceQuery).mockRejectedValueOnce(
+ expect(assetQueryPreview.previewProjectAssetQuery).toHaveBeenCalledWith({
+ projectId: "project-1",
+ request: expect.objectContaining({
+ query: expect.objectContaining({ limit: 10 }),
+ }),
+ context: expect.anything(),
+ });
+ vi.mocked(assetQueryPreview.previewProjectAssetQuery).mockRejectedValueOnce(
new AssetIndexRevisionError()
);
await expect(
diff --git a/apps/builder/app/services/api-router.server.ts b/apps/builder/app/services/api-router.server.ts
index e8b2db8e26..c92672e34b 100644
--- a/apps/builder/app/services/api-router.server.ts
+++ b/apps/builder/app/services/api-router.server.ts
@@ -7,7 +7,10 @@ import {
type AppContext,
type AuthPermit,
} from "@webstudio-is/trpc-interface/index.server";
-import { loadById } from "@webstudio-is/project/index.server";
+import {
+ loadById,
+ setMarketplaceApprovalStatus,
+} from "@webstudio-is/project/index.server";
import { loadDevBuildByProjectId } from "@webstudio-is/project-build/server";
import {
createProjectDomain,
@@ -37,7 +40,6 @@ import {
loadBuilderAssetFieldCatalog,
loadAssetDataByProject,
loadAssetFoldersByProject,
- previewAssetResourceQuery,
} from "@webstudio-is/asset-uploader/server";
import { buildPatchTransaction } from "@webstudio-is/protocol/schema";
import {
@@ -81,7 +83,7 @@ import {
executeApiRuntimeOperation,
} from "./api-runtime.server";
import { createAssetClient } from "../shared/asset-client";
-import { getContentDatabaseMaxBytes } from "./content-database.server";
+import { previewProjectAssetQuery } from "./asset-query-preview.server";
const assertApiPublishDomains = ({
auth,
@@ -652,6 +654,40 @@ export const apiRouter = router({
},
{ command: "inspect", client: "getProjectInfo" }
),
+
+ submitMarketplaceProduct: projectMutation(
+ projectIdInput.extend({
+ acknowledgePublicSubmission: z
+ .literal(true)
+ .describe(
+ "Acknowledge that submission starts public marketplace review"
+ ),
+ }),
+ "edit",
+ async ({ ctx, input }) => {
+ const build = await loadDevBuildByProjectId(ctx, input.projectId);
+ if (build.marketplaceProduct === undefined) {
+ return throwApiError(
+ "BAD_REQUEST",
+ "Complete the marketplace product metadata before submitting it for review"
+ );
+ }
+ const project = await setMarketplaceApprovalStatus(
+ {
+ projectId: input.projectId,
+ marketplaceApprovalStatus: "PENDING",
+ },
+ ctx
+ );
+ return {
+ marketplaceApprovalStatus: project.marketplaceApprovalStatus,
+ };
+ },
+ {
+ command: "submit-marketplace-product",
+ client: "submitMarketplaceProduct",
+ }
+ ),
}),
build: router({
@@ -760,12 +796,10 @@ export const apiRouter = router({
async ({ ctx, input }) => {
try {
const { projectId, ...request } = input;
- return await previewAssetResourceQuery({
+ return await previewProjectAssetQuery({
projectId,
request,
context: ctx,
- assetClient: createAssetClient(),
- contentDatabaseMaxBytes: getContentDatabaseMaxBytes(),
});
} catch (error) {
return throwAssetQueryApiError(error);
diff --git a/apps/builder/app/services/asset-query-preview.server.test.ts b/apps/builder/app/services/asset-query-preview.server.test.ts
new file mode 100644
index 0000000000..1a12b2e7a7
--- /dev/null
+++ b/apps/builder/app/services/asset-query-preview.server.test.ts
@@ -0,0 +1,51 @@
+import { describe, expect, test, vi } from "vitest";
+import { previewProjectAssetQuery } from "./asset-query-preview.server";
+
+describe("project asset query preview", () => {
+ test("previews against the current build content database plan", async () => {
+ const context = {} as never;
+ const build = {
+ props: [],
+ dataSources: [],
+ resources: [],
+ } as never;
+ const assetClient = { readFile: vi.fn(), uploadFile: vi.fn() } as never;
+ const result = { data: { items: [] } } as never;
+ const dependencies = {
+ createAssetClient: vi.fn(() => assetClient),
+ loadDevBuildByProjectId: vi.fn().mockResolvedValue(build),
+ previewAssetResourceQuery: vi.fn().mockResolvedValue(result),
+ };
+
+ await expect(
+ previewProjectAssetQuery(
+ {
+ projectId: "project-1",
+ request: { query: { limit: 5 } },
+ context,
+ },
+ dependencies
+ )
+ ).resolves.toBe(result);
+
+ expect(dependencies.loadDevBuildByProjectId).toHaveBeenCalledWith(
+ context,
+ "project-1"
+ );
+ expect(dependencies.previewAssetResourceQuery).toHaveBeenCalledWith({
+ projectId: "project-1",
+ request: { query: { limit: 5 } },
+ context,
+ assetClient,
+ contentDatabaseMaxBytes: 512_000,
+ databasePlan: expect.objectContaining({
+ queries: expect.arrayContaining([
+ expect.objectContaining({
+ id: "__query-preview__",
+ limit: { type: "literal", value: 5 },
+ }),
+ ]),
+ }),
+ });
+ });
+});
diff --git a/apps/builder/app/services/asset-query-preview.server.ts b/apps/builder/app/services/asset-query-preview.server.ts
new file mode 100644
index 0000000000..eb978d7a69
--- /dev/null
+++ b/apps/builder/app/services/asset-query-preview.server.ts
@@ -0,0 +1,39 @@
+import type { AssetQueryRequestInput } from "@webstudio-is/content-engine";
+import { previewAssetResourceQuery } from "@webstudio-is/asset-uploader/server";
+import { createAssetQueryPreviewCompilationPlan } from "@webstudio-is/project-build";
+import { loadDevBuildByProjectId } from "@webstudio-is/project-build/server";
+import type { AppContext } from "@webstudio-is/trpc-interface/index.server";
+import { createAssetClient } from "~/shared/asset-client";
+import { getContentDatabaseMaxBytes } from "./content-database.server";
+
+const defaultDependencies = {
+ createAssetClient,
+ loadDevBuildByProjectId,
+ previewAssetResourceQuery,
+};
+
+export const previewProjectAssetQuery = async (
+ {
+ projectId,
+ request,
+ context,
+ }: {
+ projectId: string;
+ request: AssetQueryRequestInput;
+ context: AppContext;
+ },
+ dependencies = defaultDependencies
+) => {
+ const build = await dependencies.loadDevBuildByProjectId(context, projectId);
+ return await dependencies.previewAssetResourceQuery({
+ projectId,
+ request,
+ context,
+ assetClient: dependencies.createAssetClient(),
+ contentDatabaseMaxBytes: getContentDatabaseMaxBytes(),
+ databasePlan: createAssetQueryPreviewCompilationPlan({
+ build,
+ query: request.query,
+ }),
+ });
+};
diff --git a/apps/builder/app/services/build-router.server.test.ts b/apps/builder/app/services/build-router.server.test.ts
index 45caa3a0e3..4292f94c9b 100644
--- a/apps/builder/app/services/build-router.server.test.ts
+++ b/apps/builder/app/services/build-router.server.test.ts
@@ -4,17 +4,11 @@ import { createPublishedProjectBundleFixture } from "@webstudio-is/protocol/fixt
import { buildRouter, __testing__ } from "./build-router.server";
import { authorizeProject } from "@webstudio-is/trpc-interface/index.server";
import { getApiCompatibilityPayload } from "@webstudio-is/trpc-interface/api-compatibility";
-import { createStructuredAssetQueryResourceBody } from "@webstudio-is/sdk";
-import {
- createAssetIndex,
- createCanonicalAssetFileEntry,
-} from "@webstudio-is/content-engine/compiler";
const {
assertCliBundleVersion,
createImportProjectBundleHandler,
prepareProjectBundleForClient,
- getContentDatabasePublishDiagnostics,
} = __testing__;
afterEach(() => {
@@ -82,87 +76,19 @@ describe("build router project bundle compatibility", () => {
});
describe("content database publish diagnostics", () => {
- test("reports bounded database stats and conservatively affected resources", async () => {
- const resourceId = "blog-posts";
- const createEntry = (id: string, bytes: number) =>
- createCanonicalAssetFileEntry({
- projectId: "source-project",
- document: {
- _id: id,
- _type: "asset.file",
- name: `${id}.md`,
- path: `blog/${id}.md`,
- key: id,
- extension: "md",
- mimeType: "text/markdown",
- size: bytes,
- revision: `revision-${id}`,
- contentRef: `files/${id}.md`,
- properties: { value: "x".repeat(bytes) },
- },
- });
- const assetIndex = await createAssetIndex({
- projectId: "source-project",
- entries: [createEntry("small", 100), createEntry("large", 10_000)],
- maxBytes: 5_000,
- });
- const bundle = createPublishedProjectBundleFixture({
- build: {
- props: [
- [
- "posts-prop",
- {
- id: "posts-prop",
- instanceId: "collection",
- name: "data",
- type: "resource",
- value: resourceId,
- },
- ],
- ],
- resources: [
- [
- resourceId,
- {
- id: resourceId,
- name: "Blog posts",
- control: "system",
- method: "post",
- url: '"/$resources/assets"',
- headers: [],
- body: createStructuredAssetQueryResourceBody({
- where: { all: [] },
- sort: [],
- limit: "pageSize",
- offset: "0",
- output: { mode: "base", includeMetadata: true },
- content: { mode: "none" },
- }),
- },
- ],
- ],
- },
- assetIndex,
- });
-
- expect(getContentDatabasePublishDiagnostics(bundle)).toMatchObject({
- stats: {
- maxBytes: 5_000,
- includedDocumentCount: 1,
- omittedDocumentCount: 1,
- truncated: true,
- },
- potentiallyAffectedResources: [{ id: resourceId, name: "Blog posts" }],
- hasDynamicValues: true,
- });
- });
+ test("uses the same edit permit as publishing", async () => {
+ const hasProjectPermit = vi
+ .spyOn(authorizeProject, "hasProjectPermit")
+ .mockResolvedValue(false);
+ const caller = buildRouter.createCaller({} as never);
- test("does nothing when the build has no content query", () => {
- expect(
- getContentDatabasePublishDiagnostics(
- createPublishedProjectBundleFixture()
- )
- ).toBeUndefined();
+ await expect(
+ caller.contentDatabasePublishDiagnostics({ projectId: "project-id" })
+ ).rejects.toThrow("permission to edit this project");
+ expect(hasProjectPermit).toHaveBeenCalledWith(
+ { projectId: "project-id", permit: "edit" },
+ expect.anything()
+ );
});
});
diff --git a/apps/builder/app/services/build-router.server.ts b/apps/builder/app/services/build-router.server.ts
index e7ee007553..429262c6e6 100644
--- a/apps/builder/app/services/build-router.server.ts
+++ b/apps/builder/app/services/build-router.server.ts
@@ -23,11 +23,6 @@ import { loadDevBuildByProjectId } from "@webstudio-is/project-build/server";
import { parseWebstudioJsxFragment } from "@webstudio-is/project-build/transfer/server";
import { serializePages } from "@webstudio-is/project-migrations/pages";
import { loadAssetDataByProject } from "@webstudio-is/asset-uploader/server";
-import {
- createContentDatabase,
- hasDynamicContentCompilationValues,
-} from "@webstudio-is/content-engine";
-import { createReachableAssetContentCompilationPlan } from "@webstudio-is/sdk";
import {
checkProjectBuildPermissionInput,
importProjectBundleInput,
@@ -55,6 +50,7 @@ import {
commitBuildTransactions,
} from "./api-build.server";
import { assertApiProjectPermit } from "./api-permits.server";
+import { getContentDatabasePublishDiagnostics } from "./content-database.server";
const projectBundleInput = z.object({
projectId: z.string(),
@@ -66,36 +62,6 @@ const buildBundleInput = z.object({
bundleVersion: z.union([z.string(), z.number()]).optional(),
});
-const getContentDatabasePublishDiagnostics = (
- bundle: z.infer<typeof publishedProjectBundle>
-) => {
- if (bundle.assetIndex === undefined) {
- return;
- }
- const plan = createReachableAssetContentCompilationPlan({
- props: bundle.build.props.map(([, prop]) => prop),
- dataSources: bundle.build.dataSources.map(([, dataSource]) => dataSource),
- resources: bundle.build.resources.map(([, resource]) => resource),
- });
- if (plan === undefined) {
- return;
- }
- const resourceNameById = new Map(
- bundle.build.resources.map(([, resource]) => [resource.id, resource.name])
- );
- const stats = createContentDatabase({
- artifact: bundle.assetIndex,
- }).getStats();
- return {
- stats,
- potentiallyAffectedResources: plan.queries.map(({ id }) => ({
- id,
- name: resourceNameById.get(id) ?? id,
- })),
- hasDynamicValues: hasDynamicContentCompilationValues(plan),
- };
-};
-
const assertCliBundleVersion = (
ctx: AppContext,
clientBundleVersion: string | number | undefined
@@ -323,7 +289,15 @@ export const buildRouter = router({
contentDatabasePublishDiagnostics: procedure
.input(z.object({ projectId: z.string() }))
.query(async ({ ctx, input }) => {
- await assertProjectBuildPermit({ ctx, projectId: input.projectId });
+ const canEdit = await authorizeProject.hasProjectPermit(
+ { projectId: input.projectId, permit: "edit" },
+ ctx
+ );
+ if (canEdit === false) {
+ throw new AuthorizationError(
+ "You don't have permission to edit this project."
+ );
+ }
return getContentDatabasePublishDiagnostics(
await loadProjectBundleByProjectId(input.projectId, ctx)
);
@@ -457,5 +431,4 @@ export const __testing__ = {
createImportProjectBundleHandler,
assertCliBundleVersion,
prepareProjectBundleForClient,
- getContentDatabasePublishDiagnostics,
};
diff --git a/apps/builder/app/services/content-database.server.test.ts b/apps/builder/app/services/content-database.server.test.ts
new file mode 100644
index 0000000000..a4466a1a89
--- /dev/null
+++ b/apps/builder/app/services/content-database.server.test.ts
@@ -0,0 +1,199 @@
+import { describe, expect, test } from "vitest";
+import { createPublishedProjectBundleFixture } from "@webstudio-is/protocol/fixtures";
+import { createStructuredAssetQueryResourceBody } from "@webstudio-is/sdk";
+import {
+ compileContentArtifact,
+ createAssetIndex,
+ createCanonicalAssetFileEntry,
+} from "@webstudio-is/content-engine/compiler";
+import { getContentDatabasePublishDiagnostics } from "./content-database.server";
+
+describe("content database publish diagnostics", () => {
+ test("classifies affected dynamic and static resources individually", async () => {
+ const resourceId = "blog-posts";
+ const overviewResourceId = "blog-overview";
+ const createEntry = (id: string, bytes: number) =>
+ createCanonicalAssetFileEntry({
+ projectId: "source-project",
+ document: {
+ _id: id,
+ _type: "asset.file",
+ name: `${id}.md`,
+ path: `blog/${id}.md`,
+ key: id,
+ extension: "md",
+ mimeType: "text/markdown",
+ size: bytes,
+ revision: `revision-${id}`,
+ contentRef: `files/${id}.md`,
+ properties: { value: "x".repeat(bytes) },
+ },
+ });
+ const assetIndex = await createAssetIndex({
+ projectId: "source-project",
+ entries: [createEntry("small", 100), createEntry("large", 10_000)],
+ maxBytes: 5_000,
+ });
+ const bundle = createPublishedProjectBundleFixture({
+ build: {
+ props: [
+ [
+ "posts-prop",
+ {
+ id: "posts-prop",
+ instanceId: "collection",
+ name: "data",
+ type: "resource",
+ value: resourceId,
+ },
+ ],
+ [
+ "overview-prop",
+ {
+ id: "overview-prop",
+ instanceId: "collection",
+ name: "overview",
+ type: "resource",
+ value: overviewResourceId,
+ },
+ ],
+ ],
+ resources: [
+ [
+ resourceId,
+ {
+ id: resourceId,
+ name: "Blog posts",
+ control: "system",
+ method: "post",
+ url: '"/$resources/assets"',
+ headers: [],
+ body: createStructuredAssetQueryResourceBody({
+ where: { all: [] },
+ sort: [],
+ limit: "pageSize",
+ offset: "0",
+ output: { mode: "base", includeMetadata: true },
+ content: { mode: "none" },
+ }),
+ },
+ ],
+ [
+ overviewResourceId,
+ {
+ id: overviewResourceId,
+ name: "Blog overview",
+ control: "system",
+ method: "post",
+ url: '"/$resources/assets"',
+ headers: [],
+ body: createStructuredAssetQueryResourceBody({
+ where: { all: [] },
+ sort: [],
+ limit: "10",
+ offset: "0",
+ output: { mode: "base", includeMetadata: true },
+ content: { mode: "none" },
+ }),
+ },
+ ],
+ ],
+ },
+ assetIndex,
+ });
+
+ expect(getContentDatabasePublishDiagnostics(bundle)).toMatchObject({
+ stats: {
+ includedDocumentCount: 1,
+ omittedDocumentCount: 1,
+ maxBytes: 5_000,
+ omissionReason: "size",
+ truncated: true,
+ },
+ affectedResources: [
+ { name: "Blog posts", kind: "dynamic" },
+ { name: "Blog overview", kind: "static" },
+ ],
+ });
+ });
+
+ test("does nothing when the build has no content query", () => {
+ expect(
+ getContentDatabasePublishDiagnostics(
+ createPublishedProjectBundleFixture()
+ )
+ ).toBeUndefined();
+ });
+
+ test("reports unavailable content for affected static resources", async () => {
+ const resourceId = "blog-overview";
+ const { artifact: assetIndex } = await compileContentArtifact({
+ projectId: "source-project",
+ entries: [
+ {
+ ...createCanonicalAssetFileEntry({
+ projectId: "source-project",
+ document: {
+ _id: "post",
+ _type: "asset.file",
+ name: "post.md",
+ path: "blog/post.md",
+ key: "post",
+ extension: "md",
+ mimeType: "text/markdown",
+ size: 100,
+ revision: "revision-post",
+ contentRef: "files/post.md",
+ properties: {},
+ },
+ }),
+ contentRequired: true,
+ },
+ ],
+ maxBytes: 5_000,
+ });
+ const bundle = createPublishedProjectBundleFixture({
+ build: {
+ props: [
+ [
+ "overview-prop",
+ {
+ id: "overview-prop",
+ instanceId: "collection",
+ name: "data",
+ type: "resource",
+ value: resourceId,
+ },
+ ],
+ ],
+ resources: [
+ [
+ resourceId,
+ {
+ id: resourceId,
+ name: "Blog overview",
+ control: "system",
+ method: "post",
+ url: '"/$resources/assets"',
+ headers: [],
+ body: createStructuredAssetQueryResourceBody({
+ where: { all: [] },
+ sort: [],
+ limit: "10",
+ offset: "0",
+ output: { mode: "base", includeMetadata: true },
+ content: { mode: "none" },
+ }),
+ },
+ ],
+ ],
+ },
+ assetIndex,
+ });
+
+ expect(getContentDatabasePublishDiagnostics(bundle)).toMatchObject({
+ stats: { omissionReason: "unavailable", truncated: true },
+ affectedResources: [{ name: "Blog overview", kind: "static" }],
+ });
+ });
+});
diff --git a/apps/builder/app/services/content-database.server.ts b/apps/builder/app/services/content-database.server.ts
index bed2abf24c..4fa1246959 100644
--- a/apps/builder/app/services/content-database.server.ts
+++ b/apps/builder/app/services/content-database.server.ts
@@ -1,4 +1,36 @@
import { parseContentDatabaseMaxBytes } from "@webstudio-is/content-engine";
+import { getContentDatabasePublishDiagnostics as analyzeContentDatabasePublish } from "@webstudio-is/project-build";
+import type { PublishedProjectBundle } from "@webstudio-is/protocol";
export const getContentDatabaseMaxBytes = () =>
parseContentDatabaseMaxBytes(process.env.CONTENT_DATABASE_MAX_BYTES);
+
+export type ContentDatabasePublishDiagnostics = {
+ stats: NonNullable<ReturnType<typeof analyzeContentDatabasePublish>>["stats"];
+ affectedResources: Array<{
+ name: string;
+ kind: "dynamic" | "static";
+ }>;
+};
+
+export const getContentDatabasePublishDiagnostics = (
+ bundle: PublishedProjectBundle
+): ContentDatabasePublishDiagnostics | undefined => {
+ const diagnostics = analyzeContentDatabasePublish({
+ build: bundle.build,
+ artifact: bundle.assetIndex,
+ });
+ if (diagnostics === undefined) {
+ return;
+ }
+ const resourceNameById = new Map(
+ bundle.build.resources.map(([, resource]) => [resource.id, resource.name])
+ );
+ return {
+ stats: diagnostics.stats,
+ affectedResources: diagnostics.queries.map(({ id, kind }) => ({
+ name: resourceNameById.get(id) ?? id,
+ kind,
+ })),
+ };
+};
diff --git a/apps/builder/app/shared/$resources/assets-query.server.test.ts b/apps/builder/app/shared/$resources/assets-query.server.test.ts
index fe889511cc..8142e39655 100644
--- a/apps/builder/app/shared/$resources/assets-query.server.test.ts
+++ b/apps/builder/app/shared/$resources/assets-query.server.test.ts
@@ -10,8 +10,7 @@ import { executeAssetQuery } from "./assets-query.server";
const projectId = "090e6e14-ae50-4b2e-bd22-71733cec05bb";
const dependencies = {
authorizeApiProject: vi.fn(),
- createAssetClient: vi.fn(() => ({ readFile: vi.fn() })),
- previewAssetResourceQuery: vi.fn(),
+ previewProjectAssetQuery: vi.fn(),
preventCrossOriginCookie: vi.fn(),
};
const outerRequest = () =>
@@ -25,7 +24,7 @@ const innerRequest = (body: unknown) =>
describe("configured Assets system resource", () => {
beforeEach(() => {
dependencies.authorizeApiProject.mockResolvedValue({} as never);
- dependencies.previewAssetResourceQuery.mockReset();
+ dependencies.previewProjectAssetQuery.mockReset();
});
test("uses the outer authentication context and typed inner request", async () => {
@@ -37,15 +36,25 @@ describe("configured Assets system resource", () => {
},
__diagnostics__: {
scope: "query-preview",
- usedBytes: 100,
- maxBytes: 512_000,
- unboundedBytes: 100,
- includedDocumentCount: 1,
- omittedDocumentCount: 0,
- truncated: false,
+ query: {
+ usedBytes: 100,
+ maxBytes: 512_000,
+ unboundedBytes: 100,
+ includedDocumentCount: 1,
+ omittedDocumentCount: 0,
+ truncated: false,
+ },
+ database: {
+ usedBytes: 200,
+ maxBytes: 512_000,
+ unboundedBytes: 200,
+ includedDocumentCount: 2,
+ omittedDocumentCount: 0,
+ truncated: false,
+ },
},
};
- dependencies.previewAssetResourceQuery.mockResolvedValue(responseBody);
+ dependencies.previewProjectAssetQuery.mockResolvedValue(responseBody);
const query = {
where: {
all: [
@@ -71,7 +80,7 @@ describe("configured Assets system resource", () => {
projectId,
"view"
);
- expect(dependencies.previewAssetResourceQuery).toHaveBeenCalledWith({
+ expect(dependencies.previewProjectAssetQuery).toHaveBeenCalledWith({
projectId,
request: {
query: expect.objectContaining({
@@ -82,22 +91,30 @@ describe("configured Assets system resource", () => {
}),
},
context: expect.anything(),
- assetClient: expect.objectContaining({ readFile: expect.any(Function) }),
- contentDatabaseMaxBytes: 512_000,
});
});
test("supports the public REST URL with an explicit project", async () => {
- dependencies.previewAssetResourceQuery.mockResolvedValue({
+ dependencies.previewProjectAssetQuery.mockResolvedValue({
data: { items: [], totalCount: 0, hasMore: false },
__diagnostics__: {
scope: "query-preview",
- usedBytes: 100,
- maxBytes: 512_000,
- unboundedBytes: 100,
- includedDocumentCount: 0,
- omittedDocumentCount: 0,
- truncated: false,
+ query: {
+ usedBytes: 100,
+ maxBytes: 512_000,
+ unboundedBytes: 100,
+ includedDocumentCount: 0,
+ omittedDocumentCount: 0,
+ truncated: false,
+ },
+ database: {
+ usedBytes: 100,
+ maxBytes: 512_000,
+ unboundedBytes: 100,
+ includedDocumentCount: 0,
+ omittedDocumentCount: 0,
+ truncated: false,
+ },
},
});
const request = new Request(
@@ -132,7 +149,7 @@ describe("configured Assets system resource", () => {
error: { code: "INVALID_REQUEST" },
});
- dependencies.previewAssetResourceQuery.mockRejectedValue(
+ dependencies.previewProjectAssetQuery.mockRejectedValue(
new AuthorizationError("denied")
);
const forbidden = await executeAssetQuery(
@@ -187,7 +204,7 @@ describe("configured Assets system resource", () => {
);
expect(malformed.status).toBe(400);
- dependencies.previewAssetResourceQuery.mockRejectedValueOnce(
+ dependencies.previewProjectAssetQuery.mockRejectedValueOnce(
new AssetQueryExecutionError("Invalid pagination")
);
const invalid = await executeAssetQuery(
@@ -201,7 +218,7 @@ describe("configured Assets system resource", () => {
});
test("maps stale revisions to conflict responses", async () => {
- dependencies.previewAssetResourceQuery.mockRejectedValue(
+ dependencies.previewProjectAssetQuery.mockRejectedValue(
new AssetIndexRevisionError()
);
diff --git a/apps/builder/app/shared/$resources/assets-query.server.ts b/apps/builder/app/shared/$resources/assets-query.server.ts
index b5b2c3d284..d1c144b1ac 100644
--- a/apps/builder/app/shared/$resources/assets-query.server.ts
+++ b/apps/builder/app/shared/$resources/assets-query.server.ts
@@ -3,7 +3,6 @@ import {
getAssetResourceQueryError,
readAssetQueryRequest,
} from "@webstudio-is/content-engine";
-import { previewAssetResourceQuery } from "@webstudio-is/asset-uploader/server";
import { privateNoStoreResponseHeaders } from "~/services/cache-control.server";
import {
authorizeApiProject,
@@ -11,24 +10,18 @@ import {
} from "~/services/api-auth.server";
import { getAssetRestProjectId } from "~/services/asset-rest.server";
import { preventCrossOriginCookie } from "~/services/no-cross-origin-cookie";
-import { getContentDatabaseMaxBytes } from "~/services/content-database.server";
-import { createAssetClient } from "../asset-client";
+import { previewProjectAssetQuery } from "~/services/asset-query-preview.server";
import { createAssetResourceFailureResponse } from "./assets-response.server";
type Dependencies = {
authorizeApiProject: typeof authorizeApiProject;
- createAssetClient: () => Pick<
- ReturnType<typeof createAssetClient>,
- "readFile"
- >;
- previewAssetResourceQuery: typeof previewAssetResourceQuery;
+ previewProjectAssetQuery: typeof previewProjectAssetQuery;
preventCrossOriginCookie: typeof preventCrossOriginCookie;
};
const defaultDependencies: Dependencies = {
authorizeApiProject,
- createAssetClient,
- previewAssetResourceQuery,
+ previewProjectAssetQuery,
preventCrossOriginCookie,
};
@@ -70,12 +63,10 @@ export const executeAssetQuery = async (
projectId,
"view"
);
- const result = await dependencies.previewAssetResourceQuery({
+ const result = await dependencies.previewProjectAssetQuery({
projectId,
request: parsed,
context,
- assetClient: dependencies.createAssetClient(),
- contentDatabaseMaxBytes: getContentDatabaseMaxBytes(),
});
return json(result, { headers: privateNoStoreResponseHeaders });
} catch (error) {
diff --git a/apps/builder/app/shared/db/canvas.server.ts b/apps/builder/app/shared/db/canvas.server.ts
index 995611a8cb..f2f27f8b22 100644
--- a/apps/builder/app/shared/db/canvas.server.ts
+++ b/apps/builder/app/shared/db/canvas.server.ts
@@ -7,16 +7,15 @@ import {
loadBuildById,
loadDevBuildByProjectId,
} from "@webstudio-is/project-build/server";
+import { createBuildContentCompilationPlan } from "@webstudio-is/project-build";
import { collectFontFamiliesFromStyleDecls } from "@webstudio-is/project-build/runtime";
import {
loadAssetDataByProject,
- PostgresAssetRepository,
+ preparePublishedAssetData,
} from "@webstudio-is/asset-uploader/server";
import type { AppContext } from "@webstudio-is/trpc-interface/index.server";
-import { getContentArtifactRuntimeAssetIds } from "@webstudio-is/content-engine";
import {
findPageByIdOrPath,
- createReachableAssetContentCompilationPlan,
getAllPages,
getStyleDeclKey,
type Asset,
@@ -160,58 +159,24 @@ const addProjectMetadata = async (
? undefined
: await getUserById(context, project.userId);
- const assetRequirements = createReachableAssetContentCompilationPlan({
- props: data.build.props.map(([, prop]) => prop),
- dataSources: data.build.dataSources.map(([, dataSource]) => dataSource),
- resources: data.build.resources.map(([, resource]) => resource),
- });
+ const assetRequirements = createBuildContentCompilationPlan(data.build);
let assetIndex: PublishedProjectBundle["assetIndex"];
let publishedAssets = data.assets;
let publishedAssetFolders = data.assetFolders;
if (assetRequirements !== undefined) {
- const assetClient = createAssetClient();
- const assetRepository = new PostgresAssetRepository({
+ const publishedAssetData = await preparePublishedAssetData({
projectId: project.id,
context,
- assetStore: assetClient,
+ assetStore: createAssetClient(),
contentDatabaseMaxBytes: getContentDatabaseMaxBytes(),
- });
- const retainedFontIds = new Set(
- data.assets
+ plan: assetRequirements,
+ retainedAssetIds: data.assets
.filter((asset) => asset.type === "font")
- .map((asset) => asset.id)
- );
- for (let attempt = 0; attempt < 2; attempt += 1) {
- const assetDataBefore = await loadAssetDataByProject(project.id, context);
- const preparedIndex =
- await assetRepository.prepareIndex(assetRequirements);
- const assetDataAfter = await loadAssetDataByProject(project.id, context);
- const assetsStayedStable =
- JSON.stringify(assetDataBefore) === JSON.stringify(assetDataAfter);
- if (assetsStayedStable === false) {
- if (attempt === 0) {
- continue;
- }
- throw new Error("Assets changed while preparing publication; retry");
- }
- assetIndex = preparedIndex;
- const retainedRuntimeAssetIds = new Set(retainedFontIds);
- for (const assetId of getContentArtifactRuntimeAssetIds({
- artifact: preparedIndex,
- includeDocuments: true,
- })) {
- retainedRuntimeAssetIds.add(assetId);
- }
- publishedAssets = assetDataAfter.assets.filter(
- (asset) =>
- asset.type !== "font" || retainedRuntimeAssetIds.has(asset.id)
- );
- publishedAssetFolders = assetDataAfter.assetFolders;
- break;
- }
- if (assetIndex === undefined) {
- throw new Error("Asset index was not prepared");
- }
+ .map((asset) => asset.id),
+ });
+ assetIndex = publishedAssetData.artifact;
+ publishedAssets = publishedAssetData.assets;
+ publishedAssetFolders = publishedAssetData.assetFolders;
}
return {
diff --git a/apps/builder/app/shared/project-settings/section-marketplace.tsx b/apps/builder/app/shared/project-settings/section-marketplace.tsx
index 6899f95041..b8ef46e313 100644
--- a/apps/builder/app/shared/project-settings/section-marketplace.tsx
+++ b/apps/builder/app/shared/project-settings/section-marketplace.tsx
@@ -62,7 +62,7 @@ const defaultMarketplaceProduct: Partial<MarketplaceProduct> = {
category: "sectionTemplates",
};
-const validate = (data: MarketplaceProduct) => {
+const validate = (data: Partial<MarketplaceProduct>) => {
const parsedResult = marketplaceProductUpdateInput.safeParse(data);
if (parsedResult.success === false) {
return parsedResult.error.flatten().fieldErrors;
@@ -124,7 +124,10 @@ const useMarketplaceApprovalStatus = () => {
export const SectionMarketplace = () => {
const project = useStore($project);
const approval = useMarketplaceApprovalStatus();
- const [data, setData] = useState(() => $marketplaceProduct.get());
+ const [data, setData] = useState<Partial<MarketplaceProduct>>(() => ({
+ ...defaultMarketplaceProduct,
+ ...$marketplaceProduct.get(),
+ }));
const ids = useIds([
"name",
"category",
@@ -139,10 +142,11 @@ export const SectionMarketplace = () => {
const [isConfirmed, setIsConfirmed] = useState<boolean>(false);
const [errors, setErrors] = useState<ReturnType<typeof validate>>();
- if (data === undefined || project === undefined) {
+ if (project === undefined) {
return;
}
const asset = assets.get(data.thumbnailAssetId ?? "");
+ const isValid = marketplaceProductUpdateInput.safeParse(data).success;
const handleSave = <Setting extends keyof MarketplaceProduct>(
setting: Setting
@@ -160,9 +164,13 @@ export const SectionMarketplace = () => {
if (errors) {
return;
}
+ const result = marketplaceProductUpdateInput.safeParse(nextData);
+ if (result.success === false) {
+ return;
+ }
executeRuntimeMutation({
id: "projectSettings.updateMarketplaceProduct",
- input: nextData,
+ input: result.data,
});
};
};
@@ -337,7 +345,7 @@ export const SectionMarketplace = () => {
{approval.status === "UNLISTED" ? (
<Button
color="primary"
- disabled={isConfirmed === false || errors !== undefined}
+ disabled={isConfirmed === false || isValid === false}
state={approval.state === "idle" ? undefined : "pending"}
onClick={approval.submit}
>
diff --git a/apps/builder/app/shared/resource-diagnostics.test.ts b/apps/builder/app/shared/resource-diagnostics.test.ts
index 41fec6aa9c..9d00b0ed33 100644
--- a/apps/builder/app/shared/resource-diagnostics.test.ts
+++ b/apps/builder/app/shared/resource-diagnostics.test.ts
@@ -20,12 +20,22 @@ describe("resource diagnostics", () => {
meta: { totalCount: 1, hasMore: false },
__diagnostics__: {
scope: "query-preview",
- usedBytes: 100,
- maxBytes: 500,
- unboundedBytes: 700,
- includedDocumentCount: 80,
- omittedDocumentCount: 20,
- truncated: true,
+ query: {
+ usedBytes: 100,
+ maxBytes: 500,
+ unboundedBytes: 100,
+ includedDocumentCount: 1,
+ omittedDocumentCount: 0,
+ truncated: false,
+ },
+ database: {
+ usedBytes: 500,
+ maxBytes: 500,
+ unboundedBytes: 700,
+ includedDocumentCount: 80,
+ omittedDocumentCount: 20,
+ truncated: true,
+ },
},
},
});
@@ -37,9 +47,12 @@ describe("resource diagnostics", () => {
});
expect(separated.result).not.toHaveProperty("__diagnostics__");
expect(separated.diagnostics).toMatchObject({
- includedDocumentCount: 80,
- omittedDocumentCount: 20,
- truncated: true,
+ query: { includedDocumentCount: 1, truncated: false },
+ database: {
+ includedDocumentCount: 80,
+ omittedDocumentCount: 20,
+ truncated: true,
+ },
});
});
diff --git a/apps/builder/app/shared/sync/builder-patch.test.ts b/apps/builder/app/shared/sync/builder-patch.test.ts
index f02fc23bed..8d4dea1bb8 100644
--- a/apps/builder/app/shared/sync/builder-patch.test.ts
+++ b/apps/builder/app/shared/sync/builder-patch.test.ts
@@ -1,7 +1,10 @@
import { describe, expect, test } from "vitest";
import type { Instance, WebstudioData } from "@webstudio-is/sdk";
import { createDefaultPages } from "@webstudio-is/project-build";
-import type { ProjectSettings } from "@webstudio-is/project-build";
+import type {
+ MarketplaceProduct,
+ ProjectSettings,
+} from "@webstudio-is/project-build";
import type { BuilderPatchChange } from "@webstudio-is/project-build/contracts";
import {
createSyncChangesFromBuilderPatchPayload,
@@ -13,6 +16,7 @@ import {
$breakpoints,
$dataSources,
$instances,
+ $marketplaceProduct,
$pages,
$projectSettings,
$props,
@@ -35,7 +39,10 @@ const createInstance = (
children,
});
-type TestData = WebstudioData & { projectSettings: ProjectSettings };
+type TestData = WebstudioData & {
+ marketplaceProduct?: MarketplaceProduct;
+ projectSettings: ProjectSettings;
+};
const createData = (): TestData => ({
pages: createDefaultPages({ rootInstanceId: "body" }),
@@ -69,6 +76,7 @@ const setupStores = (data: TestData) => {
$styleSources.set(data.styleSources);
$styles.set(data.styles);
$assets.set(data.assets);
+ $marketplaceProduct.set(data.marketplaceProduct);
$projectSettings.set(data.projectSettings);
};
@@ -301,6 +309,37 @@ describe("builder patch sync adapter", () => {
expect($projectSettings.get()?.meta.siteName).toBe("After");
});
+ test("creates marketplace metadata through sync undo and redo", () => {
+ const data = createData();
+ const marketplaceProduct = {
+ category: "pageTemplates" as const,
+ name: "Acme Template",
+ thumbnailAssetId: "asset-id",
+ author: "Acme Studio",
+ email: "[email protected]",
+ website: "https://example.com",
+ issues: "",
+ description: "Reusable template project for Acme landing pages.",
+ };
+ setupStores(data);
+
+ createTransactionFromBuilderPatchPayload({
+ data,
+ payload: [
+ {
+ namespace: "marketplaceProduct",
+ patches: [{ op: "replace", path: [], value: marketplaceProduct }],
+ },
+ ],
+ });
+
+ expect($marketplaceProduct.get()).toEqual(marketplaceProduct);
+ serverSyncStore.undo();
+ expect($marketplaceProduct.get()).toBeUndefined();
+ serverSyncStore.redo();
+ expect($marketplaceProduct.get()).toEqual(marketplaceProduct);
+ });
+
test("commits style source selection removals through sync undo and redo", () => {
const data = createData();
data.styleSourceSelections.set("card", {
diff --git a/apps/builder/app/shared/sync/builder-patch.ts b/apps/builder/app/shared/sync/builder-patch.ts
index 730f0147ec..a2e716af74 100644
--- a/apps/builder/app/shared/sync/builder-patch.ts
+++ b/apps/builder/app/shared/sync/builder-patch.ts
@@ -31,11 +31,29 @@ const getNamespaceData = (
const applyBuilderPatchPayloadMutable = (
data: BuilderPatchData,
payload: readonly BuilderPatchChange[]
-) =>
+) => {
+ const applicableChanges: BuilderPatchChange[] = [];
+ for (const change of payload) {
+ const [patch] = change.patches;
+ if (
+ change.namespace === "marketplaceProduct" &&
+ data.marketplaceProduct === undefined &&
+ change.patches.length === 1 &&
+ patch?.op === "replace" &&
+ patch.path.length === 0
+ ) {
+ data.marketplaceProduct = structuredClone(
+ patch.value
+ ) as MarketplaceProduct;
+ continue;
+ }
+ applicableChanges.push(change);
+ }
builderStatePatch.applyBuilderPatchPayloadMutable(
(namespace) => getNamespaceData(data, namespace),
- payload
+ applicableChanges
);
+};
const clonePatch = (patch: Patch | BuilderPatch): Patch =>
patch.op === "remove"
@@ -87,6 +105,14 @@ const createSyncChangesFromBuilderPatches = ({
continue;
}
const change = getChange(namespace as BuilderPatchChange["namespace"]);
+ if (
+ namespace === "marketplaceProduct" &&
+ patch.op === "remove" &&
+ path.length === 0
+ ) {
+ change.revisePatches.push({ op: "replace", path, value: undefined });
+ continue;
+ }
change.revisePatches.push(clonePatch({ ...patch, path }));
}
return Array.from(changes, ([namespace, change]) => ({
diff --git a/apps/builder/package.json b/apps/builder/package.json
index abb0a8b736..13a3788ad6 100644
--- a/apps/builder/package.json
+++ b/apps/builder/package.json
@@ -67,7 +67,7 @@
"@tus/server": "^2.4.1",
"@unocss/core": "66.6.8",
"@vercel/remix": "2.15.3",
- "@webstudio-is/content-engine": "workspace:0.0.0-webstudio-version",
+ "@webstudio-is/content-engine": "workspace:*",
"@webstudio-is/asset-uploader": "workspace:*",
"@webstudio-is/authorization-token": "workspace:*",
"@webstudio-is/css-data": "workspace:*",
diff --git a/fixtures/react-router-cloudflare/.webstudio/data.json b/fixtures/react-router-cloudflare/.webstudio/data.json
index 78421acad5..b3a725eb3a 100644
--- a/fixtures/react-router-cloudflare/.webstudio/data.json
+++ b/fixtures/react-router-cloudflare/.webstudio/data.json
@@ -1,5 +1,5 @@
{
- "bundleVersion": "bundle-1ikf7r3",
+ "bundleVersion": "bundle-1kghc5n",
"build": {
"id": "f565d527-32e7-4731-bc71-aca9e9574587",
"projectId": "d845c167-ea07-4875-b08d-83e97c09dcce",
diff --git a/fixtures/react-router-docker/.webstudio/data.json b/fixtures/react-router-docker/.webstudio/data.json
index 78421acad5..b3a725eb3a 100644
--- a/fixtures/react-router-docker/.webstudio/data.json
+++ b/fixtures/react-router-docker/.webstudio/data.json
@@ -1,5 +1,5 @@
{
- "bundleVersion": "bundle-1ikf7r3",
+ "bundleVersion": "bundle-1kghc5n",
"build": {
"id": "f565d527-32e7-4731-bc71-aca9e9574587",
"projectId": "d845c167-ea07-4875-b08d-83e97c09dcce",
diff --git a/fixtures/react-router-netlify/.webstudio/data.json b/fixtures/react-router-netlify/.webstudio/data.json
index 78421acad5..b3a725eb3a 100644
--- a/fixtures/react-router-netlify/.webstudio/data.json
+++ b/fixtures/react-router-netlify/.webstudio/data.json
@@ -1,5 +1,5 @@
{
- "bundleVersion": "bundle-1ikf7r3",
+ "bundleVersion": "bundle-1kghc5n",
"build": {
"id": "f565d527-32e7-4731-bc71-aca9e9574587",
"projectId": "d845c167-ea07-4875-b08d-83e97c09dcce",
diff --git a/fixtures/react-router-vercel/.webstudio/data.json b/fixtures/react-router-vercel/.webstudio/data.json
index 78421acad5..b3a725eb3a 100644
--- a/fixtures/react-router-vercel/.webstudio/data.json
+++ b/fixtures/react-router-vercel/.webstudio/data.json
@@ -1,5 +1,5 @@
{
- "bundleVersion": "bundle-1ikf7r3",
+ "bundleVersion": "bundle-1kghc5n",
"build": {
"id": "f565d527-32e7-4731-bc71-aca9e9574587",
"projectId": "d845c167-ea07-4875-b08d-83e97c09dcce",
diff --git a/fixtures/ssg-cloudflare-pages/.webstudio/data.json b/fixtures/ssg-cloudflare-pages/.webstudio/data.json
index c87376c6d0..e0ac58547f 100644
--- a/fixtures/ssg-cloudflare-pages/.webstudio/data.json
+++ b/fixtures/ssg-cloudflare-pages/.webstudio/data.json
@@ -1,5 +1,5 @@
{
- "bundleVersion": "bundle-1ikf7r3",
+ "bundleVersion": "bundle-1kghc5n",
"build": {
"id": "a2e8de30-03d5-4514-a3a6-406b3266a3af",
"projectId": "d845c167-ea07-4875-b08d-83e97c09dcce",
diff --git a/fixtures/ssg-netlify-by-project-id/.webstudio/data.json b/fixtures/ssg-netlify-by-project-id/.webstudio/data.json
index 54c301798f..80690523f8 100644
--- a/fixtures/ssg-netlify-by-project-id/.webstudio/data.json
+++ b/fixtures/ssg-netlify-by-project-id/.webstudio/data.json
@@ -1,5 +1,5 @@
{
- "bundleVersion": "bundle-1ikf7r3",
+ "bundleVersion": "bundle-1kghc5n",
"build": {
"id": "8f0fdff2-e76b-4f86-9203-ea7df5f1143c",
"projectId": "8a7358b1-7de3-459d-b7b1-56dddfb6ce1e",
diff --git a/fixtures/webstudio-cloudflare-template/.webstudio/data.json b/fixtures/webstudio-cloudflare-template/.webstudio/data.json
index c87376c6d0..e0ac58547f 100644
--- a/fixtures/webstudio-cloudflare-template/.webstudio/data.json
+++ b/fixtures/webstudio-cloudflare-template/.webstudio/data.json
@@ -1,5 +1,5 @@
{
- "bundleVersion": "bundle-1ikf7r3",
+ "bundleVersion": "bundle-1kghc5n",
"build": {
"id": "a2e8de30-03d5-4514-a3a6-406b3266a3af",
"projectId": "d845c167-ea07-4875-b08d-83e97c09dcce",
diff --git a/fixtures/webstudio-features/.webstudio/data.json b/fixtures/webstudio-features/.webstudio/data.json
index df1140ae07..b8733301b0 100644
--- a/fixtures/webstudio-features/.webstudio/data.json
+++ b/fixtures/webstudio-features/.webstudio/data.json
@@ -1,5 +1,5 @@
{
- "bundleVersion": "bundle-1ikf7r3",
+ "bundleVersion": "bundle-1kghc5n",
"build": {
"id": "1b66ee06-8ea5-4420-9a0e-e0d3a67aca32",
"projectId": "cddc1d44-af37-4cb6-a430-d300cf6f932d",
diff --git a/fixtures/webstudio-features/app/__generated__/$resources.asset-query-vendor.js b/fixtures/webstudio-features/app/__generated__/$resources.asset-query-vendor.js
index 483f4533b7..95b697272e 100644
--- a/fixtures/webstudio-features/app/__generated__/$resources.asset-query-vendor.js
+++ b/fixtures/webstudio-features/app/__generated__/$resources.asset-query-vendor.js
@@ -1,64 +1,64 @@
-var Li=Object.defineProperty;var Mi=(e,t)=>{for(var r in t)Li(e,r,{get:t[r],enumerable:!0})};var tr;function l(e,t,r){function n(c,a){if(c._zod||Object.defineProperty(c,"_zod",{value:{def:a,constr:i,traits:new Set},enumerable:!1}),c._zod.traits.has(e))return;c._zod.traits.add(e),t(c,a);let u=i.prototype,f=Object.keys(u);for(let p=0;p<f.length;p++){let m=f[p];m in c||(c[m]=u[m].bind(c))}}let o=r?.Parent??Object;class s extends o{}Object.defineProperty(s,"name",{value:e});function i(c){var a;let u=r?.Parent?new s:this;n(u,c),(a=u._zod).deferred??(a.deferred=[]);for(let f of u._zod.deferred)f();return u}return Object.defineProperty(i,"init",{value:n}),Object.defineProperty(i,Symbol.hasInstance,{value:c=>r?.Parent&&c instanceof r.Parent?!0:c?._zod?.traits?.has(e)}),Object.defineProperty(i,"name",{value:e}),i}var Ru=Symbol("zod_brand"),Q=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},le=class extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}};(tr=globalThis).__zod_globalConfig??(tr.__zod_globalConfig={});var pe=globalThis.__zod_globalConfig;function M(e){return e&&Object.assign(pe,e),pe}var x={};Mi(x,{BIGINT_FORMAT_RANGES:()=>ir,Class:()=>ct,NUMBER_FORMAT_RANGES:()=>ft,aborted:()=>X,allowsEval:()=>lt,assert:()=>qi,assertEqual:()=>Ui,assertIs:()=>Qi,assertNever:()=>Ji,assertNotEqual:()=>Bi,assignProp:()=>G,base64ToUint8Array:()=>ar,base64urlToUint8Array:()=>pc,cached:()=>fe,captureStackTrace:()=>Fe,cleanEnum:()=>lc,cleanRegex:()=>ve,clone:()=>U,cloneDef:()=>Gi,createTransparentProxy:()=>tc,defineLazy:()=>_,esc:()=>De,escapeRegex:()=>q,explicitlyAborted:()=>mt,extend:()=>oc,finalizeIssue:()=>j,floatSafeRemainder:()=>at,getElementAtPath:()=>Ki,getEnumValues:()=>be,getLengthableOrigin:()=>ze,getParsedType:()=>ec,getSizableOrigin:()=>cr,hexToUint8Array:()=>fc,isObject:()=>re,isPlainObject:()=>K,issue:()=>me,joinValues:()=>Vi,jsonStringifyReplacer:()=>de,merge:()=>ic,mergeDefs:()=>J,normalizeParams:()=>h,nullish:()=>we,numKeys:()=>Hi,objectClone:()=>Wi,omit:()=>nc,optionalKeys:()=>dt,parsedType:()=>uc,partial:()=>cc,pick:()=>rc,prefixIssues:()=>V,primitiveTypes:()=>or,promiseAllObject:()=>Xi,propertyKeyTypes:()=>pt,randomString:()=>Yi,required:()=>ac,safeExtend:()=>sc,shallowClone:()=>nr,slugify:()=>ut,stringifyPrimitive:()=>sr,uint8ArrayToBase64:()=>ur,uint8ArrayToBase64url:()=>dc,uint8ArrayToHex:()=>mc,unwrapMessage:()=>xe});function Ui(e){return e}function Bi(e){return e}function Qi(e){}function Ji(e){throw new Error("Unexpected value in exhaustive check")}function qi(e){}function be(e){let t=Object.values(e).filter(n=>typeof n=="number");return Object.entries(e).filter(([n,o])=>t.indexOf(+n)===-1).map(([n,o])=>o)}function Vi(e,t="|"){return e.map(r=>sr(r)).join(t)}function de(e,t){return typeof t=="bigint"?t.toString():t}function fe(e){return{get value(){{let r=e();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function we(e){return e==null}function ve(e){let t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function at(e,t){let r=e/t,n=Math.round(r),o=Number.EPSILON*Math.max(Math.abs(r),1);return Math.abs(r-n)<o?0:r-n}var rr=Symbol("evaluating");function _(e,t,r){let n;Object.defineProperty(e,t,{get(){if(n!==rr)return n===void 0&&(n=rr,n=r()),n},set(o){Object.defineProperty(e,t,{value:o})},configurable:!0})}function Wi(e){return Object.create(Object.getPrototypeOf(e),Object.getOwnPropertyDescriptors(e))}function G(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function J(...e){let t={};for(let r of e){let n=Object.getOwnPropertyDescriptors(r);Object.assign(t,n)}return Object.defineProperties({},t)}function Gi(e){return J(e._zod.def)}function Ki(e,t){return t?t.reduce((r,n)=>r?.[n],e):e}function Xi(e){let t=Object.keys(e),r=t.map(n=>e[n]);return Promise.all(r).then(n=>{let o={};for(let s=0;s<t.length;s++)o[t[s]]=n[s];return o})}function Yi(e=10){let t="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<e;n++)r+=t[Math.floor(Math.random()*t.length)];return r}function De(e){return JSON.stringify(e)}function ut(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var Fe="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function re(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var lt=fe(()=>{if(pe.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let e=Function;return new e(""),!0}catch{return!1}});function K(e){if(re(e)===!1)return!1;let t=e.constructor;if(t===void 0||typeof t!="function")return!0;let r=t.prototype;return!(re(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function nr(e){return K(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}function Hi(e){let t=0;for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&t++;return t}var ec=e=>{let t=typeof e;switch(t){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(e)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(e)?"array":e===null?"null":e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?"promise":typeof Map<"u"&&e instanceof Map?"map":typeof Set<"u"&&e instanceof Set?"set":typeof Date<"u"&&e instanceof Date?"date":typeof File<"u"&&e instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${t}`)}},pt=new Set(["string","number","symbol"]),or=new Set(["string","number","bigint","boolean","symbol","undefined"]);function q(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function U(e,t,r){let n=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(n._zod.parent=e),n}function h(e){let t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function tc(e){let t;return new Proxy({},{get(r,n,o){return t??(t=e()),Reflect.get(t,n,o)},set(r,n,o,s){return t??(t=e()),Reflect.set(t,n,o,s)},has(r,n){return t??(t=e()),Reflect.has(t,n)},deleteProperty(r,n){return t??(t=e()),Reflect.deleteProperty(t,n)},ownKeys(r){return t??(t=e()),Reflect.ownKeys(t)},getOwnPropertyDescriptor(r,n){return t??(t=e()),Reflect.getOwnPropertyDescriptor(t,n)},defineProperty(r,n,o){return t??(t=e()),Reflect.defineProperty(t,n,o)}})}function sr(e){return typeof e=="bigint"?e.toString()+"n":typeof e=="string"?`"${e}"`:`${e}`}function dt(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}var ft={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},ir={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function rc(e,t){let r=e._zod.def,n=r.checks;if(n&&n.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");let s=J(e._zod.def,{get shape(){let i={};for(let c in t){if(!(c in r.shape))throw new Error(`Unrecognized key: "${c}"`);t[c]&&(i[c]=r.shape[c])}return G(this,"shape",i),i},checks:[]});return U(e,s)}function nc(e,t){let r=e._zod.def,n=r.checks;if(n&&n.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");let s=J(e._zod.def,{get shape(){let i={...e._zod.def.shape};for(let c in t){if(!(c in r.shape))throw new Error(`Unrecognized key: "${c}"`);t[c]&&delete i[c]}return G(this,"shape",i),i},checks:[]});return U(e,s)}function oc(e,t){if(!K(t))throw new Error("Invalid input to extend: expected a plain object");let r=e._zod.def.checks;if(r&&r.length>0){let s=e._zod.def.shape;for(let i in t)if(Object.getOwnPropertyDescriptor(s,i)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let o=J(e._zod.def,{get shape(){let s={...e._zod.def.shape,...t};return G(this,"shape",s),s}});return U(e,o)}function sc(e,t){if(!K(t))throw new Error("Invalid input to safeExtend: expected a plain object");let r=J(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t};return G(this,"shape",n),n}});return U(e,r)}function ic(e,t){if(e._zod.def.checks?.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let r=J(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t._zod.def.shape};return G(this,"shape",n),n},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return U(e,r)}function cc(e,t,r){let o=t._zod.def.checks;if(o&&o.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");let i=J(t._zod.def,{get shape(){let c=t._zod.def.shape,a={...c};if(r)for(let u in r){if(!(u in c))throw new Error(`Unrecognized key: "${u}"`);r[u]&&(a[u]=e?new e({type:"optional",innerType:c[u]}):c[u])}else for(let u in c)a[u]=e?new e({type:"optional",innerType:c[u]}):c[u];return G(this,"shape",a),a},checks:[]});return U(t,i)}function ac(e,t,r){let n=J(t._zod.def,{get shape(){let o=t._zod.def.shape,s={...o};if(r)for(let i in r){if(!(i in s))throw new Error(`Unrecognized key: "${i}"`);r[i]&&(s[i]=new e({type:"nonoptional",innerType:o[i]}))}else for(let i in o)s[i]=new e({type:"nonoptional",innerType:o[i]});return G(this,"shape",s),s}});return U(t,n)}function X(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function mt(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue===!1)return!0;return!1}function V(e,t){return t.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(e),r})}function xe(e){return typeof e=="string"?e:e?.message}function j(e,t,r){let n=e.message?e.message:xe(e.inst?._zod.def?.error?.(e))??xe(t?.error?.(e))??xe(r.customError?.(e))??xe(r.localeError?.(e))??"Invalid input",{inst:o,continue:s,input:i,...c}=e;return c.path??(c.path=[]),c.message=n,t?.reportInput&&(c.input=i),c}function cr(e){return e instanceof Set?"set":e instanceof Map?"map":e instanceof File?"file":"unknown"}function ze(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function uc(e){let t=typeof e;switch(t){case"number":return Number.isNaN(e)?"nan":"number";case"object":{if(e===null)return"null";if(Array.isArray(e))return"array";let r=e;if(r&&Object.getPrototypeOf(r)!==Object.prototype&&"constructor"in r&&r.constructor)return r.constructor.name}}return t}function me(...e){let[t,r,n]=e;return typeof t=="string"?{message:t,code:"custom",input:r,inst:n}:{...t}}function lc(e){return Object.entries(e).filter(([t,r])=>Number.isNaN(Number.parseInt(t,10))).map(t=>t[1])}function ar(e){let t=atob(e),r=new Uint8Array(t.length);for(let n=0;n<t.length;n++)r[n]=t.charCodeAt(n);return r}function ur(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return btoa(t)}function pc(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),r="=".repeat((4-t.length%4)%4);return ar(t+r)}function dc(e){return ur(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function fc(e){let t=e.replace(/^0x/,"");if(t.length%2!==0)throw new Error("Invalid hex string length");let r=new Uint8Array(t.length/2);for(let n=0;n<t.length;n+=2)r[n/2]=Number.parseInt(t.slice(n,n+2),16);return r}function mc(e){return Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")}var ct=class{constructor(...t){}};var lr=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,de,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},je=l("$ZodError",lr),ht=l("$ZodError",lr,{Parent:Error});function pr(e,t=r=>r.message){let r={},n=[];for(let o of e.issues)o.path.length>0?(r[o.path[0]]=r[o.path[0]]||[],r[o.path[0]].push(t(o))):n.push(t(o));return{formErrors:n,fieldErrors:r}}function dr(e,t=r=>r.message){let r={_errors:[]},n=(o,s=[])=>{for(let i of o.issues)if(i.code==="invalid_union"&&i.errors.length)i.errors.map(c=>n({issues:c},[...s,...i.path]));else if(i.code==="invalid_key")n({issues:i.issues},[...s,...i.path]);else if(i.code==="invalid_element")n({issues:i.issues},[...s,...i.path]);else{let c=[...s,...i.path];if(c.length===0)r._errors.push(t(i));else{let a=r,u=0;for(;u<c.length;){let f=c[u];u===c.length-1?(a[f]=a[f]||{_errors:[]},a[f]._errors.push(t(i))):a[f]=a[f]||{_errors:[]},a=a[f],u++}}}};return n(e),r}var Le=e=>(t,r,n,o)=>{let s=n?{...n,async:!1}:{async:!1},i=t._zod.run({value:r,issues:[]},s);if(i instanceof Promise)throw new Q;if(i.issues.length){let c=new(o?.Err??e)(i.issues.map(a=>j(a,s,M())));throw Fe(c,o?.callee),c}return i.value};var Me=e=>async(t,r,n,o)=>{let s=n?{...n,async:!0}:{async:!0},i=t._zod.run({value:r,issues:[]},s);if(i instanceof Promise&&(i=await i),i.issues.length){let c=new(o?.Err??e)(i.issues.map(a=>j(a,s,M())));throw Fe(c,o?.callee),c}return i.value};var $e=e=>(t,r,n)=>{let o=n?{...n,async:!1}:{async:!1},s=t._zod.run({value:r,issues:[]},o);if(s instanceof Promise)throw new Q;return s.issues.length?{success:!1,error:new(e??je)(s.issues.map(i=>j(i,o,M())))}:{success:!0,data:s.value}},fr=$e(ht),ke=e=>async(t,r,n)=>{let o=n?{...n,async:!0}:{async:!0},s=t._zod.run({value:r,issues:[]},o);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new e(s.issues.map(i=>j(i,o,M())))}:{success:!0,data:s.value}},mr=ke(ht),hr=e=>(t,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return Le(e)(t,r,o)};var yr=e=>(t,r,n)=>Le(e)(t,r,n);var gr=e=>async(t,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return Me(e)(t,r,o)};var _r=e=>async(t,r,n)=>Me(e)(t,r,n);var xr=e=>(t,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return $e(e)(t,r,o)};var br=e=>(t,r,n)=>$e(e)(t,r,n);var wr=e=>async(t,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return ke(e)(t,r,o)};var vr=e=>async(t,r,n)=>ke(e)(t,r,n);var zr=/^[cC][0-9a-z]{6,}$/,$r=/^[0-9a-z]+$/,kr=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Ar=/^[0-9a-vA-V]{20}$/,Zr=/^[A-Za-z0-9]{27}$/,Sr=/^[a-zA-Z0-9_-]{21}$/,Er=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var Rr=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,yt=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;var Pr=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var yc="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function Or(){return new RegExp(yc,"u")}var Ir=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Tr=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/;var Cr=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,Nr=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Dr=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,gt=/^[A-Za-z0-9_-]*$/;var Fr=/^https?$/,jr=/^\+[1-9]\d{6,14}$/,Lr="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",Mr=new RegExp(`^${Lr}$`);function Ur(e){let t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof e.precision=="number"?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function Br(e){return new RegExp(`^${Ur(e)}$`)}function Qr(e){let t=Ur({precision:e.precision}),r=["Z"];e.local&&r.push(""),e.offset&&r.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let n=`${t}(?:${r.join("|")})`;return new RegExp(`^${Lr}T(?:${n})$`)}var Jr=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)};var qr=/^-?\d+$/,_t=/^-?\d+(?:\.\d+)?$/,Vr=/^(?:true|false)$/i,Wr=/^null$/i;var Gr=/^[^A-Z]*$/,Kr=/^[^a-z]*$/;var I=l("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),Xr={number:"number",bigint:"bigint",object:"date"},xt=l("$ZodCheckLessThan",(e,t)=>{I.init(e,t);let r=Xr[typeof t.value];e._zod.onattach.push(n=>{let o=n._zod.bag,s=(t.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<s&&(t.inclusive?o.maximum=t.value:o.exclusiveMaximum=t.value)}),e._zod.check=n=>{(t.inclusive?n.value<=t.value:n.value<t.value)||n.issues.push({origin:r,code:"too_big",maximum:typeof t.value=="object"?t.value.getTime():t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),bt=l("$ZodCheckGreaterThan",(e,t)=>{I.init(e,t);let r=Xr[typeof t.value];e._zod.onattach.push(n=>{let o=n._zod.bag,s=(t.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>s&&(t.inclusive?o.minimum=t.value:o.exclusiveMinimum=t.value)}),e._zod.check=n=>{(t.inclusive?n.value>=t.value:n.value>t.value)||n.issues.push({origin:r,code:"too_small",minimum:typeof t.value=="object"?t.value.getTime():t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Yr=l("$ZodCheckMultipleOf",(e,t)=>{I.init(e,t),e._zod.onattach.push(r=>{var n;(n=r._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=r=>{if(typeof r.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%t.value===BigInt(0):at(r.value,t.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:t.value,input:r.value,inst:e,continue:!t.abort})}}),Hr=l("$ZodCheckNumberFormat",(e,t)=>{I.init(e,t),t.format=t.format||"float64";let r=t.format?.includes("int"),n=r?"int":"number",[o,s]=ft[t.format];e._zod.onattach.push(i=>{let c=i._zod.bag;c.format=t.format,c.minimum=o,c.maximum=s,r&&(c.pattern=qr)}),e._zod.check=i=>{let c=i.value;if(r){if(!Number.isInteger(c)){i.issues.push({expected:n,format:t.format,code:"invalid_type",continue:!1,input:c,inst:e});return}if(!Number.isSafeInteger(c)){c>0?i.issues.push({input:c,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,inclusive:!0,continue:!t.abort}):i.issues.push({input:c,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,inclusive:!0,continue:!t.abort});return}}c<o&&i.issues.push({origin:"number",input:c,code:"too_small",minimum:o,inclusive:!0,inst:e,continue:!t.abort}),c>s&&i.issues.push({origin:"number",input:c,code:"too_big",maximum:s,inclusive:!0,inst:e,continue:!t.abort})}});var en=l("$ZodCheckMaxLength",(e,t)=>{var r;I.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!we(o)&&o.length!==void 0}),e._zod.onattach.push(n=>{let o=n._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<o&&(n._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{let o=n.value;if(o.length<=t.maximum)return;let i=ze(o);n.issues.push({origin:i,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),tn=l("$ZodCheckMinLength",(e,t)=>{var r;I.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!we(o)&&o.length!==void 0}),e._zod.onattach.push(n=>{let o=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>o&&(n._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{let o=n.value;if(o.length>=t.minimum)return;let i=ze(o);n.issues.push({origin:i,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),rn=l("$ZodCheckLengthEquals",(e,t)=>{var r;I.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!we(o)&&o.length!==void 0}),e._zod.onattach.push(n=>{let o=n._zod.bag;o.minimum=t.length,o.maximum=t.length,o.length=t.length}),e._zod.check=n=>{let o=n.value,s=o.length;if(s===t.length)return;let i=ze(o),c=s>t.length;n.issues.push({origin:i,...c?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),Ae=l("$ZodCheckStringFormat",(e,t)=>{var r,n;I.init(e,t),e._zod.onattach.push(o=>{let s=o._zod.bag;s.format=t.format,t.pattern&&(s.patterns??(s.patterns=new Set),s.patterns.add(t.pattern))}),t.pattern?(r=e._zod).check??(r.check=o=>{t.pattern.lastIndex=0,!t.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:t.format,input:o.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(n=e._zod).check??(n.check=()=>{})}),nn=l("$ZodCheckRegex",(e,t)=>{Ae.init(e,t),e._zod.check=r=>{t.pattern.lastIndex=0,!t.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),on=l("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=Gr),Ae.init(e,t)}),sn=l("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=Kr),Ae.init(e,t)}),cn=l("$ZodCheckIncludes",(e,t)=>{I.init(e,t);let r=q(t.includes),n=new RegExp(typeof t.position=="number"?`^.{${t.position}}${r}`:r);t.pattern=n,e._zod.onattach.push(o=>{let s=o._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(n)}),e._zod.check=o=>{o.value.includes(t.includes,t.position)||o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:o.value,inst:e,continue:!t.abort})}}),an=l("$ZodCheckStartsWith",(e,t)=>{I.init(e,t);let r=new RegExp(`^${q(t.prefix)}.*`);t.pattern??(t.pattern=r),e._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),un=l("$ZodCheckEndsWith",(e,t)=>{I.init(e,t);let r=new RegExp(`.*${q(t.suffix)}$`);t.pattern??(t.pattern=r),e._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}});var ln=l("$ZodCheckOverwrite",(e,t)=>{I.init(e,t),e._zod.check=r=>{r.value=t.tx(r.value)}});var Be=class{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}let n=t.split(`
+var Ji=Object.defineProperty;var Vi=(e,t)=>{for(var r in t)Ji(e,r,{get:t[r],enumerable:!0})};var sr;function l(e,t,r){function n(c,a){if(c._zod||Object.defineProperty(c,"_zod",{value:{def:a,constr:i,traits:new Set},enumerable:!1}),c._zod.traits.has(e))return;c._zod.traits.add(e),t(c,a);let u=i.prototype,f=Object.keys(u);for(let p=0;p<f.length;p++){let m=f[p];m in c||(c[m]=u[m].bind(c))}}let o=r?.Parent??Object;class s extends o{}Object.defineProperty(s,"name",{value:e});function i(c){var a;let u=r?.Parent?new s:this;n(u,c),(a=u._zod).deferred??(a.deferred=[]);for(let f of u._zod.deferred)f();return u}return Object.defineProperty(i,"init",{value:n}),Object.defineProperty(i,Symbol.hasInstance,{value:c=>r?.Parent&&c instanceof r.Parent?!0:c?._zod?.traits?.has(e)}),Object.defineProperty(i,"name",{value:e}),i}var Nu=Symbol("zod_brand"),B=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},le=class extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}};(sr=globalThis).__zod_globalConfig??(sr.__zod_globalConfig={});var pe=globalThis.__zod_globalConfig;function Q(e){return e&&Object.assign(pe,e),pe}var b={};Vi(b,{BIGINT_FORMAT_RANGES:()=>lr,Class:()=>pt,NUMBER_FORMAT_RANGES:()=>gt,aborted:()=>H,allowsEval:()=>mt,assert:()=>Xi,assertEqual:()=>qi,assertIs:()=>Gi,assertNever:()=>Ki,assertNotEqual:()=>Wi,assignProp:()=>X,base64ToUint8Array:()=>dr,base64urlToUint8Array:()=>yc,cached:()=>fe,captureStackTrace:()=>Le,cleanEnum:()=>hc,cleanRegex:()=>$e,clone:()=>U,cloneDef:()=>ec,createTransparentProxy:()=>ic,defineLazy:()=>_,esc:()=>je,escapeRegex:()=>q,explicitlyAborted:()=>_t,extend:()=>uc,finalizeIssue:()=>L,floatSafeRemainder:()=>dt,getElementAtPath:()=>tc,getEnumValues:()=>ve,getLengthableOrigin:()=>ke,getParsedType:()=>sc,getSizableOrigin:()=>pr,hexToUint8Array:()=>_c,isObject:()=>oe,isPlainObject:()=>Y,issue:()=>me,joinValues:()=>Yi,jsonStringifyReplacer:()=>de,merge:()=>pc,mergeDefs:()=>V,normalizeParams:()=>h,nullish:()=>ze,numKeys:()=>oc,objectClone:()=>Hi,omit:()=>ac,optionalKeys:()=>yt,parsedType:()=>mc,partial:()=>dc,pick:()=>cc,prefixIssues:()=>W,primitiveTypes:()=>ar,promiseAllObject:()=>rc,propertyKeyTypes:()=>ht,randomString:()=>nc,required:()=>fc,safeExtend:()=>lc,shallowClone:()=>cr,slugify:()=>ft,stringifyPrimitive:()=>ur,uint8ArrayToBase64:()=>fr,uint8ArrayToBase64url:()=>gc,uint8ArrayToHex:()=>xc,unwrapMessage:()=>we});function qi(e){return e}function Wi(e){return e}function Gi(e){}function Ki(e){throw new Error("Unexpected value in exhaustive check")}function Xi(e){}function ve(e){let t=Object.values(e).filter(n=>typeof n=="number");return Object.entries(e).filter(([n,o])=>t.indexOf(+n)===-1).map(([n,o])=>o)}function Yi(e,t="|"){return e.map(r=>ur(r)).join(t)}function de(e,t){return typeof t=="bigint"?t.toString():t}function fe(e){return{get value(){{let r=e();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function ze(e){return e==null}function $e(e){let t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function dt(e,t){let r=e/t,n=Math.round(r),o=Number.EPSILON*Math.max(Math.abs(r),1);return Math.abs(r-n)<o?0:r-n}var ir=Symbol("evaluating");function _(e,t,r){let n;Object.defineProperty(e,t,{get(){if(n!==ir)return n===void 0&&(n=ir,n=r()),n},set(o){Object.defineProperty(e,t,{value:o})},configurable:!0})}function Hi(e){return Object.create(Object.getPrototypeOf(e),Object.getOwnPropertyDescriptors(e))}function X(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function V(...e){let t={};for(let r of e){let n=Object.getOwnPropertyDescriptors(r);Object.assign(t,n)}return Object.defineProperties({},t)}function ec(e){return V(e._zod.def)}function tc(e,t){return t?t.reduce((r,n)=>r?.[n],e):e}function rc(e){let t=Object.keys(e),r=t.map(n=>e[n]);return Promise.all(r).then(n=>{let o={};for(let s=0;s<t.length;s++)o[t[s]]=n[s];return o})}function nc(e=10){let t="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<e;n++)r+=t[Math.floor(Math.random()*t.length)];return r}function je(e){return JSON.stringify(e)}function ft(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var Le="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function oe(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var mt=fe(()=>{if(pe.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let e=Function;return new e(""),!0}catch{return!1}});function Y(e){if(oe(e)===!1)return!1;let t=e.constructor;if(t===void 0||typeof t!="function")return!0;let r=t.prototype;return!(oe(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function cr(e){return Y(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}function oc(e){let t=0;for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&t++;return t}var sc=e=>{let t=typeof e;switch(t){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(e)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(e)?"array":e===null?"null":e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?"promise":typeof Map<"u"&&e instanceof Map?"map":typeof Set<"u"&&e instanceof Set?"set":typeof Date<"u"&&e instanceof Date?"date":typeof File<"u"&&e instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${t}`)}},ht=new Set(["string","number","symbol"]),ar=new Set(["string","number","bigint","boolean","symbol","undefined"]);function q(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function U(e,t,r){let n=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(n._zod.parent=e),n}function h(e){let t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function ic(e){let t;return new Proxy({},{get(r,n,o){return t??(t=e()),Reflect.get(t,n,o)},set(r,n,o,s){return t??(t=e()),Reflect.set(t,n,o,s)},has(r,n){return t??(t=e()),Reflect.has(t,n)},deleteProperty(r,n){return t??(t=e()),Reflect.deleteProperty(t,n)},ownKeys(r){return t??(t=e()),Reflect.ownKeys(t)},getOwnPropertyDescriptor(r,n){return t??(t=e()),Reflect.getOwnPropertyDescriptor(t,n)},defineProperty(r,n,o){return t??(t=e()),Reflect.defineProperty(t,n,o)}})}function ur(e){return typeof e=="bigint"?e.toString()+"n":typeof e=="string"?`"${e}"`:`${e}`}function yt(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}var gt={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},lr={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function cc(e,t){let r=e._zod.def,n=r.checks;if(n&&n.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");let s=V(e._zod.def,{get shape(){let i={};for(let c in t){if(!(c in r.shape))throw new Error(`Unrecognized key: "${c}"`);t[c]&&(i[c]=r.shape[c])}return X(this,"shape",i),i},checks:[]});return U(e,s)}function ac(e,t){let r=e._zod.def,n=r.checks;if(n&&n.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");let s=V(e._zod.def,{get shape(){let i={...e._zod.def.shape};for(let c in t){if(!(c in r.shape))throw new Error(`Unrecognized key: "${c}"`);t[c]&&delete i[c]}return X(this,"shape",i),i},checks:[]});return U(e,s)}function uc(e,t){if(!Y(t))throw new Error("Invalid input to extend: expected a plain object");let r=e._zod.def.checks;if(r&&r.length>0){let s=e._zod.def.shape;for(let i in t)if(Object.getOwnPropertyDescriptor(s,i)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let o=V(e._zod.def,{get shape(){let s={...e._zod.def.shape,...t};return X(this,"shape",s),s}});return U(e,o)}function lc(e,t){if(!Y(t))throw new Error("Invalid input to safeExtend: expected a plain object");let r=V(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t};return X(this,"shape",n),n}});return U(e,r)}function pc(e,t){if(e._zod.def.checks?.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let r=V(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t._zod.def.shape};return X(this,"shape",n),n},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return U(e,r)}function dc(e,t,r){let o=t._zod.def.checks;if(o&&o.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");let i=V(t._zod.def,{get shape(){let c=t._zod.def.shape,a={...c};if(r)for(let u in r){if(!(u in c))throw new Error(`Unrecognized key: "${u}"`);r[u]&&(a[u]=e?new e({type:"optional",innerType:c[u]}):c[u])}else for(let u in c)a[u]=e?new e({type:"optional",innerType:c[u]}):c[u];return X(this,"shape",a),a},checks:[]});return U(t,i)}function fc(e,t,r){let n=V(t._zod.def,{get shape(){let o=t._zod.def.shape,s={...o};if(r)for(let i in r){if(!(i in s))throw new Error(`Unrecognized key: "${i}"`);r[i]&&(s[i]=new e({type:"nonoptional",innerType:o[i]}))}else for(let i in o)s[i]=new e({type:"nonoptional",innerType:o[i]});return X(this,"shape",s),s}});return U(t,n)}function H(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function _t(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue===!1)return!0;return!1}function W(e,t){return t.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(e),r})}function we(e){return typeof e=="string"?e:e?.message}function L(e,t,r){let n=e.message?e.message:we(e.inst?._zod.def?.error?.(e))??we(t?.error?.(e))??we(r.customError?.(e))??we(r.localeError?.(e))??"Invalid input",{inst:o,continue:s,input:i,...c}=e;return c.path??(c.path=[]),c.message=n,t?.reportInput&&(c.input=i),c}function pr(e){return e instanceof Set?"set":e instanceof Map?"map":e instanceof File?"file":"unknown"}function ke(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function mc(e){let t=typeof e;switch(t){case"number":return Number.isNaN(e)?"nan":"number";case"object":{if(e===null)return"null";if(Array.isArray(e))return"array";let r=e;if(r&&Object.getPrototypeOf(r)!==Object.prototype&&"constructor"in r&&r.constructor)return r.constructor.name}}return t}function me(...e){let[t,r,n]=e;return typeof t=="string"?{message:t,code:"custom",input:r,inst:n}:{...t}}function hc(e){return Object.entries(e).filter(([t,r])=>Number.isNaN(Number.parseInt(t,10))).map(t=>t[1])}function dr(e){let t=atob(e),r=new Uint8Array(t.length);for(let n=0;n<t.length;n++)r[n]=t.charCodeAt(n);return r}function fr(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return btoa(t)}function yc(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),r="=".repeat((4-t.length%4)%4);return dr(t+r)}function gc(e){return fr(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function _c(e){let t=e.replace(/^0x/,"");if(t.length%2!==0)throw new Error("Invalid hex string length");let r=new Uint8Array(t.length/2);for(let n=0;n<t.length;n+=2)r[n/2]=Number.parseInt(t.slice(n,n+2),16);return r}function xc(e){return Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")}var pt=class{constructor(...t){}};var mr=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,de,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Me=l("$ZodError",mr),xt=l("$ZodError",mr,{Parent:Error});function hr(e,t=r=>r.message){let r={},n=[];for(let o of e.issues)o.path.length>0?(r[o.path[0]]=r[o.path[0]]||[],r[o.path[0]].push(t(o))):n.push(t(o));return{formErrors:n,fieldErrors:r}}function yr(e,t=r=>r.message){let r={_errors:[]},n=(o,s=[])=>{for(let i of o.issues)if(i.code==="invalid_union"&&i.errors.length)i.errors.map(c=>n({issues:c},[...s,...i.path]));else if(i.code==="invalid_key")n({issues:i.issues},[...s,...i.path]);else if(i.code==="invalid_element")n({issues:i.issues},[...s,...i.path]);else{let c=[...s,...i.path];if(c.length===0)r._errors.push(t(i));else{let a=r,u=0;for(;u<c.length;){let f=c[u];u===c.length-1?(a[f]=a[f]||{_errors:[]},a[f]._errors.push(t(i))):a[f]=a[f]||{_errors:[]},a=a[f],u++}}}};return n(e),r}var Qe=e=>(t,r,n,o)=>{let s=n?{...n,async:!1}:{async:!1},i=t._zod.run({value:r,issues:[]},s);if(i instanceof Promise)throw new B;if(i.issues.length){let c=new(o?.Err??e)(i.issues.map(a=>L(a,s,Q())));throw Le(c,o?.callee),c}return i.value};var Ue=e=>async(t,r,n,o)=>{let s=n?{...n,async:!0}:{async:!0},i=t._zod.run({value:r,issues:[]},s);if(i instanceof Promise&&(i=await i),i.issues.length){let c=new(o?.Err??e)(i.issues.map(a=>L(a,s,Q())));throw Le(c,o?.callee),c}return i.value};var Ae=e=>(t,r,n)=>{let o=n?{...n,async:!1}:{async:!1},s=t._zod.run({value:r,issues:[]},o);if(s instanceof Promise)throw new B;return s.issues.length?{success:!1,error:new(e??Me)(s.issues.map(i=>L(i,o,Q())))}:{success:!0,data:s.value}},gr=Ae(xt),Ze=e=>async(t,r,n)=>{let o=n?{...n,async:!0}:{async:!0},s=t._zod.run({value:r,issues:[]},o);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new e(s.issues.map(i=>L(i,o,Q())))}:{success:!0,data:s.value}},_r=Ze(xt),xr=e=>(t,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return Qe(e)(t,r,o)};var br=e=>(t,r,n)=>Qe(e)(t,r,n);var wr=e=>async(t,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return Ue(e)(t,r,o)};var vr=e=>async(t,r,n)=>Ue(e)(t,r,n);var zr=e=>(t,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return Ae(e)(t,r,o)};var $r=e=>(t,r,n)=>Ae(e)(t,r,n);var kr=e=>async(t,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return Ze(e)(t,r,o)};var Ar=e=>async(t,r,n)=>Ze(e)(t,r,n);var Zr=/^[cC][0-9a-z]{6,}$/,Sr=/^[0-9a-z]+$/,Er=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Rr=/^[0-9a-vA-V]{20}$/,Pr=/^[A-Za-z0-9]{27}$/,Or=/^[a-zA-Z0-9_-]{21}$/,Cr=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var Ir=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,bt=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;var Tr=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var wc="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function Dr(){return new RegExp(wc,"u")}var Nr=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Fr=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/;var jr=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,Lr=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Mr=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,wt=/^[A-Za-z0-9_-]*$/;var Qr=/^https?$/,Ur=/^\+[1-9]\d{6,14}$/,Br="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",Jr=new RegExp(`^${Br}$`);function Vr(e){let t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof e.precision=="number"?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function qr(e){return new RegExp(`^${Vr(e)}$`)}function Wr(e){let t=Vr({precision:e.precision}),r=["Z"];e.local&&r.push(""),e.offset&&r.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let n=`${t}(?:${r.join("|")})`;return new RegExp(`^${Br}T(?:${n})$`)}var Gr=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)};var Kr=/^-?\d+$/,vt=/^-?\d+(?:\.\d+)?$/,Xr=/^(?:true|false)$/i,Yr=/^null$/i;var Hr=/^[^A-Z]*$/,en=/^[^a-z]*$/;var I=l("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),tn={number:"number",bigint:"bigint",object:"date"},zt=l("$ZodCheckLessThan",(e,t)=>{I.init(e,t);let r=tn[typeof t.value];e._zod.onattach.push(n=>{let o=n._zod.bag,s=(t.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<s&&(t.inclusive?o.maximum=t.value:o.exclusiveMaximum=t.value)}),e._zod.check=n=>{(t.inclusive?n.value<=t.value:n.value<t.value)||n.issues.push({origin:r,code:"too_big",maximum:typeof t.value=="object"?t.value.getTime():t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),$t=l("$ZodCheckGreaterThan",(e,t)=>{I.init(e,t);let r=tn[typeof t.value];e._zod.onattach.push(n=>{let o=n._zod.bag,s=(t.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>s&&(t.inclusive?o.minimum=t.value:o.exclusiveMinimum=t.value)}),e._zod.check=n=>{(t.inclusive?n.value>=t.value:n.value>t.value)||n.issues.push({origin:r,code:"too_small",minimum:typeof t.value=="object"?t.value.getTime():t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),rn=l("$ZodCheckMultipleOf",(e,t)=>{I.init(e,t),e._zod.onattach.push(r=>{var n;(n=r._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=r=>{if(typeof r.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%t.value===BigInt(0):dt(r.value,t.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:t.value,input:r.value,inst:e,continue:!t.abort})}}),nn=l("$ZodCheckNumberFormat",(e,t)=>{I.init(e,t),t.format=t.format||"float64";let r=t.format?.includes("int"),n=r?"int":"number",[o,s]=gt[t.format];e._zod.onattach.push(i=>{let c=i._zod.bag;c.format=t.format,c.minimum=o,c.maximum=s,r&&(c.pattern=Kr)}),e._zod.check=i=>{let c=i.value;if(r){if(!Number.isInteger(c)){i.issues.push({expected:n,format:t.format,code:"invalid_type",continue:!1,input:c,inst:e});return}if(!Number.isSafeInteger(c)){c>0?i.issues.push({input:c,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,inclusive:!0,continue:!t.abort}):i.issues.push({input:c,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,inclusive:!0,continue:!t.abort});return}}c<o&&i.issues.push({origin:"number",input:c,code:"too_small",minimum:o,inclusive:!0,inst:e,continue:!t.abort}),c>s&&i.issues.push({origin:"number",input:c,code:"too_big",maximum:s,inclusive:!0,inst:e,continue:!t.abort})}});var on=l("$ZodCheckMaxLength",(e,t)=>{var r;I.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!ze(o)&&o.length!==void 0}),e._zod.onattach.push(n=>{let o=n._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<o&&(n._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{let o=n.value;if(o.length<=t.maximum)return;let i=ke(o);n.issues.push({origin:i,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),sn=l("$ZodCheckMinLength",(e,t)=>{var r;I.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!ze(o)&&o.length!==void 0}),e._zod.onattach.push(n=>{let o=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>o&&(n._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{let o=n.value;if(o.length>=t.minimum)return;let i=ke(o);n.issues.push({origin:i,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),cn=l("$ZodCheckLengthEquals",(e,t)=>{var r;I.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!ze(o)&&o.length!==void 0}),e._zod.onattach.push(n=>{let o=n._zod.bag;o.minimum=t.length,o.maximum=t.length,o.length=t.length}),e._zod.check=n=>{let o=n.value,s=o.length;if(s===t.length)return;let i=ke(o),c=s>t.length;n.issues.push({origin:i,...c?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),Se=l("$ZodCheckStringFormat",(e,t)=>{var r,n;I.init(e,t),e._zod.onattach.push(o=>{let s=o._zod.bag;s.format=t.format,t.pattern&&(s.patterns??(s.patterns=new Set),s.patterns.add(t.pattern))}),t.pattern?(r=e._zod).check??(r.check=o=>{t.pattern.lastIndex=0,!t.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:t.format,input:o.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(n=e._zod).check??(n.check=()=>{})}),an=l("$ZodCheckRegex",(e,t)=>{Se.init(e,t),e._zod.check=r=>{t.pattern.lastIndex=0,!t.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),un=l("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=Hr),Se.init(e,t)}),ln=l("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=en),Se.init(e,t)}),pn=l("$ZodCheckIncludes",(e,t)=>{I.init(e,t);let r=q(t.includes),n=new RegExp(typeof t.position=="number"?`^.{${t.position}}${r}`:r);t.pattern=n,e._zod.onattach.push(o=>{let s=o._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(n)}),e._zod.check=o=>{o.value.includes(t.includes,t.position)||o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:o.value,inst:e,continue:!t.abort})}}),dn=l("$ZodCheckStartsWith",(e,t)=>{I.init(e,t);let r=new RegExp(`^${q(t.prefix)}.*`);t.pattern??(t.pattern=r),e._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),fn=l("$ZodCheckEndsWith",(e,t)=>{I.init(e,t);let r=new RegExp(`.*${q(t.suffix)}$`);t.pattern??(t.pattern=r),e._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}});var mn=l("$ZodCheckOverwrite",(e,t)=>{I.init(e,t),e._zod.check=r=>{r.value=t.tx(r.value)}});var Je=class{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}let n=t.split(`
`).filter(i=>i),o=Math.min(...n.map(i=>i.length-i.trimStart().length)),s=n.map(i=>i.slice(o)).map(i=>" ".repeat(this.indent*2)+i);for(let i of s)this.content.push(i)}compile(){let t=Function,r=this?.args,o=[...(this?.content??[""]).map(s=>` ${s}`)];return new t(...r,o.join(`
-`))}};var dn={major:4,minor:4,patch:3};var z=l("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=dn;let n=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&n.unshift(e);for(let o of n)for(let s of o._zod.onattach)s(e);if(n.length===0)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let o=(i,c,a)=>{let u=X(i),f;for(let p of c){if(p._zod.def.when){if(mt(i)||!p._zod.def.when(i))continue}else if(u)continue;let m=i.issues.length,d=p._zod.check(i);if(d instanceof Promise&&a?.async===!1)throw new Q;if(f||d instanceof Promise)f=(f??Promise.resolve()).then(async()=>{await d,i.issues.length!==m&&(u||(u=X(i,m)))});else{if(i.issues.length===m)continue;u||(u=X(i,m))}}return f?f.then(()=>i):i},s=(i,c,a)=>{if(X(i))return i.aborted=!0,i;let u=o(c,n,a);if(u instanceof Promise){if(a.async===!1)throw new Q;return u.then(f=>e._zod.parse(f,a))}return e._zod.parse(u,a)};e._zod.run=(i,c)=>{if(c.skipChecks)return e._zod.parse(i,c);if(c.direction==="backward"){let u=e._zod.parse({value:i.value,issues:[]},{...c,skipChecks:!0});return u instanceof Promise?u.then(f=>s(f,i,c)):s(u,i,c)}let a=e._zod.parse(i,c);if(a instanceof Promise){if(c.async===!1)throw new Q;return a.then(u=>o(u,n,c))}return o(a,n,c)}}_(e,"~standard",()=>({validate:o=>{try{let s=fr(e,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return mr(e,o).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}))}),qe=l("$ZodString",(e,t)=>{z.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??Jr(e._zod.bag),e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:e}),r}}),$=l("$ZodStringFormat",(e,t)=>{Ae.init(e,t),qe.init(e,t)}),wn=l("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=Rr),$.init(e,t)}),vn=l("$ZodUUID",(e,t)=>{if(t.version){let n={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(n===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=yt(n))}else t.pattern??(t.pattern=yt());$.init(e,t)}),zn=l("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=Pr),$.init(e,t)}),$n=l("$ZodURL",(e,t)=>{$.init(e,t),e._zod.check=r=>{try{let n=r.value.trim();if(!t.normalize&&t.protocol?.source===Fr.source&&!/^https?:\/\//i.test(n)){r.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:r.value,inst:e,continue:!t.abort});return}let o=new URL(n);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(o.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:r.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:r.value,inst:e,continue:!t.abort})),t.normalize?r.value=o.href:r.value=n;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort})}}}),kn=l("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=Or()),$.init(e,t)}),An=l("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=Sr),$.init(e,t)}),Zn=l("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=zr),$.init(e,t)}),Sn=l("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=$r),$.init(e,t)}),En=l("$ZodULID",(e,t)=>{t.pattern??(t.pattern=kr),$.init(e,t)}),Rn=l("$ZodXID",(e,t)=>{t.pattern??(t.pattern=Ar),$.init(e,t)}),Pn=l("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=Zr),$.init(e,t)}),On=l("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=Qr(t)),$.init(e,t)}),In=l("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=Mr),$.init(e,t)}),Tn=l("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=Br(t)),$.init(e,t)}),Cn=l("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=Er),$.init(e,t)}),Nn=l("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=Ir),$.init(e,t),e._zod.bag.format="ipv4"}),Dn=l("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=Tr),$.init(e,t),e._zod.bag.format="ipv6",e._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:e,continue:!t.abort})}}});var Fn=l("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=Cr),$.init(e,t)}),jn=l("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=Nr),$.init(e,t),e._zod.check=r=>{let n=r.value.split("/");try{if(n.length!==2)throw new Error;let[o,s]=n;if(!s)throw new Error;let i=Number(s);if(`${i}`!==s)throw new Error;if(i<0||i>128)throw new Error;new URL(`http://[${o}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:e,continue:!t.abort})}}});function Ln(e){if(e==="")return!0;if(/\s/.test(e)||e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}var Mn=l("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=Dr),$.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=r=>{Ln(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}});function gc(e){if(!gt.test(e))return!1;let t=e.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=t.padEnd(Math.ceil(t.length/4)*4,"=");return Ln(r)}var Un=l("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=gt),$.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=r=>{gc(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),Bn=l("$ZodE164",(e,t)=>{t.pattern??(t.pattern=jr),$.init(e,t)});function _c(e,t=null){try{let r=e.split(".");if(r.length!==3)return!1;let[n]=r;if(!n)return!1;let o=JSON.parse(atob(n));return!("typ"in o&&o?.typ!=="JWT"||!o.alg||t&&(!("alg"in o)||o.alg!==t))}catch{return!1}}var Qn=l("$ZodJWT",(e,t)=>{$.init(e,t),e._zod.check=r=>{_c(r.value,t.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}});var vt=l("$ZodNumber",(e,t)=>{z.init(e,t),e._zod.pattern=e._zod.bag.pattern??_t,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=Number(r.value)}catch{}let o=r.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return r;let s=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:o,inst:e,...s?{received:s}:{}}),r}}),Jn=l("$ZodNumberFormat",(e,t)=>{Hr.init(e,t),vt.init(e,t)}),qn=l("$ZodBoolean",(e,t)=>{z.init(e,t),e._zod.pattern=Vr,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=!!r.value}catch{}let o=r.value;return typeof o=="boolean"||r.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:e}),r}});var Vn=l("$ZodNull",(e,t)=>{z.init(e,t),e._zod.pattern=Wr,e._zod.values=new Set([null]),e._zod.parse=(r,n)=>{let o=r.value;return o===null||r.issues.push({expected:"null",code:"invalid_type",input:o,inst:e}),r}});var Wn=l("$ZodUnknown",(e,t)=>{z.init(e,t),e._zod.parse=r=>r}),Gn=l("$ZodNever",(e,t)=>{z.init(e,t),e._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:e}),r)});function fn(e,t,r){e.issues.length&&t.issues.push(...V(r,e.issues)),t.value[r]=e.value}var Kn=l("$ZodArray",(e,t)=>{z.init(e,t),e._zod.parse=(r,n)=>{let o=r.value;if(!Array.isArray(o))return r.issues.push({expected:"array",code:"invalid_type",input:o,inst:e}),r;r.value=Array(o.length);let s=[];for(let i=0;i<o.length;i++){let c=o[i],a=t.element._zod.run({value:c,issues:[]},n);a instanceof Promise?s.push(a.then(u=>fn(u,r,i))):fn(a,r,i)}return s.length?Promise.all(s).then(()=>r):r}});function Je(e,t,r,n,o,s){let i=r in n;if(e.issues.length){if(o&&s&&!i)return;t.issues.push(...V(r,e.issues))}if(!i&&!o){e.issues.length||t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[r]});return}e.value===void 0?i&&(t.value[r]=void 0):t.value[r]=e.value}function Xn(e){let t=Object.keys(e.shape);for(let n of t)if(!e.shape?.[n]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${n}": expected a Zod schema`);let r=dt(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(r)}}function Yn(e,t,r,n,o,s){let i=[],c=o.keySet,a=o.catchall._zod,u=a.def.type,f=a.optin==="optional",p=a.optout==="optional";for(let m in t){if(m==="__proto__"||c.has(m))continue;if(u==="never"){i.push(m);continue}let d=a.run({value:t[m],issues:[]},n);d instanceof Promise?e.push(d.then(y=>Je(y,r,m,t,f,p))):Je(d,r,m,t,f,p)}return i.length&&r.issues.push({code:"unrecognized_keys",keys:i,input:t,inst:s}),e.length?Promise.all(e).then(()=>r):r}var xc=l("$ZodObject",(e,t)=>{if(z.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){let c=t.shape;Object.defineProperty(t,"shape",{get:()=>{let a={...c};return Object.defineProperty(t,"shape",{value:a}),a}})}let n=fe(()=>Xn(t));_(e._zod,"propValues",()=>{let c=t.shape,a={};for(let u in c){let f=c[u]._zod;if(f.values){a[u]??(a[u]=new Set);for(let p of f.values)a[u].add(p)}}return a});let o=re,s=t.catchall,i;e._zod.parse=(c,a)=>{i??(i=n.value);let u=c.value;if(!o(u))return c.issues.push({expected:"object",code:"invalid_type",input:u,inst:e}),c;c.value={};let f=[],p=i.shape;for(let m of i.keys){let d=p[m],y=d._zod.optin==="optional",P=d._zod.optout==="optional",w=d._zod.run({value:u[m],issues:[]},a);w instanceof Promise?f.push(w.then(F=>Je(F,c,m,u,y,P))):Je(w,c,m,u,y,P)}return s?Yn(f,u,c,a,n.value,e):f.length?Promise.all(f).then(()=>c):c}}),Hn=l("$ZodObjectJIT",(e,t)=>{xc.init(e,t);let r=e._zod.parse,n=fe(()=>Xn(t)),o=m=>{let d=new Be(["shape","payload","ctx"]),y=n.value,P=B=>{let Z=De(B);return`shape[${Z}]._zod.run({ value: input[${Z}], issues: [] }, ctx)`};d.write("const input = payload.value;");let w=Object.create(null),F=0;for(let B of y.keys)w[B]=`key_${F++}`;d.write("const newResult = {};");for(let B of y.keys){let Z=w[B],O=De(B),Ht=m[B],er=Ht?._zod?.optin==="optional",ji=Ht?._zod?.optout==="optional";d.write(`const ${Z} = ${P(B)};`),er&&ji?d.write(`
- if (${Z}.issues.length) {
- if (${O} in input) {
- payload.issues = payload.issues.concat(${Z}.issues.map(iss => ({
+`))}};var yn={major:4,minor:4,patch:3};var z=l("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=yn;let n=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&n.unshift(e);for(let o of n)for(let s of o._zod.onattach)s(e);if(n.length===0)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let o=(i,c,a)=>{let u=H(i),f;for(let p of c){if(p._zod.def.when){if(_t(i)||!p._zod.def.when(i))continue}else if(u)continue;let m=i.issues.length,d=p._zod.check(i);if(d instanceof Promise&&a?.async===!1)throw new B;if(f||d instanceof Promise)f=(f??Promise.resolve()).then(async()=>{await d,i.issues.length!==m&&(u||(u=H(i,m)))});else{if(i.issues.length===m)continue;u||(u=H(i,m))}}return f?f.then(()=>i):i},s=(i,c,a)=>{if(H(i))return i.aborted=!0,i;let u=o(c,n,a);if(u instanceof Promise){if(a.async===!1)throw new B;return u.then(f=>e._zod.parse(f,a))}return e._zod.parse(u,a)};e._zod.run=(i,c)=>{if(c.skipChecks)return e._zod.parse(i,c);if(c.direction==="backward"){let u=e._zod.parse({value:i.value,issues:[]},{...c,skipChecks:!0});return u instanceof Promise?u.then(f=>s(f,i,c)):s(u,i,c)}let a=e._zod.parse(i,c);if(a instanceof Promise){if(c.async===!1)throw new B;return a.then(u=>o(u,n,c))}return o(a,n,c)}}_(e,"~standard",()=>({validate:o=>{try{let s=gr(e,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return _r(e,o).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}))}),We=l("$ZodString",(e,t)=>{z.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??Gr(e._zod.bag),e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:e}),r}}),k=l("$ZodStringFormat",(e,t)=>{Se.init(e,t),We.init(e,t)}),kn=l("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=Ir),k.init(e,t)}),An=l("$ZodUUID",(e,t)=>{if(t.version){let n={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(n===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=bt(n))}else t.pattern??(t.pattern=bt());k.init(e,t)}),Zn=l("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=Tr),k.init(e,t)}),Sn=l("$ZodURL",(e,t)=>{k.init(e,t),e._zod.check=r=>{try{let n=r.value.trim();if(!t.normalize&&t.protocol?.source===Qr.source&&!/^https?:\/\//i.test(n)){r.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:r.value,inst:e,continue:!t.abort});return}let o=new URL(n);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(o.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:r.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:r.value,inst:e,continue:!t.abort})),t.normalize?r.value=o.href:r.value=n;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort})}}}),En=l("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=Dr()),k.init(e,t)}),Rn=l("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=Or),k.init(e,t)}),Pn=l("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=Zr),k.init(e,t)}),On=l("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=Sr),k.init(e,t)}),Cn=l("$ZodULID",(e,t)=>{t.pattern??(t.pattern=Er),k.init(e,t)}),In=l("$ZodXID",(e,t)=>{t.pattern??(t.pattern=Rr),k.init(e,t)}),Tn=l("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=Pr),k.init(e,t)}),Dn=l("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=Wr(t)),k.init(e,t)}),Nn=l("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=Jr),k.init(e,t)}),Fn=l("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=qr(t)),k.init(e,t)}),jn=l("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=Cr),k.init(e,t)}),Ln=l("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=Nr),k.init(e,t),e._zod.bag.format="ipv4"}),Mn=l("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=Fr),k.init(e,t),e._zod.bag.format="ipv6",e._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:e,continue:!t.abort})}}});var Qn=l("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=jr),k.init(e,t)}),Un=l("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=Lr),k.init(e,t),e._zod.check=r=>{let n=r.value.split("/");try{if(n.length!==2)throw new Error;let[o,s]=n;if(!s)throw new Error;let i=Number(s);if(`${i}`!==s)throw new Error;if(i<0||i>128)throw new Error;new URL(`http://[${o}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:e,continue:!t.abort})}}});function Bn(e){if(e==="")return!0;if(/\s/.test(e)||e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}var Jn=l("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=Mr),k.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=r=>{Bn(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}});function vc(e){if(!wt.test(e))return!1;let t=e.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=t.padEnd(Math.ceil(t.length/4)*4,"=");return Bn(r)}var Vn=l("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=wt),k.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=r=>{vc(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),qn=l("$ZodE164",(e,t)=>{t.pattern??(t.pattern=Ur),k.init(e,t)});function zc(e,t=null){try{let r=e.split(".");if(r.length!==3)return!1;let[n]=r;if(!n)return!1;let o=JSON.parse(atob(n));return!("typ"in o&&o?.typ!=="JWT"||!o.alg||t&&(!("alg"in o)||o.alg!==t))}catch{return!1}}var Wn=l("$ZodJWT",(e,t)=>{k.init(e,t),e._zod.check=r=>{zc(r.value,t.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}});var At=l("$ZodNumber",(e,t)=>{z.init(e,t),e._zod.pattern=e._zod.bag.pattern??vt,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=Number(r.value)}catch{}let o=r.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return r;let s=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:o,inst:e,...s?{received:s}:{}}),r}}),Gn=l("$ZodNumberFormat",(e,t)=>{nn.init(e,t),At.init(e,t)}),Kn=l("$ZodBoolean",(e,t)=>{z.init(e,t),e._zod.pattern=Xr,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=!!r.value}catch{}let o=r.value;return typeof o=="boolean"||r.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:e}),r}});var Xn=l("$ZodNull",(e,t)=>{z.init(e,t),e._zod.pattern=Yr,e._zod.values=new Set([null]),e._zod.parse=(r,n)=>{let o=r.value;return o===null||r.issues.push({expected:"null",code:"invalid_type",input:o,inst:e}),r}});var Yn=l("$ZodUnknown",(e,t)=>{z.init(e,t),e._zod.parse=r=>r}),Hn=l("$ZodNever",(e,t)=>{z.init(e,t),e._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:e}),r)});function gn(e,t,r){e.issues.length&&t.issues.push(...W(r,e.issues)),t.value[r]=e.value}var eo=l("$ZodArray",(e,t)=>{z.init(e,t),e._zod.parse=(r,n)=>{let o=r.value;if(!Array.isArray(o))return r.issues.push({expected:"array",code:"invalid_type",input:o,inst:e}),r;r.value=Array(o.length);let s=[];for(let i=0;i<o.length;i++){let c=o[i],a=t.element._zod.run({value:c,issues:[]},n);a instanceof Promise?s.push(a.then(u=>gn(u,r,i))):gn(a,r,i)}return s.length?Promise.all(s).then(()=>r):r}});function qe(e,t,r,n,o,s){let i=r in n;if(e.issues.length){if(o&&s&&!i)return;t.issues.push(...W(r,e.issues))}if(!i&&!o){e.issues.length||t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[r]});return}e.value===void 0?i&&(t.value[r]=void 0):t.value[r]=e.value}function to(e){let t=Object.keys(e.shape);for(let n of t)if(!e.shape?.[n]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${n}": expected a Zod schema`);let r=yt(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(r)}}function ro(e,t,r,n,o,s){let i=[],c=o.keySet,a=o.catchall._zod,u=a.def.type,f=a.optin==="optional",p=a.optout==="optional";for(let m in t){if(m==="__proto__"||c.has(m))continue;if(u==="never"){i.push(m);continue}let d=a.run({value:t[m],issues:[]},n);d instanceof Promise?e.push(d.then(y=>qe(y,r,m,t,f,p))):qe(d,r,m,t,f,p)}return i.length&&r.issues.push({code:"unrecognized_keys",keys:i,input:t,inst:s}),e.length?Promise.all(e).then(()=>r):r}var $c=l("$ZodObject",(e,t)=>{if(z.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){let c=t.shape;Object.defineProperty(t,"shape",{get:()=>{let a={...c};return Object.defineProperty(t,"shape",{value:a}),a}})}let n=fe(()=>to(t));_(e._zod,"propValues",()=>{let c=t.shape,a={};for(let u in c){let f=c[u]._zod;if(f.values){a[u]??(a[u]=new Set);for(let p of f.values)a[u].add(p)}}return a});let o=oe,s=t.catchall,i;e._zod.parse=(c,a)=>{i??(i=n.value);let u=c.value;if(!o(u))return c.issues.push({expected:"object",code:"invalid_type",input:u,inst:e}),c;c.value={};let f=[],p=i.shape;for(let m of i.keys){let d=p[m],y=d._zod.optin==="optional",O=d._zod.optout==="optional",w=d._zod.run({value:u[m],issues:[]},a);w instanceof Promise?f.push(w.then(j=>qe(j,c,m,u,y,O))):qe(w,c,m,u,y,O)}return s?ro(f,u,c,a,n.value,e):f.length?Promise.all(f).then(()=>c):c}}),no=l("$ZodObjectJIT",(e,t)=>{$c.init(e,t);let r=e._zod.parse,n=fe(()=>to(t)),o=m=>{let d=new Je(["shape","payload","ctx"]),y=n.value,O=N=>{let $=je(N);return`shape[${$}]._zod.run({ value: input[${$}], issues: [] }, ctx)`};d.write("const input = payload.value;");let w=Object.create(null),j=0;for(let N of y.keys)w[N]=`key_${j++}`;d.write("const newResult = {};");for(let N of y.keys){let $=w[N],C=je(N),nr=m[N],or=nr?._zod?.optin==="optional",Bi=nr?._zod?.optout==="optional";d.write(`const ${$} = ${O(N)};`),or&&Bi?d.write(`
+ if (${$}.issues.length) {
+ if (${C} in input) {
+ payload.issues = payload.issues.concat(${$}.issues.map(iss => ({
...iss,
- path: iss.path ? [${O}, ...iss.path] : [${O}]
+ path: iss.path ? [${C}, ...iss.path] : [${C}]
})));
}
}
- if (${Z}.value === undefined) {
- if (${O} in input) {
- newResult[${O}] = undefined;
+ if (${$}.value === undefined) {
+ if (${C} in input) {
+ newResult[${C}] = undefined;
}
} else {
- newResult[${O}] = ${Z}.value;
+ newResult[${C}] = ${$}.value;
}
- `):er?d.write(`
- if (${Z}.issues.length) {
- payload.issues = payload.issues.concat(${Z}.issues.map(iss => ({
+ `):or?d.write(`
+ if (${$}.issues.length) {
+ payload.issues = payload.issues.concat(${$}.issues.map(iss => ({
...iss,
- path: iss.path ? [${O}, ...iss.path] : [${O}]
+ path: iss.path ? [${C}, ...iss.path] : [${C}]
})));
}
- if (${Z}.value === undefined) {
- if (${O} in input) {
- newResult[${O}] = undefined;
+ if (${$}.value === undefined) {
+ if (${C} in input) {
+ newResult[${C}] = undefined;
}
} else {
- newResult[${O}] = ${Z}.value;
+ newResult[${C}] = ${$}.value;
}
`):d.write(`
- const ${Z}_present = ${O} in input;
- if (${Z}.issues.length) {
- payload.issues = payload.issues.concat(${Z}.issues.map(iss => ({
+ const ${$}_present = ${C} in input;
+ if (${$}.issues.length) {
+ payload.issues = payload.issues.concat(${$}.issues.map(iss => ({
...iss,
- path: iss.path ? [${O}, ...iss.path] : [${O}]
+ path: iss.path ? [${C}, ...iss.path] : [${C}]
})));
}
- if (!${Z}_present && !${Z}.issues.length) {
+ if (!${$}_present && !${$}.issues.length) {
payload.issues.push({
code: "invalid_type",
expected: "nonoptional",
input: undefined,
- path: [${O}]
+ path: [${C}]
});
}
- if (${Z}_present) {
- if (${Z}.value === undefined) {
- newResult[${O}] = undefined;
+ if (${$}_present) {
+ if (${$}.value === undefined) {
+ newResult[${C}] = undefined;
} else {
- newResult[${O}] = ${Z}.value;
+ newResult[${C}] = ${$}.value;
}
}
- `)}d.write("payload.value = newResult;"),d.write("return payload;");let Fi=d.compile();return(B,Z)=>Fi(m,B,Z)},s,i=re,c=!pe.jitless,u=c&&lt.value,f=t.catchall,p;e._zod.parse=(m,d)=>{p??(p=n.value);let y=m.value;return i(y)?c&&u&&d?.async===!1&&d.jitless!==!0?(s||(s=o(t.shape)),m=s(m,d),f?Yn([],y,m,d,p,e):m):r(m,d):(m.issues.push({expected:"object",code:"invalid_type",input:y,inst:e}),m)}});function mn(e,t,r,n){for(let s of e)if(s.issues.length===0)return t.value=s.value,t;let o=e.filter(s=>!X(s));return o.length===1?(t.value=o[0].value,o[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map(s=>s.issues.map(i=>j(i,n,M())))}),t)}var zt=l("$ZodUnion",(e,t)=>{z.init(e,t),_(e._zod,"optin",()=>t.options.some(n=>n._zod.optin==="optional")?"optional":void 0),_(e._zod,"optout",()=>t.options.some(n=>n._zod.optout==="optional")?"optional":void 0),_(e._zod,"values",()=>{if(t.options.every(n=>n._zod.values))return new Set(t.options.flatMap(n=>Array.from(n._zod.values)))}),_(e._zod,"pattern",()=>{if(t.options.every(n=>n._zod.pattern)){let n=t.options.map(o=>o._zod.pattern);return new RegExp(`^(${n.map(o=>ve(o.source)).join("|")})$`)}});let r=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(n,o)=>{if(r)return r(n,o);let s=!1,i=[];for(let c of t.options){let a=c._zod.run({value:n.value,issues:[]},o);if(a instanceof Promise)i.push(a),s=!0;else{if(a.issues.length===0)return a;i.push(a)}}return s?Promise.all(i).then(c=>mn(c,n,e,o)):mn(i,n,e,o)}});var eo=l("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,zt.init(e,t);let r=e._zod.parse;_(e._zod,"propValues",()=>{let o={};for(let s of t.options){let i=s._zod.propValues;if(!i||Object.keys(i).length===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(s)}"`);for(let[c,a]of Object.entries(i)){o[c]||(o[c]=new Set);for(let u of a)o[c].add(u)}}return o});let n=fe(()=>{let o=t.options,s=new Map;for(let i of o){let c=i._zod.propValues?.[t.discriminator];if(!c||c.size===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(i)}"`);for(let a of c){if(s.has(a))throw new Error(`Duplicate discriminator value "${String(a)}"`);s.set(a,i)}}return s});e._zod.parse=(o,s)=>{let i=o.value;if(!re(i))return o.issues.push({code:"invalid_type",expected:"object",input:i,inst:e}),o;let c=n.value.get(i?.[t.discriminator]);return c?c._zod.run(o,s):t.unionFallback||s.direction==="backward"?r(o,s):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:t.discriminator,options:Array.from(n.value.keys()),input:i,path:[t.discriminator],inst:e}),o)}}),to=l("$ZodIntersection",(e,t)=>{z.init(e,t),e._zod.parse=(r,n)=>{let o=r.value,s=t.left._zod.run({value:o,issues:[]},n),i=t.right._zod.run({value:o,issues:[]},n);return s instanceof Promise||i instanceof Promise?Promise.all([s,i]).then(([a,u])=>hn(r,a,u)):hn(r,s,i)}});function wt(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(K(e)&&K(t)){let r=Object.keys(t),n=Object.keys(e).filter(s=>r.indexOf(s)!==-1),o={...e,...t};for(let s of n){let i=wt(e[s],t[s]);if(!i.valid)return{valid:!1,mergeErrorPath:[s,...i.mergeErrorPath]};o[s]=i.data}return{valid:!0,data:o}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let n=0;n<e.length;n++){let o=e[n],s=t[n],i=wt(o,s);if(!i.valid)return{valid:!1,mergeErrorPath:[n,...i.mergeErrorPath]};r.push(i.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function hn(e,t,r){let n=new Map,o;for(let c of t.issues)if(c.code==="unrecognized_keys"){o??(o=c);for(let a of c.keys)n.has(a)||n.set(a,{}),n.get(a).l=!0}else e.issues.push(c);for(let c of r.issues)if(c.code==="unrecognized_keys")for(let a of c.keys)n.has(a)||n.set(a,{}),n.get(a).r=!0;else e.issues.push(c);let s=[...n].filter(([,c])=>c.l&&c.r).map(([c])=>c);if(s.length&&o&&e.issues.push({...o,keys:s}),X(e))return e;let i=wt(t.value,r.value);if(!i.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(i.mergeErrorPath)}`);return e.value=i.data,e}var ro=l("$ZodRecord",(e,t)=>{z.init(e,t),e._zod.parse=(r,n)=>{let o=r.value;if(!K(o))return r.issues.push({expected:"record",code:"invalid_type",input:o,inst:e}),r;let s=[],i=t.keyType._zod.values;if(i){r.value={};let c=new Set;for(let u of i)if(typeof u=="string"||typeof u=="number"||typeof u=="symbol"){c.add(typeof u=="number"?u.toString():u);let f=t.keyType._zod.run({value:u,issues:[]},n);if(f instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(f.issues.length){r.issues.push({code:"invalid_key",origin:"record",issues:f.issues.map(d=>j(d,n,M())),input:u,path:[u],inst:e});continue}let p=f.value,m=t.valueType._zod.run({value:o[u],issues:[]},n);m instanceof Promise?s.push(m.then(d=>{d.issues.length&&r.issues.push(...V(u,d.issues)),r.value[p]=d.value})):(m.issues.length&&r.issues.push(...V(u,m.issues)),r.value[p]=m.value)}let a;for(let u in o)c.has(u)||(a=a??[],a.push(u));a&&a.length>0&&r.issues.push({code:"unrecognized_keys",input:o,inst:e,keys:a})}else{r.value={};for(let c of Reflect.ownKeys(o)){if(c==="__proto__"||!Object.prototype.propertyIsEnumerable.call(o,c))continue;let a=t.keyType._zod.run({value:c,issues:[]},n);if(a instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(typeof c=="string"&&_t.test(c)&&a.issues.length){let p=t.keyType._zod.run({value:Number(c),issues:[]},n);if(p instanceof Promise)throw new Error("Async schemas not supported in object keys currently");p.issues.length===0&&(a=p)}if(a.issues.length){t.mode==="loose"?r.value[c]=o[c]:r.issues.push({code:"invalid_key",origin:"record",issues:a.issues.map(p=>j(p,n,M())),input:c,path:[c],inst:e});continue}let f=t.valueType._zod.run({value:o[c],issues:[]},n);f instanceof Promise?s.push(f.then(p=>{p.issues.length&&r.issues.push(...V(c,p.issues)),r.value[a.value]=p.value})):(f.issues.length&&r.issues.push(...V(c,f.issues)),r.value[a.value]=f.value)}}return s.length?Promise.all(s).then(()=>r):r}});var no=l("$ZodEnum",(e,t)=>{z.init(e,t);let r=be(t.entries),n=new Set(r);e._zod.values=n,e._zod.pattern=new RegExp(`^(${r.filter(o=>pt.has(typeof o)).map(o=>typeof o=="string"?q(o):o.toString()).join("|")})$`),e._zod.parse=(o,s)=>{let i=o.value;return n.has(i)||o.issues.push({code:"invalid_value",values:r,input:i,inst:e}),o}}),oo=l("$ZodLiteral",(e,t)=>{if(z.init(e,t),t.values.length===0)throw new Error("Cannot create literal schema with no valid values");let r=new Set(t.values);e._zod.values=r,e._zod.pattern=new RegExp(`^(${t.values.map(n=>typeof n=="string"?q(n):n?q(n.toString()):String(n)).join("|")})$`),e._zod.parse=(n,o)=>{let s=n.value;return r.has(s)||n.issues.push({code:"invalid_value",values:t.values,input:s,inst:e}),n}});var so=l("$ZodTransform",(e,t)=>{z.init(e,t),e._zod.optin="optional",e._zod.parse=(r,n)=>{if(n.direction==="backward")throw new le(e.constructor.name);let o=t.transform(r.value,r);if(n.async)return(o instanceof Promise?o:Promise.resolve(o)).then(i=>(r.value=i,r.fallback=!0,r));if(o instanceof Promise)throw new Q;return r.value=o,r.fallback=!0,r}});function yn(e,t){return t===void 0&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}var $t=l("$ZodOptional",(e,t)=>{z.init(e,t),e._zod.optin="optional",e._zod.optout="optional",_(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),_(e._zod,"pattern",()=>{let r=t.innerType._zod.pattern;return r?new RegExp(`^(${ve(r.source)})?$`):void 0}),e._zod.parse=(r,n)=>{if(t.innerType._zod.optin==="optional"){let o=r.value,s=t.innerType._zod.run(r,n);return s instanceof Promise?s.then(i=>yn(i,o)):yn(s,o)}return r.value===void 0?r:t.innerType._zod.run(r,n)}}),io=l("$ZodExactOptional",(e,t)=>{$t.init(e,t),_(e._zod,"values",()=>t.innerType._zod.values),_(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(r,n)=>t.innerType._zod.run(r,n)}),co=l("$ZodNullable",(e,t)=>{z.init(e,t),_(e._zod,"optin",()=>t.innerType._zod.optin),_(e._zod,"optout",()=>t.innerType._zod.optout),_(e._zod,"pattern",()=>{let r=t.innerType._zod.pattern;return r?new RegExp(`^(${ve(r.source)}|null)$`):void 0}),_(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(r,n)=>r.value===null?r:t.innerType._zod.run(r,n)}),ao=l("$ZodDefault",(e,t)=>{z.init(e,t),e._zod.optin="optional",_(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>{if(n.direction==="backward")return t.innerType._zod.run(r,n);if(r.value===void 0)return r.value=t.defaultValue,r;let o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>gn(s,t)):gn(o,t)}});function gn(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}var uo=l("$ZodPrefault",(e,t)=>{z.init(e,t),e._zod.optin="optional",_(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>(n.direction==="backward"||r.value===void 0&&(r.value=t.defaultValue),t.innerType._zod.run(r,n))}),lo=l("$ZodNonOptional",(e,t)=>{z.init(e,t),_(e._zod,"values",()=>{let r=t.innerType._zod.values;return r?new Set([...r].filter(n=>n!==void 0)):void 0}),e._zod.parse=(r,n)=>{let o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>_n(s,e)):_n(o,e)}});function _n(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}var po=l("$ZodCatch",(e,t)=>{z.init(e,t),e._zod.optin="optional",_(e._zod,"optout",()=>t.innerType._zod.optout),_(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>{if(n.direction==="backward")return t.innerType._zod.run(r,n);let o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>(r.value=s.value,s.issues.length&&(r.value=t.catchValue({...r,error:{issues:s.issues.map(i=>j(i,n,M()))},input:r.value}),r.issues=[],r.fallback=!0),r)):(r.value=o.value,o.issues.length&&(r.value=t.catchValue({...r,error:{issues:o.issues.map(s=>j(s,n,M()))},input:r.value}),r.issues=[],r.fallback=!0),r)}});var fo=l("$ZodPipe",(e,t)=>{z.init(e,t),_(e._zod,"values",()=>t.in._zod.values),_(e._zod,"optin",()=>t.in._zod.optin),_(e._zod,"optout",()=>t.out._zod.optout),_(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(r,n)=>{if(n.direction==="backward"){let s=t.out._zod.run(r,n);return s instanceof Promise?s.then(i=>Qe(i,t.in,n)):Qe(s,t.in,n)}let o=t.in._zod.run(r,n);return o instanceof Promise?o.then(s=>Qe(s,t.out,n)):Qe(o,t.out,n)}});function Qe(e,t,r){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues,fallback:e.fallback},r)}var mo=l("$ZodReadonly",(e,t)=>{z.init(e,t),_(e._zod,"propValues",()=>t.innerType._zod.propValues),_(e._zod,"values",()=>t.innerType._zod.values),_(e._zod,"optin",()=>t.innerType?._zod?.optin),_(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(r,n)=>{if(n.direction==="backward")return t.innerType._zod.run(r,n);let o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(xn):xn(o)}});function xn(e){return e.value=Object.freeze(e.value),e}var ho=l("$ZodLazy",(e,t)=>{z.init(e,t),_(e._zod,"innerType",()=>{let r=t;return r._cachedInner||(r._cachedInner=t.getter()),r._cachedInner}),_(e._zod,"pattern",()=>e._zod.innerType?._zod?.pattern),_(e._zod,"propValues",()=>e._zod.innerType?._zod?.propValues),_(e._zod,"optin",()=>e._zod.innerType?._zod?.optin??void 0),_(e._zod,"optout",()=>e._zod.innerType?._zod?.optout??void 0),e._zod.parse=(r,n)=>e._zod.innerType._zod.run(r,n)}),yo=l("$ZodCustom",(e,t)=>{I.init(e,t),z.init(e,t),e._zod.parse=(r,n)=>r,e._zod.check=r=>{let n=r.value,o=t.fn(n);if(o instanceof Promise)return o.then(s=>bn(s,r,n,e));bn(o,r,n,e)}});function bn(e,t,r,n){if(!e){let o={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(o.params=n._zod.def.params),t.issues.push(me(o))}}var go,Vu=Symbol("ZodOutput"),Wu=Symbol("ZodInput"),kt=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(t,...r){let n=r[0];return this._map.set(t,n),n&&typeof n=="object"&&"id"in n&&this._idmap.set(n.id,t),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(t){let r=this._map.get(t);return r&&typeof r=="object"&&"id"in r&&this._idmap.delete(r.id),this._map.delete(t),this}get(t){let r=t._zod.parent;if(r){let n={...this.get(r)??{}};delete n.id;let o={...n,...this._map.get(t)};return Object.keys(o).length?o:void 0}return this._map.get(t)}has(t){return this._map.has(t)}};function bc(){return new kt}(go=globalThis).__zod_globalRegistry??(go.__zod_globalRegistry=bc());var ne=globalThis.__zod_globalRegistry;function _o(e,t){return new e({type:"string",...h(t)})}function xo(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...h(t)})}function At(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...h(t)})}function bo(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...h(t)})}function wo(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...h(t)})}function vo(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...h(t)})}function zo(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...h(t)})}function $o(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...h(t)})}function ko(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...h(t)})}function Ao(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...h(t)})}function Zo(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...h(t)})}function So(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...h(t)})}function Eo(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...h(t)})}function Ro(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...h(t)})}function Po(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...h(t)})}function Oo(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...h(t)})}function Io(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...h(t)})}function To(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...h(t)})}function Co(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...h(t)})}function No(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...h(t)})}function Do(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...h(t)})}function Fo(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...h(t)})}function jo(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...h(t)})}function Lo(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...h(t)})}function Mo(e,t){return new e({type:"string",format:"date",check:"string_format",...h(t)})}function Uo(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...h(t)})}function Bo(e,t){return new e({type:"string",format:"duration",check:"string_format",...h(t)})}function Qo(e,t){return new e({type:"number",checks:[],...h(t)})}function Jo(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...h(t)})}function qo(e,t){return new e({type:"boolean",...h(t)})}function Vo(e,t){return new e({type:"null",...h(t)})}function Wo(e){return new e({type:"unknown"})}function Go(e,t){return new e({type:"never",...h(t)})}function Ve(e,t){return new xt({check:"less_than",...h(t),value:e,inclusive:!1})}function Ze(e,t){return new xt({check:"less_than",...h(t),value:e,inclusive:!0})}function We(e,t){return new bt({check:"greater_than",...h(t),value:e,inclusive:!1})}function Se(e,t){return new bt({check:"greater_than",...h(t),value:e,inclusive:!0})}function Ge(e,t){return new Yr({check:"multiple_of",...h(t),value:e})}function Ke(e,t){return new en({check:"max_length",...h(t),maximum:e})}function he(e,t){return new tn({check:"min_length",...h(t),minimum:e})}function Xe(e,t){return new rn({check:"length_equals",...h(t),length:e})}function Zt(e,t){return new nn({check:"string_format",format:"regex",...h(t),pattern:e})}function St(e){return new on({check:"string_format",format:"lowercase",...h(e)})}function Et(e){return new sn({check:"string_format",format:"uppercase",...h(e)})}function Rt(e,t){return new cn({check:"string_format",format:"includes",...h(t),includes:e})}function Pt(e,t){return new an({check:"string_format",format:"starts_with",...h(t),prefix:e})}function Ot(e,t){return new un({check:"string_format",format:"ends_with",...h(t),suffix:e})}function Y(e){return new ln({check:"overwrite",tx:e})}function It(e){return Y(t=>t.normalize(e))}function Tt(){return Y(e=>e.trim())}function Ct(){return Y(e=>e.toLowerCase())}function Nt(){return Y(e=>e.toUpperCase())}function Dt(){return Y(e=>ut(e))}function Ko(e,t,r){return new e({type:"array",element:t,...h(r)})}function Xo(e,t,r){return new e({type:"custom",check:"custom",fn:t,...h(r)})}function Yo(e,t){let r=wc(n=>(n.addIssue=o=>{if(typeof o=="string")n.issues.push(me(o,n.value,r._zod.def));else{let s=o;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=n.value),s.inst??(s.inst=r),s.continue??(s.continue=!r._zod.def.abort),n.issues.push(me(s))}},e(n.value,n)),t);return r}function wc(e,t){let r=new I({check:"custom",...h(t)});return r._zod.check=e,r}function Ft(e){let t=e?.target??"draft-2020-12";return t==="draft-4"&&(t="draft-04"),t==="draft-7"&&(t="draft-07"),{processors:e.processors??{},metadataRegistry:e?.metadata??ne,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,cycles:e?.cycles??"ref",reused:e?.reused??"inline",external:e?.external??void 0}}function S(e,t,r={path:[],schemaPath:[]}){var n;let o=e._zod.def,s=t.seen.get(e);if(s)return s.count++,r.schemaPath.includes(e)&&(s.cycle=r.path),s.schema;let i={schema:{},count:1,cycle:void 0,path:r.path};t.seen.set(e,i);let c=e._zod.toJSONSchema?.();if(c)i.schema=c;else{let f={...r,schemaPath:[...r.schemaPath,e],path:r.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,i.schema,f);else{let m=i.schema,d=t.processors[o.type];if(!d)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${o.type}`);d(e,t,m,f)}let p=e._zod.parent;p&&(i.ref||(i.ref=p),S(p,t,f),t.seen.get(p).isParent=!0)}let a=t.metadataRegistry.get(e);return a&&Object.assign(i.schema,a),t.io==="input"&&T(e)&&(delete i.schema.examples,delete i.schema.default),t.io==="input"&&"_prefault"in i.schema&&((n=i.schema).default??(n.default=i.schema._prefault)),delete i.schema._prefault,t.seen.get(e).schema}function jt(e,t){let r=e.seen.get(t);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");let n=new Map;for(let i of e.seen.entries()){let c=e.metadataRegistry.get(i[0])?.id;if(c){let a=n.get(c);if(a&&a!==i[0])throw new Error(`Duplicate schema id "${c}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);n.set(c,i[0])}}let o=i=>{let c=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){let p=e.external.registry.get(i[0])?.id,m=e.external.uri??(y=>y);if(p)return{ref:m(p)};let d=i[1].defId??i[1].schema.id??`schema${e.counter++}`;return i[1].defId=d,{defId:d,ref:`${m("__shared")}#/${c}/${d}`}}if(i[1]===r)return{ref:"#"};let u=`#/${c}/`,f=i[1].schema.id??`__schema${e.counter++}`;return{defId:f,ref:u+f}},s=i=>{if(i[1].schema.$ref)return;let c=i[1],{ref:a,defId:u}=o(i);c.def={...c.schema},u&&(c.defId=u);let f=c.schema;for(let p in f)delete f[p];f.$ref=a};if(e.cycles==="throw")for(let i of e.seen.entries()){let c=i[1];if(c.cycle)throw new Error(`Cycle detected: #/${c.cycle?.join("/")}/<root>
+ `)}d.write("payload.value = newResult;"),d.write("return payload;");let Fe=d.compile();return(N,$)=>Fe(m,N,$)},s,i=oe,c=!pe.jitless,u=c&&mt.value,f=t.catchall,p;e._zod.parse=(m,d)=>{p??(p=n.value);let y=m.value;return i(y)?c&&u&&d?.async===!1&&d.jitless!==!0?(s||(s=o(t.shape)),m=s(m,d),f?ro([],y,m,d,p,e):m):r(m,d):(m.issues.push({expected:"object",code:"invalid_type",input:y,inst:e}),m)}});function _n(e,t,r,n){for(let s of e)if(s.issues.length===0)return t.value=s.value,t;let o=e.filter(s=>!H(s));return o.length===1?(t.value=o[0].value,o[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map(s=>s.issues.map(i=>L(i,n,Q())))}),t)}var Zt=l("$ZodUnion",(e,t)=>{z.init(e,t),_(e._zod,"optin",()=>t.options.some(n=>n._zod.optin==="optional")?"optional":void 0),_(e._zod,"optout",()=>t.options.some(n=>n._zod.optout==="optional")?"optional":void 0),_(e._zod,"values",()=>{if(t.options.every(n=>n._zod.values))return new Set(t.options.flatMap(n=>Array.from(n._zod.values)))}),_(e._zod,"pattern",()=>{if(t.options.every(n=>n._zod.pattern)){let n=t.options.map(o=>o._zod.pattern);return new RegExp(`^(${n.map(o=>$e(o.source)).join("|")})$`)}});let r=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(n,o)=>{if(r)return r(n,o);let s=!1,i=[];for(let c of t.options){let a=c._zod.run({value:n.value,issues:[]},o);if(a instanceof Promise)i.push(a),s=!0;else{if(a.issues.length===0)return a;i.push(a)}}return s?Promise.all(i).then(c=>_n(c,n,e,o)):_n(i,n,e,o)}});var oo=l("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,Zt.init(e,t);let r=e._zod.parse;_(e._zod,"propValues",()=>{let o={};for(let s of t.options){let i=s._zod.propValues;if(!i||Object.keys(i).length===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(s)}"`);for(let[c,a]of Object.entries(i)){o[c]||(o[c]=new Set);for(let u of a)o[c].add(u)}}return o});let n=fe(()=>{let o=t.options,s=new Map;for(let i of o){let c=i._zod.propValues?.[t.discriminator];if(!c||c.size===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(i)}"`);for(let a of c){if(s.has(a))throw new Error(`Duplicate discriminator value "${String(a)}"`);s.set(a,i)}}return s});e._zod.parse=(o,s)=>{let i=o.value;if(!oe(i))return o.issues.push({code:"invalid_type",expected:"object",input:i,inst:e}),o;let c=n.value.get(i?.[t.discriminator]);return c?c._zod.run(o,s):t.unionFallback||s.direction==="backward"?r(o,s):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:t.discriminator,options:Array.from(n.value.keys()),input:i,path:[t.discriminator],inst:e}),o)}}),so=l("$ZodIntersection",(e,t)=>{z.init(e,t),e._zod.parse=(r,n)=>{let o=r.value,s=t.left._zod.run({value:o,issues:[]},n),i=t.right._zod.run({value:o,issues:[]},n);return s instanceof Promise||i instanceof Promise?Promise.all([s,i]).then(([a,u])=>xn(r,a,u)):xn(r,s,i)}});function kt(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(Y(e)&&Y(t)){let r=Object.keys(t),n=Object.keys(e).filter(s=>r.indexOf(s)!==-1),o={...e,...t};for(let s of n){let i=kt(e[s],t[s]);if(!i.valid)return{valid:!1,mergeErrorPath:[s,...i.mergeErrorPath]};o[s]=i.data}return{valid:!0,data:o}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let n=0;n<e.length;n++){let o=e[n],s=t[n],i=kt(o,s);if(!i.valid)return{valid:!1,mergeErrorPath:[n,...i.mergeErrorPath]};r.push(i.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function xn(e,t,r){let n=new Map,o;for(let c of t.issues)if(c.code==="unrecognized_keys"){o??(o=c);for(let a of c.keys)n.has(a)||n.set(a,{}),n.get(a).l=!0}else e.issues.push(c);for(let c of r.issues)if(c.code==="unrecognized_keys")for(let a of c.keys)n.has(a)||n.set(a,{}),n.get(a).r=!0;else e.issues.push(c);let s=[...n].filter(([,c])=>c.l&&c.r).map(([c])=>c);if(s.length&&o&&e.issues.push({...o,keys:s}),H(e))return e;let i=kt(t.value,r.value);if(!i.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(i.mergeErrorPath)}`);return e.value=i.data,e}var io=l("$ZodRecord",(e,t)=>{z.init(e,t),e._zod.parse=(r,n)=>{let o=r.value;if(!Y(o))return r.issues.push({expected:"record",code:"invalid_type",input:o,inst:e}),r;let s=[],i=t.keyType._zod.values;if(i){r.value={};let c=new Set;for(let u of i)if(typeof u=="string"||typeof u=="number"||typeof u=="symbol"){c.add(typeof u=="number"?u.toString():u);let f=t.keyType._zod.run({value:u,issues:[]},n);if(f instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(f.issues.length){r.issues.push({code:"invalid_key",origin:"record",issues:f.issues.map(d=>L(d,n,Q())),input:u,path:[u],inst:e});continue}let p=f.value,m=t.valueType._zod.run({value:o[u],issues:[]},n);m instanceof Promise?s.push(m.then(d=>{d.issues.length&&r.issues.push(...W(u,d.issues)),r.value[p]=d.value})):(m.issues.length&&r.issues.push(...W(u,m.issues)),r.value[p]=m.value)}let a;for(let u in o)c.has(u)||(a=a??[],a.push(u));a&&a.length>0&&r.issues.push({code:"unrecognized_keys",input:o,inst:e,keys:a})}else{r.value={};for(let c of Reflect.ownKeys(o)){if(c==="__proto__"||!Object.prototype.propertyIsEnumerable.call(o,c))continue;let a=t.keyType._zod.run({value:c,issues:[]},n);if(a instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(typeof c=="string"&&vt.test(c)&&a.issues.length){let p=t.keyType._zod.run({value:Number(c),issues:[]},n);if(p instanceof Promise)throw new Error("Async schemas not supported in object keys currently");p.issues.length===0&&(a=p)}if(a.issues.length){t.mode==="loose"?r.value[c]=o[c]:r.issues.push({code:"invalid_key",origin:"record",issues:a.issues.map(p=>L(p,n,Q())),input:c,path:[c],inst:e});continue}let f=t.valueType._zod.run({value:o[c],issues:[]},n);f instanceof Promise?s.push(f.then(p=>{p.issues.length&&r.issues.push(...W(c,p.issues)),r.value[a.value]=p.value})):(f.issues.length&&r.issues.push(...W(c,f.issues)),r.value[a.value]=f.value)}}return s.length?Promise.all(s).then(()=>r):r}});var co=l("$ZodEnum",(e,t)=>{z.init(e,t);let r=ve(t.entries),n=new Set(r);e._zod.values=n,e._zod.pattern=new RegExp(`^(${r.filter(o=>ht.has(typeof o)).map(o=>typeof o=="string"?q(o):o.toString()).join("|")})$`),e._zod.parse=(o,s)=>{let i=o.value;return n.has(i)||o.issues.push({code:"invalid_value",values:r,input:i,inst:e}),o}}),ao=l("$ZodLiteral",(e,t)=>{if(z.init(e,t),t.values.length===0)throw new Error("Cannot create literal schema with no valid values");let r=new Set(t.values);e._zod.values=r,e._zod.pattern=new RegExp(`^(${t.values.map(n=>typeof n=="string"?q(n):n?q(n.toString()):String(n)).join("|")})$`),e._zod.parse=(n,o)=>{let s=n.value;return r.has(s)||n.issues.push({code:"invalid_value",values:t.values,input:s,inst:e}),n}});var uo=l("$ZodTransform",(e,t)=>{z.init(e,t),e._zod.optin="optional",e._zod.parse=(r,n)=>{if(n.direction==="backward")throw new le(e.constructor.name);let o=t.transform(r.value,r);if(n.async)return(o instanceof Promise?o:Promise.resolve(o)).then(i=>(r.value=i,r.fallback=!0,r));if(o instanceof Promise)throw new B;return r.value=o,r.fallback=!0,r}});function bn(e,t){return t===void 0&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}var St=l("$ZodOptional",(e,t)=>{z.init(e,t),e._zod.optin="optional",e._zod.optout="optional",_(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),_(e._zod,"pattern",()=>{let r=t.innerType._zod.pattern;return r?new RegExp(`^(${$e(r.source)})?$`):void 0}),e._zod.parse=(r,n)=>{if(t.innerType._zod.optin==="optional"){let o=r.value,s=t.innerType._zod.run(r,n);return s instanceof Promise?s.then(i=>bn(i,o)):bn(s,o)}return r.value===void 0?r:t.innerType._zod.run(r,n)}}),lo=l("$ZodExactOptional",(e,t)=>{St.init(e,t),_(e._zod,"values",()=>t.innerType._zod.values),_(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(r,n)=>t.innerType._zod.run(r,n)}),po=l("$ZodNullable",(e,t)=>{z.init(e,t),_(e._zod,"optin",()=>t.innerType._zod.optin),_(e._zod,"optout",()=>t.innerType._zod.optout),_(e._zod,"pattern",()=>{let r=t.innerType._zod.pattern;return r?new RegExp(`^(${$e(r.source)}|null)$`):void 0}),_(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(r,n)=>r.value===null?r:t.innerType._zod.run(r,n)}),fo=l("$ZodDefault",(e,t)=>{z.init(e,t),e._zod.optin="optional",_(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>{if(n.direction==="backward")return t.innerType._zod.run(r,n);if(r.value===void 0)return r.value=t.defaultValue,r;let o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>wn(s,t)):wn(o,t)}});function wn(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}var mo=l("$ZodPrefault",(e,t)=>{z.init(e,t),e._zod.optin="optional",_(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>(n.direction==="backward"||r.value===void 0&&(r.value=t.defaultValue),t.innerType._zod.run(r,n))}),ho=l("$ZodNonOptional",(e,t)=>{z.init(e,t),_(e._zod,"values",()=>{let r=t.innerType._zod.values;return r?new Set([...r].filter(n=>n!==void 0)):void 0}),e._zod.parse=(r,n)=>{let o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>vn(s,e)):vn(o,e)}});function vn(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}var yo=l("$ZodCatch",(e,t)=>{z.init(e,t),e._zod.optin="optional",_(e._zod,"optout",()=>t.innerType._zod.optout),_(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>{if(n.direction==="backward")return t.innerType._zod.run(r,n);let o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>(r.value=s.value,s.issues.length&&(r.value=t.catchValue({...r,error:{issues:s.issues.map(i=>L(i,n,Q()))},input:r.value}),r.issues=[],r.fallback=!0),r)):(r.value=o.value,o.issues.length&&(r.value=t.catchValue({...r,error:{issues:o.issues.map(s=>L(s,n,Q()))},input:r.value}),r.issues=[],r.fallback=!0),r)}});var go=l("$ZodPipe",(e,t)=>{z.init(e,t),_(e._zod,"values",()=>t.in._zod.values),_(e._zod,"optin",()=>t.in._zod.optin),_(e._zod,"optout",()=>t.out._zod.optout),_(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(r,n)=>{if(n.direction==="backward"){let s=t.out._zod.run(r,n);return s instanceof Promise?s.then(i=>Ve(i,t.in,n)):Ve(s,t.in,n)}let o=t.in._zod.run(r,n);return o instanceof Promise?o.then(s=>Ve(s,t.out,n)):Ve(o,t.out,n)}});function Ve(e,t,r){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues,fallback:e.fallback},r)}var _o=l("$ZodReadonly",(e,t)=>{z.init(e,t),_(e._zod,"propValues",()=>t.innerType._zod.propValues),_(e._zod,"values",()=>t.innerType._zod.values),_(e._zod,"optin",()=>t.innerType?._zod?.optin),_(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(r,n)=>{if(n.direction==="backward")return t.innerType._zod.run(r,n);let o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(zn):zn(o)}});function zn(e){return e.value=Object.freeze(e.value),e}var xo=l("$ZodLazy",(e,t)=>{z.init(e,t),_(e._zod,"innerType",()=>{let r=t;return r._cachedInner||(r._cachedInner=t.getter()),r._cachedInner}),_(e._zod,"pattern",()=>e._zod.innerType?._zod?.pattern),_(e._zod,"propValues",()=>e._zod.innerType?._zod?.propValues),_(e._zod,"optin",()=>e._zod.innerType?._zod?.optin??void 0),_(e._zod,"optout",()=>e._zod.innerType?._zod?.optout??void 0),e._zod.parse=(r,n)=>e._zod.innerType._zod.run(r,n)}),bo=l("$ZodCustom",(e,t)=>{I.init(e,t),z.init(e,t),e._zod.parse=(r,n)=>r,e._zod.check=r=>{let n=r.value,o=t.fn(n);if(o instanceof Promise)return o.then(s=>$n(s,r,n,e));$n(o,r,n,e)}});function $n(e,t,r,n){if(!e){let o={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(o.params=n._zod.def.params),t.issues.push(me(o))}}var wo,el=Symbol("ZodOutput"),tl=Symbol("ZodInput"),Et=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(t,...r){let n=r[0];return this._map.set(t,n),n&&typeof n=="object"&&"id"in n&&this._idmap.set(n.id,t),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(t){let r=this._map.get(t);return r&&typeof r=="object"&&"id"in r&&this._idmap.delete(r.id),this._map.delete(t),this}get(t){let r=t._zod.parent;if(r){let n={...this.get(r)??{}};delete n.id;let o={...n,...this._map.get(t)};return Object.keys(o).length?o:void 0}return this._map.get(t)}has(t){return this._map.has(t)}};function kc(){return new Et}(wo=globalThis).__zod_globalRegistry??(wo.__zod_globalRegistry=kc());var se=globalThis.__zod_globalRegistry;function vo(e,t){return new e({type:"string",...h(t)})}function zo(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...h(t)})}function Rt(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...h(t)})}function $o(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...h(t)})}function ko(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...h(t)})}function Ao(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...h(t)})}function Zo(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...h(t)})}function So(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...h(t)})}function Eo(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...h(t)})}function Ro(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...h(t)})}function Po(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...h(t)})}function Oo(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...h(t)})}function Co(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...h(t)})}function Io(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...h(t)})}function To(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...h(t)})}function Do(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...h(t)})}function No(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...h(t)})}function Fo(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...h(t)})}function jo(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...h(t)})}function Lo(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...h(t)})}function Mo(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...h(t)})}function Qo(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...h(t)})}function Uo(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...h(t)})}function Bo(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...h(t)})}function Jo(e,t){return new e({type:"string",format:"date",check:"string_format",...h(t)})}function Vo(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...h(t)})}function qo(e,t){return new e({type:"string",format:"duration",check:"string_format",...h(t)})}function Wo(e,t){return new e({type:"number",checks:[],...h(t)})}function Go(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...h(t)})}function Ko(e,t){return new e({type:"boolean",...h(t)})}function Xo(e,t){return new e({type:"null",...h(t)})}function Yo(e){return new e({type:"unknown"})}function Ho(e,t){return new e({type:"never",...h(t)})}function Ge(e,t){return new zt({check:"less_than",...h(t),value:e,inclusive:!1})}function Ee(e,t){return new zt({check:"less_than",...h(t),value:e,inclusive:!0})}function Ke(e,t){return new $t({check:"greater_than",...h(t),value:e,inclusive:!1})}function Re(e,t){return new $t({check:"greater_than",...h(t),value:e,inclusive:!0})}function Xe(e,t){return new rn({check:"multiple_of",...h(t),value:e})}function Ye(e,t){return new on({check:"max_length",...h(t),maximum:e})}function he(e,t){return new sn({check:"min_length",...h(t),minimum:e})}function He(e,t){return new cn({check:"length_equals",...h(t),length:e})}function Pt(e,t){return new an({check:"string_format",format:"regex",...h(t),pattern:e})}function Ot(e){return new un({check:"string_format",format:"lowercase",...h(e)})}function Ct(e){return new ln({check:"string_format",format:"uppercase",...h(e)})}function It(e,t){return new pn({check:"string_format",format:"includes",...h(t),includes:e})}function Tt(e,t){return new dn({check:"string_format",format:"starts_with",...h(t),prefix:e})}function Dt(e,t){return new fn({check:"string_format",format:"ends_with",...h(t),suffix:e})}function ee(e){return new mn({check:"overwrite",tx:e})}function Nt(e){return ee(t=>t.normalize(e))}function Ft(){return ee(e=>e.trim())}function jt(){return ee(e=>e.toLowerCase())}function Lt(){return ee(e=>e.toUpperCase())}function Mt(){return ee(e=>ft(e))}function es(e,t,r){return new e({type:"array",element:t,...h(r)})}function ts(e,t,r){return new e({type:"custom",check:"custom",fn:t,...h(r)})}function rs(e,t){let r=Ac(n=>(n.addIssue=o=>{if(typeof o=="string")n.issues.push(me(o,n.value,r._zod.def));else{let s=o;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=n.value),s.inst??(s.inst=r),s.continue??(s.continue=!r._zod.def.abort),n.issues.push(me(s))}},e(n.value,n)),t);return r}function Ac(e,t){let r=new I({check:"custom",...h(t)});return r._zod.check=e,r}function Qt(e){let t=e?.target??"draft-2020-12";return t==="draft-4"&&(t="draft-04"),t==="draft-7"&&(t="draft-07"),{processors:e.processors??{},metadataRegistry:e?.metadata??se,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,cycles:e?.cycles??"ref",reused:e?.reused??"inline",external:e?.external??void 0}}function E(e,t,r={path:[],schemaPath:[]}){var n;let o=e._zod.def,s=t.seen.get(e);if(s)return s.count++,r.schemaPath.includes(e)&&(s.cycle=r.path),s.schema;let i={schema:{},count:1,cycle:void 0,path:r.path};t.seen.set(e,i);let c=e._zod.toJSONSchema?.();if(c)i.schema=c;else{let f={...r,schemaPath:[...r.schemaPath,e],path:r.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,i.schema,f);else{let m=i.schema,d=t.processors[o.type];if(!d)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${o.type}`);d(e,t,m,f)}let p=e._zod.parent;p&&(i.ref||(i.ref=p),E(p,t,f),t.seen.get(p).isParent=!0)}let a=t.metadataRegistry.get(e);return a&&Object.assign(i.schema,a),t.io==="input"&&T(e)&&(delete i.schema.examples,delete i.schema.default),t.io==="input"&&"_prefault"in i.schema&&((n=i.schema).default??(n.default=i.schema._prefault)),delete i.schema._prefault,t.seen.get(e).schema}function Ut(e,t){let r=e.seen.get(t);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");let n=new Map;for(let i of e.seen.entries()){let c=e.metadataRegistry.get(i[0])?.id;if(c){let a=n.get(c);if(a&&a!==i[0])throw new Error(`Duplicate schema id "${c}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);n.set(c,i[0])}}let o=i=>{let c=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){let p=e.external.registry.get(i[0])?.id,m=e.external.uri??(y=>y);if(p)return{ref:m(p)};let d=i[1].defId??i[1].schema.id??`schema${e.counter++}`;return i[1].defId=d,{defId:d,ref:`${m("__shared")}#/${c}/${d}`}}if(i[1]===r)return{ref:"#"};let u=`#/${c}/`,f=i[1].schema.id??`__schema${e.counter++}`;return{defId:f,ref:u+f}},s=i=>{if(i[1].schema.$ref)return;let c=i[1],{ref:a,defId:u}=o(i);c.def={...c.schema},u&&(c.defId=u);let f=c.schema;for(let p in f)delete f[p];f.$ref=a};if(e.cycles==="throw")for(let i of e.seen.entries()){let c=i[1];if(c.cycle)throw new Error(`Cycle detected: #/${c.cycle?.join("/")}/<root>
-Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let i of e.seen.entries()){let c=i[1];if(t===i[0]){s(i);continue}if(e.external){let u=e.external.registry.get(i[0])?.id;if(t!==i[0]&&u){s(i);continue}}if(e.metadataRegistry.get(i[0])?.id){s(i);continue}if(c.cycle){s(i);continue}if(c.count>1&&e.reused==="ref"){s(i);continue}}}function Lt(e,t){let r=e.seen.get(t);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");let n=c=>{let a=e.seen.get(c);if(a.ref===null)return;let u=a.def??a.schema,f={...u},p=a.ref;if(a.ref=null,p){n(p);let d=e.seen.get(p),y=d.schema;if(y.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(u.allOf=u.allOf??[],u.allOf.push(y)):Object.assign(u,y),Object.assign(u,f),c._zod.parent===p)for(let w in u)w==="$ref"||w==="allOf"||w in f||delete u[w];if(y.$ref&&d.def)for(let w in u)w==="$ref"||w==="allOf"||w in d.def&&JSON.stringify(u[w])===JSON.stringify(d.def[w])&&delete u[w]}let m=c._zod.parent;if(m&&m!==p){n(m);let d=e.seen.get(m);if(d?.schema.$ref&&(u.$ref=d.schema.$ref,d.def))for(let y in u)y==="$ref"||y==="allOf"||y in d.def&&JSON.stringify(u[y])===JSON.stringify(d.def[y])&&delete u[y]}e.override({zodSchema:c,jsonSchema:u,path:a.path??[]})};for(let c of[...e.seen.entries()].reverse())n(c[0]);let o={};if(e.target==="draft-2020-12"?o.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?o.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?o.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){let c=e.external.registry.get(t)?.id;if(!c)throw new Error("Schema is missing an `id` property");o.$id=e.external.uri(c)}Object.assign(o,r.def??r.schema);let s=e.metadataRegistry.get(t)?.id;s!==void 0&&o.id===s&&delete o.id;let i=e.external?.defs??{};for(let c of e.seen.entries()){let a=c[1];a.def&&a.defId&&(a.def.id===a.defId&&delete a.def.id,i[a.defId]=a.def)}e.external||Object.keys(i).length>0&&(e.target==="draft-2020-12"?o.$defs=i:o.definitions=i);try{let c=JSON.parse(JSON.stringify(o));return Object.defineProperty(c,"~standard",{value:{...t["~standard"],jsonSchema:{input:Ee(t,"input",e.processors),output:Ee(t,"output",e.processors)}},enumerable:!1,writable:!1}),c}catch{throw new Error("Error converting schema to JSON.")}}function T(e,t){let r=t??{seen:new Set};if(r.seen.has(e))return!1;r.seen.add(e);let n=e._zod.def;if(n.type==="transform")return!0;if(n.type==="array")return T(n.element,r);if(n.type==="set")return T(n.valueType,r);if(n.type==="lazy")return T(n.getter(),r);if(n.type==="promise"||n.type==="optional"||n.type==="nonoptional"||n.type==="nullable"||n.type==="readonly"||n.type==="default"||n.type==="prefault")return T(n.innerType,r);if(n.type==="intersection")return T(n.left,r)||T(n.right,r);if(n.type==="record"||n.type==="map")return T(n.keyType,r)||T(n.valueType,r);if(n.type==="pipe")return e._zod.traits.has("$ZodCodec")?!0:T(n.in,r)||T(n.out,r);if(n.type==="object"){for(let o in n.shape)if(T(n.shape[o],r))return!0;return!1}if(n.type==="union"){for(let o of n.options)if(T(o,r))return!0;return!1}if(n.type==="tuple"){for(let o of n.items)if(T(o,r))return!0;return!!(n.rest&&T(n.rest,r))}return!1}var Ho=(e,t={})=>r=>{let n=Ft({...r,processors:t});return S(e,n),jt(n,e),Lt(n,e)},Ee=(e,t,r={})=>n=>{let{libraryOptions:o,target:s}=n??{},i=Ft({...o??{},target:s,io:t,processors:r});return S(e,i),jt(i,e),Lt(i,e)};var vc={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},es=(e,t,r,n)=>{let o=r;o.type="string";let{minimum:s,maximum:i,format:c,patterns:a,contentEncoding:u}=e._zod.bag;if(typeof s=="number"&&(o.minLength=s),typeof i=="number"&&(o.maxLength=i),c&&(o.format=vc[c]??c,o.format===""&&delete o.format,c==="time"&&delete o.format),u&&(o.contentEncoding=u),a&&a.size>0){let f=[...a];f.length===1?o.pattern=f[0].source:f.length>1&&(o.allOf=[...f.map(p=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:p.source}))])}},ts=(e,t,r,n)=>{let o=r,{minimum:s,maximum:i,format:c,multipleOf:a,exclusiveMaximum:u,exclusiveMinimum:f}=e._zod.bag;typeof c=="string"&&c.includes("int")?o.type="integer":o.type="number";let p=typeof f=="number"&&f>=(s??Number.NEGATIVE_INFINITY),m=typeof u=="number"&&u<=(i??Number.POSITIVE_INFINITY),d=t.target==="draft-04"||t.target==="openapi-3.0";p?d?(o.minimum=f,o.exclusiveMinimum=!0):o.exclusiveMinimum=f:typeof s=="number"&&(o.minimum=s),m?d?(o.maximum=u,o.exclusiveMaximum=!0):o.exclusiveMaximum=u:typeof i=="number"&&(o.maximum=i),typeof a=="number"&&(o.multipleOf=a)},rs=(e,t,r,n)=>{r.type="boolean"};var ns=(e,t,r,n)=>{t.target==="openapi-3.0"?(r.type="string",r.nullable=!0,r.enum=[null]):r.type="null"};var os=(e,t,r,n)=>{r.not={}};var ss=(e,t,r,n)=>{};var is=(e,t,r,n)=>{let o=e._zod.def,s=be(o.entries);s.every(i=>typeof i=="number")&&(r.type="number"),s.every(i=>typeof i=="string")&&(r.type="string"),r.enum=s},cs=(e,t,r,n)=>{let o=e._zod.def,s=[];for(let i of o.values)if(i===void 0){if(t.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof i=="bigint"){if(t.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");s.push(Number(i))}else s.push(i);if(s.length!==0)if(s.length===1){let i=s[0];r.type=i===null?"null":typeof i,t.target==="draft-04"||t.target==="openapi-3.0"?r.enum=[i]:r.const=i}else s.every(i=>typeof i=="number")&&(r.type="number"),s.every(i=>typeof i=="string")&&(r.type="string"),s.every(i=>typeof i=="boolean")&&(r.type="boolean"),s.every(i=>i===null)&&(r.type="null"),r.enum=s};var as=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")};var us=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")};var ls=(e,t,r,n)=>{let o=r,s=e._zod.def,{minimum:i,maximum:c}=e._zod.bag;typeof i=="number"&&(o.minItems=i),typeof c=="number"&&(o.maxItems=c),o.type="array",o.items=S(s.element,t,{...n,path:[...n.path,"items"]})},ps=(e,t,r,n)=>{let o=r,s=e._zod.def;o.type="object",o.properties={};let i=s.shape;for(let u in i)o.properties[u]=S(i[u],t,{...n,path:[...n.path,"properties",u]});let c=new Set(Object.keys(i)),a=new Set([...c].filter(u=>{let f=s.shape[u]._zod;return t.io==="input"?f.optin===void 0:f.optout===void 0}));a.size>0&&(o.required=Array.from(a)),s.catchall?._zod.def.type==="never"?o.additionalProperties=!1:s.catchall?s.catchall&&(o.additionalProperties=S(s.catchall,t,{...n,path:[...n.path,"additionalProperties"]})):t.io==="output"&&(o.additionalProperties=!1)},ds=(e,t,r,n)=>{let o=e._zod.def,s=o.inclusive===!1,i=o.options.map((c,a)=>S(c,t,{...n,path:[...n.path,s?"oneOf":"anyOf",a]}));s?r.oneOf=i:r.anyOf=i},fs=(e,t,r,n)=>{let o=e._zod.def,s=S(o.left,t,{...n,path:[...n.path,"allOf",0]}),i=S(o.right,t,{...n,path:[...n.path,"allOf",1]}),c=u=>"allOf"in u&&Object.keys(u).length===1,a=[...c(s)?s.allOf:[s],...c(i)?i.allOf:[i]];r.allOf=a};var ms=(e,t,r,n)=>{let o=r,s=e._zod.def;o.type="object";let i=s.keyType,a=i._zod.bag?.patterns;if(s.mode==="loose"&&a&&a.size>0){let f=S(s.valueType,t,{...n,path:[...n.path,"patternProperties","*"]});o.patternProperties={};for(let p of a)o.patternProperties[p.source]=f}else(t.target==="draft-07"||t.target==="draft-2020-12")&&(o.propertyNames=S(s.keyType,t,{...n,path:[...n.path,"propertyNames"]})),o.additionalProperties=S(s.valueType,t,{...n,path:[...n.path,"additionalProperties"]});let u=i._zod.values;if(u){let f=[...u].filter(p=>typeof p=="string"||typeof p=="number");f.length>0&&(o.required=f)}},hs=(e,t,r,n)=>{let o=e._zod.def,s=S(o.innerType,t,n),i=t.seen.get(e);t.target==="openapi-3.0"?(i.ref=o.innerType,r.nullable=!0):r.anyOf=[s,{type:"null"}]},ys=(e,t,r,n)=>{let o=e._zod.def;S(o.innerType,t,n);let s=t.seen.get(e);s.ref=o.innerType},gs=(e,t,r,n)=>{let o=e._zod.def;S(o.innerType,t,n);let s=t.seen.get(e);s.ref=o.innerType,r.default=JSON.parse(JSON.stringify(o.defaultValue))},_s=(e,t,r,n)=>{let o=e._zod.def;S(o.innerType,t,n);let s=t.seen.get(e);s.ref=o.innerType,t.io==="input"&&(r._prefault=JSON.parse(JSON.stringify(o.defaultValue)))},xs=(e,t,r,n)=>{let o=e._zod.def;S(o.innerType,t,n);let s=t.seen.get(e);s.ref=o.innerType;let i;try{i=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}r.default=i},bs=(e,t,r,n)=>{let o=e._zod.def,s=o.in._zod.traits.has("$ZodTransform"),i=t.io==="input"?s?o.out:o.in:o.out;S(i,t,n);let c=t.seen.get(e);c.ref=i},ws=(e,t,r,n)=>{let o=e._zod.def;S(o.innerType,t,n);let s=t.seen.get(e);s.ref=o.innerType,r.readOnly=!0};var Mt=(e,t,r,n)=>{let o=e._zod.def;S(o.innerType,t,n);let s=t.seen.get(e);s.ref=o.innerType},vs=(e,t,r,n)=>{let o=e._zod.innerType;S(o,t,n);let s=t.seen.get(e);s.ref=o};var Ec=l("ZodISODateTime",(e,t)=>{On.init(e,t),A.init(e,t)});function zs(e){return Lo(Ec,e)}var Rc=l("ZodISODate",(e,t)=>{In.init(e,t),A.init(e,t)});function $s(e){return Mo(Rc,e)}var Pc=l("ZodISOTime",(e,t)=>{Tn.init(e,t),A.init(e,t)});function ks(e){return Uo(Pc,e)}var Oc=l("ZodISODuration",(e,t)=>{Cn.init(e,t),A.init(e,t)});function As(e){return Bo(Oc,e)}var Cc=(e,t)=>{je.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:r=>dr(e,r)},flatten:{value:r=>pr(e,r)},addIssue:{value:r=>{e.issues.push(r),e.message=JSON.stringify(e.issues,de,2)}},addIssues:{value:r=>{e.issues.push(...r),e.message=JSON.stringify(e.issues,de,2)}},isEmpty:{get(){return e.issues.length===0}}})};var D=l("ZodError",Cc,{Parent:Error});var Zs=Le(D),Ss=Me(D),Es=$e(D),Rs=ke(D),Ps=hr(D),Os=yr(D),Is=gr(D),Ts=_r(D),Cs=xr(D),Ns=br(D),Ds=wr(D),Fs=vr(D);var js=new WeakMap;function Re(e,t,r){let n=Object.getPrototypeOf(e),o=js.get(n);if(o||(o=new Set,js.set(n,o)),!o.has(t)){o.add(t);for(let s in r){let i=r[s];Object.defineProperty(n,s,{configurable:!0,enumerable:!1,get(){let c=i.bind(this);return Object.defineProperty(this,s,{configurable:!0,writable:!0,enumerable:!0,value:c}),c},set(c){Object.defineProperty(this,s,{configurable:!0,writable:!0,enumerable:!0,value:c})}})}}}var k=l("ZodType",(e,t)=>(z.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:Ee(e,"input"),output:Ee(e,"output")}}),e.toJSONSchema=Ho(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(r,n)=>Zs(e,r,n,{callee:e.parse}),e.safeParse=(r,n)=>Es(e,r,n),e.parseAsync=async(r,n)=>Ss(e,r,n,{callee:e.parseAsync}),e.safeParseAsync=async(r,n)=>Rs(e,r,n),e.spa=e.safeParseAsync,e.encode=(r,n)=>Ps(e,r,n),e.decode=(r,n)=>Os(e,r,n),e.encodeAsync=async(r,n)=>Is(e,r,n),e.decodeAsync=async(r,n)=>Ts(e,r,n),e.safeEncode=(r,n)=>Cs(e,r,n),e.safeDecode=(r,n)=>Ns(e,r,n),e.safeEncodeAsync=async(r,n)=>Ds(e,r,n),e.safeDecodeAsync=async(r,n)=>Fs(e,r,n),Re(e,"ZodType",{check(...r){let n=this.def;return this.clone(x.mergeDefs(n,{checks:[...n.checks??[],...r.map(o=>typeof o=="function"?{_zod:{check:o,def:{check:"custom"},onattach:[]}}:o)]}),{parent:!0})},with(...r){return this.check(...r)},clone(r,n){return U(this,r,n)},brand(){return this},register(r,n){return r.add(this,n),this},refine(r,n){return this.check(Ea(r,n))},superRefine(r,n){return this.check(Ra(r,n))},overwrite(r){return this.check(Y(r))},optional(){return Qs(this)},exactOptional(){return ha(this)},nullable(){return Js(this)},nullish(){return Qs(Js(this))},nonoptional(r){return wa(this,r)},array(){return N(this)},or(r){return et([this,r])},and(r){return la(this,r)},transform(r){return qs(this,fa(r))},default(r){return _a(this,r)},prefault(r){return ba(this,r)},catch(r){return za(this,r)},pipe(r){return qs(this,r)},readonly(){return Aa(this)},describe(r){let n=this.clone();return ne.add(n,{description:r}),n},meta(...r){if(r.length===0)return ne.get(this);let n=this.clone();return ne.add(n,r[0]),n},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(r){return r(this)}}),Object.defineProperty(e,"description",{get(){return ne.get(e)?.description},configurable:!0}),e)),Vs=l("_ZodString",(e,t)=>{qe.init(e,t),k.init(e,t),e._zod.processJSONSchema=(n,o,s)=>es(e,n,o,s);let r=e._zod.bag;e.format=r.format??null,e.minLength=r.minimum??null,e.maxLength=r.maximum??null,Re(e,"_ZodString",{regex(...n){return this.check(Zt(...n))},includes(...n){return this.check(Rt(...n))},startsWith(...n){return this.check(Pt(...n))},endsWith(...n){return this.check(Ot(...n))},min(...n){return this.check(he(...n))},max(...n){return this.check(Ke(...n))},length(...n){return this.check(Xe(...n))},nonempty(...n){return this.check(he(1,...n))},lowercase(n){return this.check(St(n))},uppercase(n){return this.check(Et(n))},trim(){return this.check(Tt())},normalize(...n){return this.check(It(...n))},toLowerCase(){return this.check(Ct())},toUpperCase(){return this.check(Nt())},slugify(){return this.check(Dt())}})}),Dc=l("ZodString",(e,t)=>{qe.init(e,t),Vs.init(e,t),e.email=r=>e.check(xo(Fc,r)),e.url=r=>e.check($o(jc,r)),e.jwt=r=>e.check(jo(ea,r)),e.emoji=r=>e.check(ko(Lc,r)),e.guid=r=>e.check(At(Ls,r)),e.uuid=r=>e.check(bo(He,r)),e.uuidv4=r=>e.check(wo(He,r)),e.uuidv6=r=>e.check(vo(He,r)),e.uuidv7=r=>e.check(zo(He,r)),e.nanoid=r=>e.check(Ao(Mc,r)),e.guid=r=>e.check(At(Ls,r)),e.cuid=r=>e.check(Zo(Uc,r)),e.cuid2=r=>e.check(So(Bc,r)),e.ulid=r=>e.check(Eo(Qc,r)),e.base64=r=>e.check(No(Xc,r)),e.base64url=r=>e.check(Do(Yc,r)),e.xid=r=>e.check(Ro(Jc,r)),e.ksuid=r=>e.check(Po(qc,r)),e.ipv4=r=>e.check(Oo(Vc,r)),e.ipv6=r=>e.check(Io(Wc,r)),e.cidrv4=r=>e.check(To(Gc,r)),e.cidrv6=r=>e.check(Co(Kc,r)),e.e164=r=>e.check(Fo(Hc,r)),e.datetime=r=>e.check(zs(r)),e.date=r=>e.check($s(r)),e.time=r=>e.check(ks(r)),e.duration=r=>e.check(As(r))});function g(e){return _o(Dc,e)}var A=l("ZodStringFormat",(e,t)=>{$.init(e,t),Vs.init(e,t)}),Fc=l("ZodEmail",(e,t)=>{zn.init(e,t),A.init(e,t)});var Ls=l("ZodGUID",(e,t)=>{wn.init(e,t),A.init(e,t)});var He=l("ZodUUID",(e,t)=>{vn.init(e,t),A.init(e,t)});var jc=l("ZodURL",(e,t)=>{$n.init(e,t),A.init(e,t)});var Lc=l("ZodEmoji",(e,t)=>{kn.init(e,t),A.init(e,t)});var Mc=l("ZodNanoID",(e,t)=>{An.init(e,t),A.init(e,t)});var Uc=l("ZodCUID",(e,t)=>{Zn.init(e,t),A.init(e,t)});var Bc=l("ZodCUID2",(e,t)=>{Sn.init(e,t),A.init(e,t)});var Qc=l("ZodULID",(e,t)=>{En.init(e,t),A.init(e,t)});var Jc=l("ZodXID",(e,t)=>{Rn.init(e,t),A.init(e,t)});var qc=l("ZodKSUID",(e,t)=>{Pn.init(e,t),A.init(e,t)});var Vc=l("ZodIPv4",(e,t)=>{Nn.init(e,t),A.init(e,t)});var Wc=l("ZodIPv6",(e,t)=>{Dn.init(e,t),A.init(e,t)});var Gc=l("ZodCIDRv4",(e,t)=>{Fn.init(e,t),A.init(e,t)});var Kc=l("ZodCIDRv6",(e,t)=>{jn.init(e,t),A.init(e,t)});var Xc=l("ZodBase64",(e,t)=>{Mn.init(e,t),A.init(e,t)});var Yc=l("ZodBase64URL",(e,t)=>{Un.init(e,t),A.init(e,t)});var Hc=l("ZodE164",(e,t)=>{Bn.init(e,t),A.init(e,t)});var ea=l("ZodJWT",(e,t)=>{Qn.init(e,t),A.init(e,t)});var Ws=l("ZodNumber",(e,t)=>{vt.init(e,t),k.init(e,t),e._zod.processJSONSchema=(n,o,s)=>ts(e,n,o,s),Re(e,"ZodNumber",{gt(n,o){return this.check(We(n,o))},gte(n,o){return this.check(Se(n,o))},min(n,o){return this.check(Se(n,o))},lt(n,o){return this.check(Ve(n,o))},lte(n,o){return this.check(Ze(n,o))},max(n,o){return this.check(Ze(n,o))},int(n){return this.check(Ms(n))},safe(n){return this.check(Ms(n))},positive(n){return this.check(We(0,n))},nonnegative(n){return this.check(Se(0,n))},negative(n){return this.check(Ve(0,n))},nonpositive(n){return this.check(Ze(0,n))},multipleOf(n,o){return this.check(Ge(n,o))},step(n,o){return this.check(Ge(n,o))},finite(){return this}});let r=e._zod.bag;e.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),e.isFinite=!0,e.format=r.format??null});function v(e){return Qo(Ws,e)}var ta=l("ZodNumberFormat",(e,t)=>{Jn.init(e,t),Ws.init(e,t)});function Ms(e){return Jo(ta,e)}var ra=l("ZodBoolean",(e,t)=>{qn.init(e,t),k.init(e,t),e._zod.processJSONSchema=(r,n,o)=>rs(e,r,n,o)});function oe(e){return qo(ra,e)}var na=l("ZodNull",(e,t)=>{Vn.init(e,t),k.init(e,t),e._zod.processJSONSchema=(r,n,o)=>ns(e,r,n,o)});function oa(e){return Vo(na,e)}var sa=l("ZodUnknown",(e,t)=>{Wn.init(e,t),k.init(e,t),e._zod.processJSONSchema=(r,n,o)=>ss(e,r,n,o)});function Us(){return Wo(sa)}var ia=l("ZodNever",(e,t)=>{Gn.init(e,t),k.init(e,t),e._zod.processJSONSchema=(r,n,o)=>os(e,r,n,o)});function Gs(e){return Go(ia,e)}var ca=l("ZodArray",(e,t)=>{Kn.init(e,t),k.init(e,t),e._zod.processJSONSchema=(r,n,o)=>ls(e,r,n,o),e.element=t.element,Re(e,"ZodArray",{min(r,n){return this.check(he(r,n))},nonempty(r){return this.check(he(1,r))},max(r,n){return this.check(Ke(r,n))},length(r,n){return this.check(Xe(r,n))},unwrap(){return this.element}})});function N(e,t){return Ko(ca,e,t)}var Ks=l("ZodObject",(e,t)=>{Hn.init(e,t),k.init(e,t),e._zod.processJSONSchema=(r,n,o)=>ps(e,r,n,o),x.defineLazy(e,"shape",()=>t.shape),Re(e,"ZodObject",{keyof(){return H(Object.keys(this._zod.def.shape))},catchall(r){return this.clone({...this._zod.def,catchall:r})},passthrough(){return this.clone({...this._zod.def,catchall:Us()})},loose(){return this.clone({...this._zod.def,catchall:Us()})},strict(){return this.clone({...this._zod.def,catchall:Gs()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(r){return x.extend(this,r)},safeExtend(r){return x.safeExtend(this,r)},merge(r){return x.merge(this,r)},pick(r){return x.pick(this,r)},omit(r){return x.omit(this,r)},partial(...r){return x.partial(Ys,this,r[0])},required(...r){return x.required(Hs,this,r[0])}})});function L(e,t){let r={type:"object",shape:e??{},...x.normalizeParams(t)};return new Ks(r)}function E(e,t){return new Ks({type:"object",shape:e,catchall:Gs(),...x.normalizeParams(t)})}var Xs=l("ZodUnion",(e,t)=>{zt.init(e,t),k.init(e,t),e._zod.processJSONSchema=(r,n,o)=>ds(e,r,n,o),e.options=t.options});function et(e,t){return new Xs({type:"union",options:e,...x.normalizeParams(t)})}var aa=l("ZodDiscriminatedUnion",(e,t)=>{Xs.init(e,t),eo.init(e,t)});function tt(e,t,r){return new aa({type:"union",options:t,discriminator:e,...x.normalizeParams(r)})}var ua=l("ZodIntersection",(e,t)=>{to.init(e,t),k.init(e,t),e._zod.processJSONSchema=(r,n,o)=>fs(e,r,n,o)});function la(e,t){return new ua({type:"intersection",left:e,right:t})}var Bs=l("ZodRecord",(e,t)=>{ro.init(e,t),k.init(e,t),e._zod.processJSONSchema=(r,n,o)=>ms(e,r,n,o),e.keyType=t.keyType,e.valueType=t.valueType});function se(e,t,r){return!t||!t._zod?new Bs({type:"record",keyType:g(),valueType:e,...x.normalizeParams(t)}):new Bs({type:"record",keyType:e,valueType:t,...x.normalizeParams(r)})}var Ut=l("ZodEnum",(e,t)=>{no.init(e,t),k.init(e,t),e._zod.processJSONSchema=(n,o,s)=>is(e,n,o,s),e.enum=t.entries,e.options=Object.values(t.entries);let r=new Set(Object.keys(t.entries));e.extract=(n,o)=>{let s={};for(let i of n)if(r.has(i))s[i]=t.entries[i];else throw new Error(`Key ${i} not found in enum`);return new Ut({...t,checks:[],...x.normalizeParams(o),entries:s})},e.exclude=(n,o)=>{let s={...t.entries};for(let i of n)if(r.has(i))delete s[i];else throw new Error(`Key ${i} not found in enum`);return new Ut({...t,checks:[],...x.normalizeParams(o),entries:s})}});function H(e,t){let r=Array.isArray(e)?Object.fromEntries(e.map(n=>[n,n])):e;return new Ut({type:"enum",entries:r,...x.normalizeParams(t)})}var pa=l("ZodLiteral",(e,t)=>{oo.init(e,t),k.init(e,t),e._zod.processJSONSchema=(r,n,o)=>cs(e,r,n,o),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function R(e,t){return new pa({type:"literal",values:Array.isArray(e)?e:[e],...x.normalizeParams(t)})}var da=l("ZodTransform",(e,t)=>{so.init(e,t),k.init(e,t),e._zod.processJSONSchema=(r,n,o)=>us(e,r,n,o),e._zod.parse=(r,n)=>{if(n.direction==="backward")throw new le(e.constructor.name);r.addIssue=s=>{if(typeof s=="string")r.issues.push(x.issue(s,r.value,t));else{let i=s;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=r.value),i.inst??(i.inst=e),r.issues.push(x.issue(i))}};let o=t.transform(r.value,r);return o instanceof Promise?o.then(s=>(r.value=s,r.fallback=!0,r)):(r.value=o,r.fallback=!0,r)}});function fa(e){return new da({type:"transform",transform:e})}var Ys=l("ZodOptional",(e,t)=>{$t.init(e,t),k.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Mt(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});function Qs(e){return new Ys({type:"optional",innerType:e})}var ma=l("ZodExactOptional",(e,t)=>{io.init(e,t),k.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Mt(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});function ha(e){return new ma({type:"optional",innerType:e})}var ya=l("ZodNullable",(e,t)=>{co.init(e,t),k.init(e,t),e._zod.processJSONSchema=(r,n,o)=>hs(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});function Js(e){return new ya({type:"nullable",innerType:e})}var ga=l("ZodDefault",(e,t)=>{ao.init(e,t),k.init(e,t),e._zod.processJSONSchema=(r,n,o)=>gs(e,r,n,o),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function _a(e,t){return new ga({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():x.shallowClone(t)}})}var xa=l("ZodPrefault",(e,t)=>{uo.init(e,t),k.init(e,t),e._zod.processJSONSchema=(r,n,o)=>_s(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});function ba(e,t){return new xa({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():x.shallowClone(t)}})}var Hs=l("ZodNonOptional",(e,t)=>{lo.init(e,t),k.init(e,t),e._zod.processJSONSchema=(r,n,o)=>ys(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});function wa(e,t){return new Hs({type:"nonoptional",innerType:e,...x.normalizeParams(t)})}var va=l("ZodCatch",(e,t)=>{po.init(e,t),k.init(e,t),e._zod.processJSONSchema=(r,n,o)=>xs(e,r,n,o),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function za(e,t){return new va({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}var $a=l("ZodPipe",(e,t)=>{fo.init(e,t),k.init(e,t),e._zod.processJSONSchema=(r,n,o)=>bs(e,r,n,o),e.in=t.in,e.out=t.out});function qs(e,t){return new $a({type:"pipe",in:e,out:t})}var ka=l("ZodReadonly",(e,t)=>{mo.init(e,t),k.init(e,t),e._zod.processJSONSchema=(r,n,o)=>ws(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});function Aa(e){return new ka({type:"readonly",innerType:e})}var Za=l("ZodLazy",(e,t)=>{ho.init(e,t),k.init(e,t),e._zod.processJSONSchema=(r,n,o)=>vs(e,r,n,o),e.unwrap=()=>e._zod.def.getter()});function Bt(e){return new Za({type:"lazy",getter:e})}var Sa=l("ZodCustom",(e,t)=>{yo.init(e,t),k.init(e,t),e._zod.processJSONSchema=(r,n,o)=>as(e,r,n,o)});function Ea(e,t={}){return Xo(Sa,e,t)}function Ra(e,t){return Yo(e,t)}function Pe(e){let t=Bt(()=>et([g(e),v(),oe(),oa(),N(t),se(g(),t)]));return t}var ei=e=>"field"in e?[e]:("all"in e?e.all:e.any).flatMap(ei),ti=e=>ei(e);var rt=(e,t)=>{if("field"in e)return t(e);let r="all"in e?e.all:e.any,n=!1;if("all"in e){for(let o of r){let s=rt(o,t);if(s===!1)return!1;n||=s===void 0}return n?void 0:!0}for(let o of r){let s=rt(o,t);if(s===!0)return!0;n||=s===void 0}return n?void 0:!1},ri=e=>JSON.stringify(e),Qt=e=>{if("field"in e)return{conditions:1,depth:0};let t="all"in e?e.all:e.any,r=0,n=1;for(let o of t){let s=Qt(o);r+=s.conditions,n=Math.max(n,s.depth+1)}return{conditions:r,depth:n}},ni=(e,t={})=>{let r=o=>{let s=N(o),i=t.maximumChildren===void 0?s:s.max(t.maximumChildren);return et([e,E({all:i}),E({any:i})])},n=Bt(()=>r(n));return t.maximumConditions===void 0&&t.maximumDepth===void 0?n:n.superRefine((o,s)=>{let{conditions:i,depth:c}=Qt(o);t.maximumConditions!==void 0&&i>t.maximumConditions&&s.addIssue({code:"custom",message:t.maximumConditionsMessage??"Query exceeds the condition limit"}),t.maximumDepth!==void 0&&c>t.maximumDepth&&s.addIssue({code:"custom",message:t.maximumDepthMessage??"Query exceeds the nesting limit"})})};var b={requestBytes:524288,filterCount:32,filterDepth:8,sortCount:8,outputFieldCount:256,fieldPathDepth:9,defaultResultCount:20,resultCount:1e3,resultBytes:16777216,candidateDocuments:1e3,databaseBytes:512e3,frontmatterBytes:65536,frontmatterDepth:8,frontmatterFields:256,frontmatterStringBytes:16384,jsonBytes:1048576,jsonDepth:8,jsonFields:256,jsonStringBytes:16384,indexedPropertiesBytes:65536,excerptBytes:2048,hydratedFileBytes:1048576,hydratedTotalBytes:2097152,hydratedFileCount:20,hydratedRangeBytes:262144,concurrentContentReads:8};var Pa=g().min(1).refine(e=>e.startsWith("/")===!1,{error:"Asset path must be relative"}).refine(e=>e.includes("\\")===!1&&e.split("/").every(t=>t.length>0&&t!==".."&&t!=="."),{error:"Asset path must be normalized and must not contain dot segments"}),oi=E({_id:g().min(1),_type:R("asset.file"),name:g().min(1),description:g().optional(),path:Pa,key:g(),folderId:g().min(1).optional(),extension:g().regex(/^[a-z0-9]*$/),mimeType:g().min(1),size:v().int().nonnegative(),createdAt:g().datetime().optional(),revision:g().min(1),contentRef:g().min(1),properties:se(g(),Pe()),excerpt:g().optional(),metadataError:E({code:g().min(1),message:g().min(1)}).optional()}),Oa=oi.partial().required({_id:!0}),Ia=H(["null","boolean","number","string","object","array"]),Ta=L({format:R("webstudio-builder-asset-field-catalog"),version:R(1),canonicalRevision:g().regex(/^sha256:[a-f0-9]{64}$/),documentCount:v().int().nonnegative(),fields:se(g().min(1),L({queryPath:N(g().min(1)).min(1).max(b.fieldPathDepth).optional(),types:N(Ia).min(1),occurrences:v().int().positive(),optional:R(!0).optional(),mixed:R(!0).optional()}))}).superRefine((e,t)=>{for(let[r,n]of Object.entries(e.fields)){let o=[...new Set(n.types)].sort();JSON.stringify(n.types)!==JSON.stringify(o)&&t.addIssue({code:"custom",path:["fields",r,"types"],message:"Observed field types must be unique and sorted"}),n.occurrences>e.documentCount&&t.addIssue({code:"custom",path:["fields",r,"occurrences"],message:"Field occurrences cannot exceed the document count"});let s=n.occurrences<e.documentCount;n.optional===!0!==s&&t.addIssue({code:"custom",path:["fields",r,"optional"],message:"Field optionality must match its occurrence count"});let i=o.length>1;n.mixed===!0!==i&&t.addIssue({code:"custom",path:["fields",r,"mixed"],message:"Mixed status must match the observed types"})}}),qt=g().regex(/^sha256:[a-f0-9]{64}$/),si=E({format:R("webstudio-content-database"),version:R(1),assetRevision:qt,documents:N(Oa),contents:se(g().min(1),g()).optional(),assetReferences:se(g().min(1),N(E({start:v().int().nonnegative(),end:v().int().positive(),assetId:g().min(1),suffix:g().min(1).optional()}).refine(({start:e,end:t})=>t>e,{message:"Markdown asset reference range must not be empty"}))).optional(),fieldCatalog:Ta,database:E({maxBytes:v().int().positive(),unboundedBytes:v().int().nonnegative(),sourceDocumentCount:v().int().nonnegative()}).optional(),integrity:E({algorithm:R("sha256"),checksum:qt})}).superRefine((e,t)=>{e.documents.length>b.candidateDocuments&&t.addIssue({code:"custom",path:["documents"],message:"Asset index exceeds the document limit"}),(e.fieldCatalog.canonicalRevision!==e.assetRevision||e.fieldCatalog.documentCount!==e.documents.length)&&t.addIssue({code:"custom",path:["fieldCatalog"],message:"Asset index field catalog does not match its documents"}),e.database!==void 0&&e.database.sourceDocumentCount<e.documents.length&&t.addIssue({code:"custom",path:["database","sourceDocumentCount"],message:"Source document count cannot be smaller than the database"});let r;for(let[o,s]of e.documents.entries())r!==void 0&&s._id<=r&&t.addIssue({code:"custom",path:["documents",o,"_id"],message:"Asset index documents must have unique sorted IDs"}),r=s._id;let n=new Set(e.documents.flatMap(({contentRef:o})=>o===void 0?[]:[o]));for(let o of Object.keys(e.contents??{}))n.has(o)===!1&&t.addIssue({code:"custom",path:["contents",o],message:"Embedded content must belong to an indexed document"});for(let o of Object.keys(e.assetReferences??{}))n.has(o)===!1&&t.addIssue({code:"custom",path:["assetReferences",o],message:"Asset references must belong to an indexed document"})}),Ca=tt("mode",[L({mode:R("none")}),L({mode:R("full"),maxBytes:v().int().positive().max(b.hydratedFileBytes).optional()}),L({mode:R("range"),offset:v().int().nonnegative(),length:v().int().positive().max(b.hydratedRangeBytes)}),L({mode:R("markdown-body"),maxBytes:v().int().positive().max(b.hydratedFileBytes).optional()})]),Vt={id:["string"],url:["string"],width:["number"],height:["number"],name:["string"],description:["string"],path:["string"],key:["string"],folderId:["string"],extension:["string"],mimeType:["string"],size:["number"],createdAt:["string"],revision:["string"],excerpt:["string"]},ii=Object.keys(Vt),ci=["url","width","height"],Wt=e=>ci.includes(e),ai=ii.filter(e=>Wt(e)===!1&&e!=="excerpt"),ui=ai.filter(e=>e!=="id"),li=e=>ai.includes(e),Na=H(ii),Oe=N(g().min(1)).min(1).max(b.fieldPathDepth).superRefine((e,t)=>{if(e[0]==="properties"){e.length<2&&t.addIssue({code:"custom",message:"A properties field path must select a property"});return}(e.length!==1||Na.safeParse(e[0]).success===!1)&&t.addIssue({code:"custom",message:"Asset query field path is unsupported"})}),Jt=oe().default(!0),Da=tt("mode",[E({mode:R("all"),includeMetadata:Jt}),E({mode:R("base"),includeMetadata:Jt}),E({mode:R("fields"),includeMetadata:Jt,fields:N(Oe).max(b.outputFieldCount).refine(e=>new Set(e.map(ri)).size===e.length,{error:"Selected output fields must be unique"})})]),Fa={mode:"fields",includeMetadata:!1,fields:ci.map(e=>[e])},pi=["eq","ne","contains","startsWith","endsWith","gt","gte","lt","lte"],Dp=[...pi,"in","exists","isEmpty"],ja=E({field:Oe,operator:H(pi),value:Pe()}),La=E({field:Oe,operator:R("in"),value:N(Pe()).max(b.resultCount)}),Ma=E({field:Oe,operator:H(["exists","isEmpty"]),value:oe()}),Ua=tt("operator",[ja,La,Ma]),Ba=ni(Ua,{maximumChildren:b.filterCount,maximumConditions:b.filterCount,maximumDepth:b.filterDepth,maximumConditionsMessage:"Asset query exceeds the filter limit",maximumDepthMessage:"Asset query exceeds the filter nesting limit"});var Qa=Ba,di=e=>{let t=new Set(["eq","ne","in","exists"]);return e.some(r=>r==="string"||r==="array")&&t.add("contains"),e.includes("string")&&(t.add("startsWith"),t.add("endsWith")),e.some(r=>r==="string"||r==="number")&&(t.add("gt"),t.add("gte"),t.add("lt"),t.add("lte")),e.some(r=>r==="string"||r==="array"||r==="object")&&t.add("isEmpty"),[...t]},Ja=E({field:Oe,direction:H(["asc","desc"])}),qa=({output:e,content:t})=>e.includeMetadata||e.mode==="all"||e.mode==="fields"&&e.fields.length>0||t.mode!=="none",Gt=E({where:Qa.default({all:[]}),sort:N(Ja).max(b.sortCount).default([]),limit:v().int().nonnegative().max(b.resultCount).default(b.defaultResultCount),offset:v().int().nonnegative().max(b.candidateDocuments).default(0),output:Da.default(Fa),content:Ca.default({mode:"none"})}).refine(qa,{error:"Select at least one asset query output"}),fi=E({query:Gt,indexRevision:g().min(1).max(255).optional()}),Va=L({_id:g().min(1),revision:g().min(1),contentRef:g().min(1),encoding:R("utf-8"),text:g(),range:L({offset:v().int().nonnegative(),length:v().int().nonnegative(),total:v().int().nonnegative()}).optional()}),Wa=Va.omit({_id:!0,revision:!0,contentRef:!0}),Ga=oi.omit({_id:!0,_type:!0,contentRef:!0}).partial().extend({id:g().min(1),url:g().min(1).optional(),width:v().positive().optional(),height:v().positive().optional(),content:Wa.optional()}).refine(e=>e.width===void 0==(e.height===void 0),{error:"Asset dimensions must include both width and height"}),Ka=E({format:R("webstudio-content-database"),version:R(1),revision:qt,usedBytes:v().int().nonnegative(),maxBytes:v().int().positive(),unboundedBytes:v().int().nonnegative(),includedDocumentCount:v().int().nonnegative(),omittedDocumentCount:v().int().nonnegative(),truncated:oe()}),Xa=Ka.pick({usedBytes:!0,maxBytes:!0,unboundedBytes:!0,includedDocumentCount:!0,omittedDocumentCount:!0,truncated:!0}).extend({scope:R("query-preview")}),Ya=E({items:N(Ga),totalCount:v().int().nonnegative(),hasMore:oe()}),Fp=E({data:Ya,__diagnostics__:Xa}),Ha=H(["INVALID_REQUEST","REQUEST_CANCELLED","UNAUTHORIZED","FORBIDDEN","STALE_INDEX","CONTENT_IDENTITY_REQUIRED","CONTENT_NOT_TEXT","CONTENT_DECODING_FAILED","CONTENT_LIMIT_EXCEEDED","INTERNAL_ERROR"]),eu=L({ok:R(!1),error:L({code:Ha,message:g().min(1),retryable:oe(),details:se(g(),Pe()).optional()}),meta:L({queryHash:g().min(1).optional(),indexRevision:g().min(1).optional(),assetRevision:g().min(1).optional()}).optional()}),mi=({code:e,message:t,retryable:r=!1,details:n})=>eu.parse({ok:!1,error:{code:e,message:t,retryable:r,details:n}});function ie(e,t=new Set){if(typeof e=="number"&&isNaN(e))throw new Error("NaN is not allowed");if(typeof e=="number"&&!isFinite(e))throw new Error("Infinity is not allowed");if(e===null||typeof e!="object")return JSON.stringify(e);if(typeof e.toJSON=="function"){if(t.has(e))throw new Error("Circular reference detected");t.add(e);let n=ie(e.toJSON(),t);return t.delete(e),n}if(t.has(e))throw new Error("Circular reference detected");t.add(e);let r;if(Array.isArray(e))r=`[${e.map(o=>ie(o===void 0||typeof o=="symbol"?null:o,t)).join(",")}]`;else{let n=[];for(let o of Object.keys(e).sort())e[o]===void 0||typeof e[o]=="symbol"||n.push(`${ie(o)}:${ie(e[o],t)}`);r=`{${n.join(",")}}`}return t.delete(e),r}var tu=new TextEncoder,ye=e=>tu.encode(e),ee=e=>ye(e).byteLength,ce=class extends Error{constructor(){super("Byte stream exceeds the configured limit"),this.name="ByteLimitExceededError"}},ru=(e,t)=>{let r=new Uint8Array(t),n=0;for(let o of e)r.set(o,n),n+=o.byteLength;return r},nu=e=>typeof e=="string"?{async*[Symbol.asyncIterator](){yield ye(e)}}:e instanceof Uint8Array?{async*[Symbol.asyncIterator](){yield e}}:e,ou=async(e,t)=>{let r=[],n=0;for await(let o of nu(e)){let s=t-n;if(s<=0)break;let i=o.subarray(0,s);if(r.push(i),n+=i.byteLength,n===t)break}return ru(r,n)},nt=async(e,t)=>{let r=await ou(e,t+1);if(r.byteLength>t)throw new ce;return r},ae=e=>new TextDecoder("utf-8",{fatal:!0}).decode(e),hi=e=>e.charCodeAt(0)===65279?e.slice(1):e;var yi=e=>{for(let t=0;t<e.length;t+=1){let r=e.charCodeAt(t);if(r>=55296&&r<=56319){let n=e.charCodeAt(t+1);if(t+1>=e.length||n<56320||n>57343)throw new Error("JSON strings cannot contain lone Unicode surrogates");t+=1;continue}if(r>=56320&&r<=57343)throw new Error("JSON strings cannot contain lone Unicode surrogates")}},Kt=(e,t)=>{if(e===null||typeof e=="boolean")return e;if(typeof e=="string")return yi(e),e;if(typeof e=="number"){if(Number.isFinite(e)===!1)throw new Error("JSON cannot contain non-finite numbers");return e}if(Array.isArray(e)){if(Object.getOwnPropertySymbols(e).length>0)throw new Error("JSON arrays cannot contain symbol properties");if(t.has(e))throw new Error("JSON cannot contain circular references");t.add(e);try{let r=[];for(let n=0;n<e.length;n+=1){if(Object.hasOwn(e,n)===!1)throw new Error("JSON arrays cannot be sparse");let o=e[n];if(o===void 0)throw new Error("JSON arrays cannot contain undefined values");r.push(Kt(o,t))}if(Object.keys(e).length!==e.length)throw new Error("JSON arrays cannot contain named properties");return r}finally{t.delete(e)}}if(typeof e=="object"){let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)throw new Error("JSON can contain only plain objects");if(Object.getOwnPropertySymbols(e).length>0)throw new Error("JSON objects cannot contain symbol properties");if(t.has(e))throw new Error("JSON cannot contain circular references");t.add(e);let n={};try{for(let[o,s]of Object.entries(e))yi(o),s!==void 0&&Object.defineProperty(n,o,{value:Kt(s,t),enumerable:!0,configurable:!0,writable:!0})}finally{t.delete(e)}return n}throw new Error("Value cannot be represented as JSON")},su=e=>Kt(e,new Set),te=e=>{let t=ie(su(e));if(t===void 0)throw new Error("Value cannot be represented as canonical JSON");return t},Ie=(e,t)=>e<t?-1:e>t?1:0,gi=async e=>{let t=typeof e=="string"?ye(e):e,r=await globalThis.crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(r),n=>n.toString(16).padStart(2,"0")).join("")};var _i=e=>te(si.parse(e)),xi=e=>[...new Set(Object.values(e.assetReferences??{}).flat().map(({assetId:t})=>t))].sort();var ue=class extends Error{code;constructor(t,r){super(r),this.name="MarkdownMetadataError",this.code=t}};var Te=new Uint8Array([239,187,191]),Kp=Te.byteLength+10,iu=(e,t,r=0)=>e.byteLength-r<t.byteLength?!1:t.every((n,o)=>e[r+o]===n),bi=(e,t)=>{let r=0;if(iu(e,Te))r=Te.byteLength;else if(e.byteLength<Te.byteLength&&Te.slice(0,e.byteLength).every((s,i)=>s===e[i]))return t?null:void 0;if(e.byteLength<r+4)return t?null:void 0;if(e[r]!==45||e[r+1]!==45||e[r+2]!==45)return null;let n=r+3;if(e[n]===10)n+=1;else if(e[n]===13){if(e.byteLength===n+1)return t?null:void 0;if(e[n+1]!==10)return null;n+=2}else return null;let o=n;for(let s=n;s<=e.byteLength;s+=1){let i=s===e.byteLength;if(i===!1&&e[s]!==10)continue;if(i&&t===!1)return;let c=s;if(c>o&&e[c-1]===13&&(c-=1),c-o===3&&(e[o]===45&&e[o+1]===45&&e[o+2]===45||e[o]===46&&e[o+1]===46&&e[o+2]===46))return{yamlStart:n,yamlEnd:o,blockEnd:i?s:s+1};o=s+1}};var wi=async(e,t=b.hydratedFileBytes)=>{if(Number.isInteger(t)===!1||t<=0||t>b.hydratedFileBytes)throw new ue("MARKDOWN_BODY_BYTES_EXCEEDED","Markdown body byte limit is outside the supported range");let r;try{r=await nt(e,t)}catch(c){throw c instanceof ce?new ue("MARKDOWN_BODY_BYTES_EXCEEDED","Markdown content exceeds the byte limit"):c}let n;try{n=ae(r)}catch{throw new ue("MARKDOWN_BODY_DECODING_FAILED","Markdown content is not valid UTF-8")}let s=bi(r,!0)?.blockEnd??0,i;try{i=s===0?hi(n):ae(r.subarray(s))}catch{throw new ue("MARKDOWN_BODY_DECODING_FAILED","Markdown content is not valid UTF-8")}return{body:i,bodyBytes:ee(i),sourceBytes:r.byteLength}};var vi=async(e,t,r)=>{if(Number.isSafeInteger(t)===!1||t<=0)throw new Error("Concurrency must be a positive safe integer");let n=0,o=new Array(e.length),s=async()=>{for(;n<e.length;){let u=n;n+=1,o[u]=await r(e[u])}},i=Array.from({length:Math.min(t,e.length)},s),a=(await Promise.allSettled(i)).find(u=>u.status==="rejected");if(a!==void 0)throw a.reason;return o};var cu=(e,t)=>{if(t===void 0||t.length===0)return e;let r=new URL("https://content.webstudio.invalid/__assets__/"),n=new URL(e,r),o=new URL(t,r);for(let[c,a]of o.searchParams)n.searchParams.append(c,a);if(o.hash!==""&&(n.hash=o.hash),URL.canParse(e))return n.href;if(e.startsWith("//"))return`//${n.host}${n.pathname}${n.search}${n.hash}`;if(e.startsWith("/"))return`${n.pathname}${n.search}${n.hash}`;let s=r.pathname;return`${n.pathname.startsWith(s)?n.pathname.slice(s.length):n.pathname}${n.search}${n.hash}`},zi=({markdown:e,references:t,assetUrls:r})=>{let n=e.length,o=e;for(let s of[...t].sort((i,c)=>c.start-i.start)){if(s.start<0||s.end<=s.start||s.end>e.length||s.end>n)throw new Error("Markdown asset reference range is invalid");n=s.start;let i=r[s.assetId];if(i===void 0)continue;let c=cu(i,s.suffix);o=`${o.slice(0,s.start)}${c}${o.slice(s.end)}`}return o};var C=class extends Error{code;details;constructor({code:t,message:r,details:n}){super(r),this.name="AssetResourceHydrationError",this.code=t,this.details=n}},au=e=>{if(e===null)return[];let t=Array.isArray(e)?e:[e],r=new Map;for(let n of t){if(typeof n!="object"||n===null||!("_id"in n)||typeof n._id!="string"||!("revision"in n)||typeof n.revision!="string"||!("contentRef"in n)||typeof n.contentRef!="string")throw new C({code:"CONTENT_IDENTITY_REQUIRED",message:"Hydrated query results must retain _id, revision, and contentRef"});let o=r.get(n._id);if(o!==void 0&&(o.revision!==n.revision||o.contentRef!==n.contentRef))throw new C({code:"CONTENT_IDENTITY_REQUIRED",message:"A selected asset ID has conflicting content identity",details:{assetId:n._id}});r.set(n._id,{_id:n._id,revision:n.revision,contentRef:n.contentRef})}return Array.from(r.values())},uu=e=>typeof e.mimeType=="string"&&(e.mimeType.startsWith("text/")||["application/json","application/javascript","application/xml","image/svg+xml"].includes(e.mimeType)),lu=async({read:e,contentRef:t,range:r,maximumBytes:n})=>{if(n===0)return new Uint8Array;let o=await e(t,r);try{return await nt(o.data,n)}catch(s){throw s instanceof ce?new C({code:"CONTENT_LIMIT_EXCEEDED",message:"Asset storage returned more content than requested"}):s}},pu=e=>{try{return ae(e)}catch{throw new C({code:"CONTENT_DECODING_FAILED",message:"Selected asset content is not valid UTF-8"})}},du=(e,t)=>{if(t.mode==="range")return Math.max(0,Math.min(t.length,e.size-t.offset));let r=t.maxBytes??b.hydratedFileBytes;if(e.size>r)throw new C({code:"CONTENT_LIMIT_EXCEEDED",message:"Selected asset exceeds the per-file content limit",details:{assetId:e._id,assetBytes:e.size,fileByteLimit:r}});return e.size},$i=async({result:e,documents:t,options:r,read:n,assetReferences:o,assetUrls:s})=>{if(r.mode==="none")return{content:{},hydratedFileCount:0,hydratedBytes:0};let i=au(e);if(i.length>b.hydratedFileCount)throw new C({code:"CONTENT_LIMIT_EXCEEDED",message:"Too many selected assets requested content hydration",details:{fileCount:i.length,fileCountLimit:b.hydratedFileCount}});let c=new Map(t.map(p=>[p._id,p])),a=i.map(p=>{let m=c.get(p._id);if(m===void 0||m.revision!==p.revision||m.contentRef!==p.contentRef||typeof m.size!="number"||typeof m.mimeType!="string")throw new C({code:"CONTENT_IDENTITY_REQUIRED",message:"Selected asset content identity is stale or unavailable",details:{assetId:p._id}});let d={...m,size:m.size,mimeType:m.mimeType};if(uu(d)===!1)throw new C({code:"CONTENT_NOT_TEXT",message:"Selected binary asset cannot be embedded as text",details:{assetId:p._id,mimeType:d.mimeType}});return{identity:p,document:d,readLength:du(d,r)}}),u=a.reduce((p,m)=>p+m.readLength,0);if(u>b.hydratedTotalBytes)throw new C({code:"CONTENT_LIMIT_EXCEEDED",message:"Selected assets exceed the total hydrated-content limit",details:{totalReadBytes:u,totalByteLimit:b.hydratedTotalBytes}});let f=await vi(a,b.concurrentContentReads,async p=>{let m=r.mode==="range"?{offset:r.offset,length:p.readLength}:p.readLength===0?void 0:{offset:0,length:p.readLength},d=await lu({read:n,contentRef:p.identity.contentRef,range:m,maximumBytes:p.readLength});if(d.byteLength!==p.readLength)throw new C({code:"CONTENT_IDENTITY_REQUIRED",message:"Selected asset bytes do not match canonical metadata",details:{assetId:p.identity._id}});let y;if(r.mode==="markdown-body")try{y=(await wi(d,p.readLength||1)).body;let w=o?.[p.identity.contentRef];w!==void 0&&s!==void 0&&(y=zi({markdown:y,references:w,assetUrls:s}))}catch{throw new C({code:"CONTENT_DECODING_FAILED",message:"Selected Markdown body could not be decoded",details:{assetId:p.identity._id}})}else y=pu(d);let P=ee(y);return{id:p.identity._id,returnedBytes:P,content:{...p.identity,encoding:"utf-8",text:y,...r.mode==="range"?{range:{offset:r.offset,length:d.byteLength,total:p.document.size}}:{}}}});return{content:Object.fromEntries(f.map(({id:p,content:m})=>[p,m])),hydratedFileCount:a.length,hydratedBytes:f.reduce((p,{returnedBytes:m})=>p+m,0)}};var dd=g().datetime({offset:!0}).transform(e=>new Date(e).toISOString());var fu=/^[A-Za-z_][A-Za-z0-9_]*$/,ki=(e,t)=>fu.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`;var Ai=({document:e,includes:t})=>{let r={};for(let n of ui){let o=e[n];o!==void 0&&t(n)&&(r[n]=o)}return r},Zi=({source:e,target:t,path:r})=>{let[n,...o]=r;if(n===void 0||Object.hasOwn(e,n)===!1)return;let s=e[n];if(o.length===0){Object.defineProperty(t,n,{value:s,enumerable:!0,configurable:!0,writable:!0});return}if(typeof s!="object"||s===null||Array.isArray(s))return;let i={};if(Zi({source:s,target:i,path:o}),Object.keys(i).length===0)return;let c=t[n];Object.defineProperty(t,n,{value:{...typeof c=="object"&&c!==null&&Array.isArray(c)===!1?c:{},...i},enumerable:!0,configurable:!0,writable:!0})},Si=({properties:e,fields:t})=>{let r={};for(let n of t)n[0]==="properties"&&Zi({source:e,target:r,path:n.slice(1)});return r};var W=class extends Error{constructor(t,r){super(t,r),this.name="AssetQueryExecutionError"}},_e=class extends Error{constructor(){super("The requested asset index revision is stale"),this.name="AssetIndexRevisionError"}},Ei=e=>{if(e[0]!=="properties")return e[0];let t="properties";for(let r of e.slice(1))t=ki(t,r);return t},Ri=({filter:e,fieldTypes:t})=>di(t).includes(e.operator),Pi=(e,t)=>Object.hasOwn(e.fields,t)?e.fields[t]:void 0,mu=({query:e,catalog:t})=>{let r=Gt.parse(e),n=new Map,o=[];for(let s of ti(r.where)){let i=Ei(s.field);if(n.set(i,s.field),s.field[0]==="properties"){let c=Pi(t,i);c===void 0?o.push(`Asset field ${i} is not currently observed`):Ri({filter:s,fieldTypes:c.types})===!1&&o.push(`Operator ${s.operator} is not compatible with the currently observed types of ${i}`)}else if(Ri({filter:s,fieldTypes:Vt[s.field[0]]})===!1)throw new W(`Operator ${s.operator} is incompatible with ${i}`)}for(let s of r.sort){let i=Ei(s.field);if(n.set(i,s.field),s.field[0]==="properties"){let c=Pi(t,i);c===void 0?o.push(`Asset field ${i} is not currently observed`):c.types.some(a=>a==="object"||a==="array")&&o.push(`Asset field ${i} currently includes structured values that use deterministic JSON sort order`)}}return{query:r,referencedFieldPaths:[...n.values()],warnings:[...new Set(o)]}},Xt=(e,t,r)=>{let n=t[0]==="id"?e._id:Wt(t[0])?r?.[t[0]]:e[t[0]];for(let o of t.slice(1)){if(typeof n!="object"||n===null||Object.hasOwn(n,o)===!1)return;n=n[o]}return n},ot=(e,t)=>e===void 0||t===void 0?e===t:te(e)===te(t),hu=e=>typeof e=="string"||Array.isArray(e)?e.length===0:typeof e=="object"&&e!==null&&Object.keys(e).length===0,yu=(e,t)=>{if(typeof e=="number"&&typeof t=="number")return e-t;if(typeof e=="string"&&typeof t=="string")return Ie(e,t)},gu=(e,t,r)=>{let n=Xt(e,t.field,r);if(t.operator==="exists")return n!=null===t.value;if(t.operator==="isEmpty")return hu(n)===t.value;if(t.operator==="eq")return ot(n,t.value);if(t.operator==="ne")return ot(n,t.value)===!1;if(t.operator==="in")return t.value.some(s=>ot(n,s));if(t.operator==="contains")return typeof n=="string"&&typeof t.value=="string"?n.includes(t.value):Array.isArray(n)&&n.some(s=>ot(s,t.value));if(t.operator==="startsWith")return typeof n=="string"&&typeof t.value=="string"&&n.startsWith(t.value);if(t.operator==="endsWith")return typeof n=="string"&&typeof t.value=="string"&&n.endsWith(t.value);let o=yu(n,t.value);return o===void 0?!1:t.operator==="gt"?o>0:t.operator==="gte"?o>=0:t.operator==="lt"?o<0:o<=0},_u=(e,t,r)=>rt(t,n=>gu(e,n,r))===!0,xu=(e,t)=>{let r=e==null,n=t==null;return r||n?r===n?0:r?1:-1:typeof e=="number"&&typeof t=="number"?e-t:(typeof e=="string"||typeof e=="boolean")&&(typeof t=="string"||typeof t=="boolean")?Ie(String(e),String(t)):Ie(te(e),te(t))},bu=({left:e,right:t,sort:r,runtimeAssets:n})=>{for(let o of r){let s=xu(Xt(e,o.field,n?.[e._id]),Xt(t,o.field,n?.[t._id]));if(s!==0)return o.direction==="asc"?s:-s}return Ie(e._id,t._id)};var wu=(e,t)=>{if(e.properties===void 0)return;if(t.mode==="all")return Object.keys(e.properties).length===0?void 0:e.properties;if(t.mode!=="fields"||t.fields.some(n=>n[0]==="properties")===!1)return;let r=Si({properties:e.properties,fields:t.fields});return Object.keys(r).length===0?void 0:r},ge=(e,t)=>e.includeMetadata&&li(t)||e.mode==="fields"&&e.fields.some(r=>r.length===1&&r[0]===t),vu=e=>e.mode==="all"||e.mode==="fields"&&e.fields.some(t=>t.length===1&&t[0]==="excerpt"),zu=(e,t,r)=>{if(ge(t,"url")&&r===void 0)throw new Error(`Asset URL is unavailable for ${e._id}`);let n=wu(e,t),o=r?.width!==void 0&&r.height!==void 0;return{...r!==void 0&&ge(t,"url")?{url:r.url}:{},...o&&ge(t,"width")?{width:r.width}:{},...o&&ge(t,"height")?{height:r.height}:{},...Ai({document:e,includes:s=>ge(t,s)}),...n===void 0?{}:{properties:n},...e.excerpt===void 0||vu(t)===!1?{}:{excerpt:e.excerpt},...e.metadataError===void 0||t.includeMetadata===!1?{}:{metadataError:e.metadataError}}},$u=e=>{if(ee(te(e))>b.resultBytes)throw new W("Asset query result exceeds the byte limit")},Oi=async({query:e,catalog:t,documents:r,read:n,runtimeAssets:o,assetReferences:s})=>{let{query:i}=mu({query:e,catalog:t});if(r.length>b.candidateDocuments)throw new W("Asset query document limit was exceeded");let c=r.flatMap(d=>{let y=o?.[d._id];if(_u(d,i.where,y)===!1)return[];let P=zu(d,i.output,y);return i.content.mode==="none"&&Object.keys(P).length===0&&ge(i.output,"id")===!1?[]:[{document:d,item:{id:d._id,...P}}]}),u=[...c].sort((d,y)=>bu({left:d.document,right:y.document,sort:i.sort,runtimeAssets:o})).slice(i.offset,i.offset+i.limit),f=u.map(({document:d})=>d),p=u.map(({item:d})=>d);if(i.content.mode!=="none"){let d=i.content;if(n===void 0)throw new W("Asset content reader is unavailable");let y=await $i({result:f,documents:f,options:d,read:n,assetReferences:s,assetUrls:s===void 0?void 0:Object.fromEntries(Object.entries(o??{}).map(([P,w])=>[P,w.url]))});p=f.map((P,w)=>{let F=y.content[P._id];if(F===void 0)throw new W("Selected asset content could not be read");return{...p[w],content:{encoding:F.encoding,text:F.text,...F.range===void 0?{}:{range:F.range}}}})}let m={items:p,totalCount:c.length,hasMore:i.offset+u.length<c.length};return $u(m),m};var Yt=({artifact:e,readContent:t})=>{let r=e.documents.length,o=(e.database?.sourceDocumentCount??r)-r,s=ee(_i(e)),i={format:e.format,version:e.version,revision:e.integrity.checksum,usedBytes:s,maxBytes:e.database?.maxBytes??Number.MAX_SAFE_INTEGER,unboundedBytes:e.database?.unboundedBytes??s,includedDocumentCount:r,omittedDocumentCount:o,truncated:o>0};return{query:async(c,a,u)=>{if(c.indexRevision!==void 0&&c.indexRevision!==e.integrity.checksum)throw new _e;let f=async(m,d)=>{let y=e.contents?.[m];if(y===void 0){let F=a??t;if(F===void 0)throw new Error("Content is not embedded in this database");return await F(m,d)}let P=ye(y),w=d===void 0?P:P.slice(d.offset,d.offset+d.length);return{data:async function*(){yield w}(),contentLength:w.byteLength}};return await Oi({query:c.query,catalog:e.fieldCatalog,documents:e.documents,read:f,runtimeAssets:u,assetReferences:e.assetReferences})},getFieldCatalog:()=>e.fieldCatalog,getStats:()=>i}};var st=class extends Error{constructor(t,r){super(t,r),this.name="AssetQueryRequestError"}},Ce=class extends Error{},ku=async(e,t)=>{if(Number.isSafeInteger(t)===!1||t<0)throw new TypeError("Request byte limit must be a non-negative integer");let r=Number(e.headers.get("content-length"));if(Number.isFinite(r)&&r>t)throw new Ce("Request exceeds the byte limit");let n=e.body?.getReader(),o=[],s=0;if(n!==void 0)for(;;){let{done:a,value:u}=await n.read();if(a)break;if(s+=u.byteLength,s>t){try{await n.cancel()}catch{}throw new Ce("Request exceeds the byte limit")}o.push(u)}let i=new Uint8Array(s),c=0;for(let a of o)i.set(a,c),c+=a.byteLength;return i},Ii=async e=>{let t;try{t=await ku(e,b.requestBytes)}catch(r){throw r instanceof Ce?new st("Asset query request exceeds the byte limit",{cause:r}):r}try{return fi.parse(JSON.parse(ae(t)))}catch(r){throw new st("Asset query request is invalid",{cause:r})}};var Ti=e=>{if(e instanceof _e)return{code:"STALE_INDEX",message:e.message,retryable:!1,status:409};if(e instanceof W)return{code:"INVALID_REQUEST",message:e.message,retryable:!1,status:400};if(e instanceof C)return{code:e.code,message:e.message,retryable:!1,details:e.details,status:400}};var Au="/$resources/assets",Ci=(e,t=200)=>new Response(JSON.stringify(e),{status:t,headers:{"content-type":"application/json; charset=utf-8"}}),Ne=({code:e,message:t,status:r,retryable:n=!1,details:o})=>Ci(mi({code:e,message:t,retryable:n,details:o}),r),Zu=(e,t,r)=>typeof e=="string"||e instanceof URL?new Request(new URL(e,t),r):new Request(e,r),Su=async({deploymentId:e,artifact:t,request:r})=>{let n=await r.clone().text(),o=r.headers.get("cache-control"),s=await gi(JSON.stringify([e,t.integrity.checksum,n,o])),i=new URL(r.url);return i.searchParams.set("ws-asset-resource",s),new Request(i,{method:"GET"})},Ud=({deploymentId:e,artifact:t,runtimeAssets:r,cache:n,baseUrl:o})=>(Ni({artifact:t,runtimeAssets:r}),Di({deploymentId:e,artifact:t,runtimeAssets:r,cache:n,baseUrl:o,database:Yt({artifact:t})})),Ni=({artifact:e,runtimeAssets:t})=>{let r=xi(e).find(n=>t[n]===void 0);if(r!==void 0)throw new Error(`Published referenced asset URL is unavailable for ${r}`)},Di=({deploymentId:e,artifact:t,runtimeAssets:r,cache:n,baseUrl:o,database:s})=>{let i=new URL(o).origin;return async(c,a)=>{let u=Zu(c,o,a),f=new URL(u.url);if(f.origin!==i||f.pathname!==Au||u.method.toUpperCase()!=="POST")return;let p;try{p=await Ii(u.clone())}catch{return Ne({code:"INVALID_REQUEST",message:"Asset resource request is invalid",status:400})}let m=n===void 0||u.headers.has("cache-control")===!1?void 0:await Su({deploymentId:e,artifact:t,request:u});if(m!==void 0&&n!==void 0){let d=await n.match(m).catch(()=>{});if(d!==void 0)return new Response(d.body,d)}try{if(u.signal.aborted)return Ne({code:"REQUEST_CANCELLED",message:"Published asset query was cancelled",status:499});let d=Ci(await s.query(p,void 0,r));return m!==void 0&&n!==void 0&&u.signal.aborted===!1&&(d.headers.set("cache-control",u.headers.get("cache-control")),await n.put(m,d.clone()).catch(()=>{})),d}catch(d){if(u.signal.aborted)return Ne({code:"REQUEST_CANCELLED",message:"Published asset query was cancelled",status:499});let y=Ti(d);return Ne(y!==void 0?y:{code:"INTERNAL_ERROR",message:"Published asset query failed",status:500,retryable:!0})}}},Bd=({deploymentId:e,artifact:t,runtimeAssets:r})=>{let n=globalThis.caches,o,s=()=>(o??=n.open(`webstudio-assets-${e}`),o),i=n===void 0?void 0:{match:async a=>(await s()).match(a),put:async(a,u)=>(await s()).put(a,u)};Ni({artifact:t,runtimeAssets:r});let c=Yt({artifact:t});return async({request:a,fallback:u})=>{let f=new URL(a.url).origin,p=Di({deploymentId:e,artifact:t,runtimeAssets:r,cache:i,baseUrl:f,database:c});return async(m,d)=>await p(m,d)??u(m,d)}};export{Bd as createGeneratedAssetResourceRuntime,Ud as createPublishedAssetResourceFetch};
+Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let i of e.seen.entries()){let c=i[1];if(t===i[0]){s(i);continue}if(e.external){let u=e.external.registry.get(i[0])?.id;if(t!==i[0]&&u){s(i);continue}}if(e.metadataRegistry.get(i[0])?.id){s(i);continue}if(c.cycle){s(i);continue}if(c.count>1&&e.reused==="ref"){s(i);continue}}}function Bt(e,t){let r=e.seen.get(t);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");let n=c=>{let a=e.seen.get(c);if(a.ref===null)return;let u=a.def??a.schema,f={...u},p=a.ref;if(a.ref=null,p){n(p);let d=e.seen.get(p),y=d.schema;if(y.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(u.allOf=u.allOf??[],u.allOf.push(y)):Object.assign(u,y),Object.assign(u,f),c._zod.parent===p)for(let w in u)w==="$ref"||w==="allOf"||w in f||delete u[w];if(y.$ref&&d.def)for(let w in u)w==="$ref"||w==="allOf"||w in d.def&&JSON.stringify(u[w])===JSON.stringify(d.def[w])&&delete u[w]}let m=c._zod.parent;if(m&&m!==p){n(m);let d=e.seen.get(m);if(d?.schema.$ref&&(u.$ref=d.schema.$ref,d.def))for(let y in u)y==="$ref"||y==="allOf"||y in d.def&&JSON.stringify(u[y])===JSON.stringify(d.def[y])&&delete u[y]}e.override({zodSchema:c,jsonSchema:u,path:a.path??[]})};for(let c of[...e.seen.entries()].reverse())n(c[0]);let o={};if(e.target==="draft-2020-12"?o.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?o.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?o.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){let c=e.external.registry.get(t)?.id;if(!c)throw new Error("Schema is missing an `id` property");o.$id=e.external.uri(c)}Object.assign(o,r.def??r.schema);let s=e.metadataRegistry.get(t)?.id;s!==void 0&&o.id===s&&delete o.id;let i=e.external?.defs??{};for(let c of e.seen.entries()){let a=c[1];a.def&&a.defId&&(a.def.id===a.defId&&delete a.def.id,i[a.defId]=a.def)}e.external||Object.keys(i).length>0&&(e.target==="draft-2020-12"?o.$defs=i:o.definitions=i);try{let c=JSON.parse(JSON.stringify(o));return Object.defineProperty(c,"~standard",{value:{...t["~standard"],jsonSchema:{input:Pe(t,"input",e.processors),output:Pe(t,"output",e.processors)}},enumerable:!1,writable:!1}),c}catch{throw new Error("Error converting schema to JSON.")}}function T(e,t){let r=t??{seen:new Set};if(r.seen.has(e))return!1;r.seen.add(e);let n=e._zod.def;if(n.type==="transform")return!0;if(n.type==="array")return T(n.element,r);if(n.type==="set")return T(n.valueType,r);if(n.type==="lazy")return T(n.getter(),r);if(n.type==="promise"||n.type==="optional"||n.type==="nonoptional"||n.type==="nullable"||n.type==="readonly"||n.type==="default"||n.type==="prefault")return T(n.innerType,r);if(n.type==="intersection")return T(n.left,r)||T(n.right,r);if(n.type==="record"||n.type==="map")return T(n.keyType,r)||T(n.valueType,r);if(n.type==="pipe")return e._zod.traits.has("$ZodCodec")?!0:T(n.in,r)||T(n.out,r);if(n.type==="object"){for(let o in n.shape)if(T(n.shape[o],r))return!0;return!1}if(n.type==="union"){for(let o of n.options)if(T(o,r))return!0;return!1}if(n.type==="tuple"){for(let o of n.items)if(T(o,r))return!0;return!!(n.rest&&T(n.rest,r))}return!1}var ns=(e,t={})=>r=>{let n=Qt({...r,processors:t});return E(e,n),Ut(n,e),Bt(n,e)},Pe=(e,t,r={})=>n=>{let{libraryOptions:o,target:s}=n??{},i=Qt({...o??{},target:s,io:t,processors:r});return E(e,i),Ut(i,e),Bt(i,e)};var Zc={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},os=(e,t,r,n)=>{let o=r;o.type="string";let{minimum:s,maximum:i,format:c,patterns:a,contentEncoding:u}=e._zod.bag;if(typeof s=="number"&&(o.minLength=s),typeof i=="number"&&(o.maxLength=i),c&&(o.format=Zc[c]??c,o.format===""&&delete o.format,c==="time"&&delete o.format),u&&(o.contentEncoding=u),a&&a.size>0){let f=[...a];f.length===1?o.pattern=f[0].source:f.length>1&&(o.allOf=[...f.map(p=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:p.source}))])}},ss=(e,t,r,n)=>{let o=r,{minimum:s,maximum:i,format:c,multipleOf:a,exclusiveMaximum:u,exclusiveMinimum:f}=e._zod.bag;typeof c=="string"&&c.includes("int")?o.type="integer":o.type="number";let p=typeof f=="number"&&f>=(s??Number.NEGATIVE_INFINITY),m=typeof u=="number"&&u<=(i??Number.POSITIVE_INFINITY),d=t.target==="draft-04"||t.target==="openapi-3.0";p?d?(o.minimum=f,o.exclusiveMinimum=!0):o.exclusiveMinimum=f:typeof s=="number"&&(o.minimum=s),m?d?(o.maximum=u,o.exclusiveMaximum=!0):o.exclusiveMaximum=u:typeof i=="number"&&(o.maximum=i),typeof a=="number"&&(o.multipleOf=a)},is=(e,t,r,n)=>{r.type="boolean"};var cs=(e,t,r,n)=>{t.target==="openapi-3.0"?(r.type="string",r.nullable=!0,r.enum=[null]):r.type="null"};var as=(e,t,r,n)=>{r.not={}};var us=(e,t,r,n)=>{};var ls=(e,t,r,n)=>{let o=e._zod.def,s=ve(o.entries);s.every(i=>typeof i=="number")&&(r.type="number"),s.every(i=>typeof i=="string")&&(r.type="string"),r.enum=s},ps=(e,t,r,n)=>{let o=e._zod.def,s=[];for(let i of o.values)if(i===void 0){if(t.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof i=="bigint"){if(t.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");s.push(Number(i))}else s.push(i);if(s.length!==0)if(s.length===1){let i=s[0];r.type=i===null?"null":typeof i,t.target==="draft-04"||t.target==="openapi-3.0"?r.enum=[i]:r.const=i}else s.every(i=>typeof i=="number")&&(r.type="number"),s.every(i=>typeof i=="string")&&(r.type="string"),s.every(i=>typeof i=="boolean")&&(r.type="boolean"),s.every(i=>i===null)&&(r.type="null"),r.enum=s};var ds=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")};var fs=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")};var ms=(e,t,r,n)=>{let o=r,s=e._zod.def,{minimum:i,maximum:c}=e._zod.bag;typeof i=="number"&&(o.minItems=i),typeof c=="number"&&(o.maxItems=c),o.type="array",o.items=E(s.element,t,{...n,path:[...n.path,"items"]})},hs=(e,t,r,n)=>{let o=r,s=e._zod.def;o.type="object",o.properties={};let i=s.shape;for(let u in i)o.properties[u]=E(i[u],t,{...n,path:[...n.path,"properties",u]});let c=new Set(Object.keys(i)),a=new Set([...c].filter(u=>{let f=s.shape[u]._zod;return t.io==="input"?f.optin===void 0:f.optout===void 0}));a.size>0&&(o.required=Array.from(a)),s.catchall?._zod.def.type==="never"?o.additionalProperties=!1:s.catchall?s.catchall&&(o.additionalProperties=E(s.catchall,t,{...n,path:[...n.path,"additionalProperties"]})):t.io==="output"&&(o.additionalProperties=!1)},ys=(e,t,r,n)=>{let o=e._zod.def,s=o.inclusive===!1,i=o.options.map((c,a)=>E(c,t,{...n,path:[...n.path,s?"oneOf":"anyOf",a]}));s?r.oneOf=i:r.anyOf=i},gs=(e,t,r,n)=>{let o=e._zod.def,s=E(o.left,t,{...n,path:[...n.path,"allOf",0]}),i=E(o.right,t,{...n,path:[...n.path,"allOf",1]}),c=u=>"allOf"in u&&Object.keys(u).length===1,a=[...c(s)?s.allOf:[s],...c(i)?i.allOf:[i]];r.allOf=a};var _s=(e,t,r,n)=>{let o=r,s=e._zod.def;o.type="object";let i=s.keyType,a=i._zod.bag?.patterns;if(s.mode==="loose"&&a&&a.size>0){let f=E(s.valueType,t,{...n,path:[...n.path,"patternProperties","*"]});o.patternProperties={};for(let p of a)o.patternProperties[p.source]=f}else(t.target==="draft-07"||t.target==="draft-2020-12")&&(o.propertyNames=E(s.keyType,t,{...n,path:[...n.path,"propertyNames"]})),o.additionalProperties=E(s.valueType,t,{...n,path:[...n.path,"additionalProperties"]});let u=i._zod.values;if(u){let f=[...u].filter(p=>typeof p=="string"||typeof p=="number");f.length>0&&(o.required=f)}},xs=(e,t,r,n)=>{let o=e._zod.def,s=E(o.innerType,t,n),i=t.seen.get(e);t.target==="openapi-3.0"?(i.ref=o.innerType,r.nullable=!0):r.anyOf=[s,{type:"null"}]},bs=(e,t,r,n)=>{let o=e._zod.def;E(o.innerType,t,n);let s=t.seen.get(e);s.ref=o.innerType},ws=(e,t,r,n)=>{let o=e._zod.def;E(o.innerType,t,n);let s=t.seen.get(e);s.ref=o.innerType,r.default=JSON.parse(JSON.stringify(o.defaultValue))},vs=(e,t,r,n)=>{let o=e._zod.def;E(o.innerType,t,n);let s=t.seen.get(e);s.ref=o.innerType,t.io==="input"&&(r._prefault=JSON.parse(JSON.stringify(o.defaultValue)))},zs=(e,t,r,n)=>{let o=e._zod.def;E(o.innerType,t,n);let s=t.seen.get(e);s.ref=o.innerType;let i;try{i=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}r.default=i},$s=(e,t,r,n)=>{let o=e._zod.def,s=o.in._zod.traits.has("$ZodTransform"),i=t.io==="input"?s?o.out:o.in:o.out;E(i,t,n);let c=t.seen.get(e);c.ref=i},ks=(e,t,r,n)=>{let o=e._zod.def;E(o.innerType,t,n);let s=t.seen.get(e);s.ref=o.innerType,r.readOnly=!0};var Jt=(e,t,r,n)=>{let o=e._zod.def;E(o.innerType,t,n);let s=t.seen.get(e);s.ref=o.innerType},As=(e,t,r,n)=>{let o=e._zod.innerType;E(o,t,n);let s=t.seen.get(e);s.ref=o};var Ic=l("ZodISODateTime",(e,t)=>{Dn.init(e,t),Z.init(e,t)});function Zs(e){return Bo(Ic,e)}var Tc=l("ZodISODate",(e,t)=>{Nn.init(e,t),Z.init(e,t)});function Ss(e){return Jo(Tc,e)}var Dc=l("ZodISOTime",(e,t)=>{Fn.init(e,t),Z.init(e,t)});function Es(e){return Vo(Dc,e)}var Nc=l("ZodISODuration",(e,t)=>{jn.init(e,t),Z.init(e,t)});function Rs(e){return qo(Nc,e)}var Lc=(e,t)=>{Me.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:r=>yr(e,r)},flatten:{value:r=>hr(e,r)},addIssue:{value:r=>{e.issues.push(r),e.message=JSON.stringify(e.issues,de,2)}},addIssues:{value:r=>{e.issues.push(...r),e.message=JSON.stringify(e.issues,de,2)}},isEmpty:{get(){return e.issues.length===0}}})};var F=l("ZodError",Lc,{Parent:Error});var Ps=Qe(F),Os=Ue(F),Cs=Ae(F),Is=Ze(F),Ts=xr(F),Ds=br(F),Ns=wr(F),Fs=vr(F),js=zr(F),Ls=$r(F),Ms=kr(F),Qs=Ar(F);var Us=new WeakMap;function Oe(e,t,r){let n=Object.getPrototypeOf(e),o=Us.get(n);if(o||(o=new Set,Us.set(n,o)),!o.has(t)){o.add(t);for(let s in r){let i=r[s];Object.defineProperty(n,s,{configurable:!0,enumerable:!1,get(){let c=i.bind(this);return Object.defineProperty(this,s,{configurable:!0,writable:!0,enumerable:!0,value:c}),c},set(c){Object.defineProperty(this,s,{configurable:!0,writable:!0,enumerable:!0,value:c})}})}}}var A=l("ZodType",(e,t)=>(z.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:Pe(e,"input"),output:Pe(e,"output")}}),e.toJSONSchema=ns(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(r,n)=>Ps(e,r,n,{callee:e.parse}),e.safeParse=(r,n)=>Cs(e,r,n),e.parseAsync=async(r,n)=>Os(e,r,n,{callee:e.parseAsync}),e.safeParseAsync=async(r,n)=>Is(e,r,n),e.spa=e.safeParseAsync,e.encode=(r,n)=>Ts(e,r,n),e.decode=(r,n)=>Ds(e,r,n),e.encodeAsync=async(r,n)=>Ns(e,r,n),e.decodeAsync=async(r,n)=>Fs(e,r,n),e.safeEncode=(r,n)=>js(e,r,n),e.safeDecode=(r,n)=>Ls(e,r,n),e.safeEncodeAsync=async(r,n)=>Ms(e,r,n),e.safeDecodeAsync=async(r,n)=>Qs(e,r,n),Oe(e,"ZodType",{check(...r){let n=this.def;return this.clone(b.mergeDefs(n,{checks:[...n.checks??[],...r.map(o=>typeof o=="function"?{_zod:{check:o,def:{check:"custom"},onattach:[]}}:o)]}),{parent:!0})},with(...r){return this.check(...r)},clone(r,n){return U(this,r,n)},brand(){return this},register(r,n){return r.add(this,n),this},refine(r,n){return this.check(Ia(r,n))},superRefine(r,n){return this.check(Ta(r,n))},overwrite(r){return this.check(ee(r))},optional(){return Ws(this)},exactOptional(){return ba(this)},nullable(){return Gs(this)},nullish(){return Ws(Gs(this))},nonoptional(r){return Aa(this,r)},array(){return P(this)},or(r){return rt([this,r])},and(r){return ha(this,r)},transform(r){return Ks(this,_a(r))},default(r){return za(this,r)},prefault(r){return ka(this,r)},catch(r){return Sa(this,r)},pipe(r){return Ks(this,r)},readonly(){return Pa(this)},describe(r){let n=this.clone();return se.add(n,{description:r}),n},meta(...r){if(r.length===0)return se.get(this);let n=this.clone();return se.add(n,r[0]),n},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(r){return r(this)}}),Object.defineProperty(e,"description",{get(){return se.get(e)?.description},configurable:!0}),e)),Xs=l("_ZodString",(e,t)=>{We.init(e,t),A.init(e,t),e._zod.processJSONSchema=(n,o,s)=>os(e,n,o,s);let r=e._zod.bag;e.format=r.format??null,e.minLength=r.minimum??null,e.maxLength=r.maximum??null,Oe(e,"_ZodString",{regex(...n){return this.check(Pt(...n))},includes(...n){return this.check(It(...n))},startsWith(...n){return this.check(Tt(...n))},endsWith(...n){return this.check(Dt(...n))},min(...n){return this.check(he(...n))},max(...n){return this.check(Ye(...n))},length(...n){return this.check(He(...n))},nonempty(...n){return this.check(he(1,...n))},lowercase(n){return this.check(Ot(n))},uppercase(n){return this.check(Ct(n))},trim(){return this.check(Ft())},normalize(...n){return this.check(Nt(...n))},toLowerCase(){return this.check(jt())},toUpperCase(){return this.check(Lt())},slugify(){return this.check(Mt())}})}),Qc=l("ZodString",(e,t)=>{We.init(e,t),Xs.init(e,t),e.email=r=>e.check(zo(Uc,r)),e.url=r=>e.check(So(Bc,r)),e.jwt=r=>e.check(Uo(sa,r)),e.emoji=r=>e.check(Eo(Jc,r)),e.guid=r=>e.check(Rt(Bs,r)),e.uuid=r=>e.check($o(tt,r)),e.uuidv4=r=>e.check(ko(tt,r)),e.uuidv6=r=>e.check(Ao(tt,r)),e.uuidv7=r=>e.check(Zo(tt,r)),e.nanoid=r=>e.check(Ro(Vc,r)),e.guid=r=>e.check(Rt(Bs,r)),e.cuid=r=>e.check(Po(qc,r)),e.cuid2=r=>e.check(Oo(Wc,r)),e.ulid=r=>e.check(Co(Gc,r)),e.base64=r=>e.check(Lo(ra,r)),e.base64url=r=>e.check(Mo(na,r)),e.xid=r=>e.check(Io(Kc,r)),e.ksuid=r=>e.check(To(Xc,r)),e.ipv4=r=>e.check(Do(Yc,r)),e.ipv6=r=>e.check(No(Hc,r)),e.cidrv4=r=>e.check(Fo(ea,r)),e.cidrv6=r=>e.check(jo(ta,r)),e.e164=r=>e.check(Qo(oa,r)),e.datetime=r=>e.check(Zs(r)),e.date=r=>e.check(Ss(r)),e.time=r=>e.check(Es(r)),e.duration=r=>e.check(Rs(r))});function g(e){return vo(Qc,e)}var Z=l("ZodStringFormat",(e,t)=>{k.init(e,t),Xs.init(e,t)}),Uc=l("ZodEmail",(e,t)=>{Zn.init(e,t),Z.init(e,t)});var Bs=l("ZodGUID",(e,t)=>{kn.init(e,t),Z.init(e,t)});var tt=l("ZodUUID",(e,t)=>{An.init(e,t),Z.init(e,t)});var Bc=l("ZodURL",(e,t)=>{Sn.init(e,t),Z.init(e,t)});var Jc=l("ZodEmoji",(e,t)=>{En.init(e,t),Z.init(e,t)});var Vc=l("ZodNanoID",(e,t)=>{Rn.init(e,t),Z.init(e,t)});var qc=l("ZodCUID",(e,t)=>{Pn.init(e,t),Z.init(e,t)});var Wc=l("ZodCUID2",(e,t)=>{On.init(e,t),Z.init(e,t)});var Gc=l("ZodULID",(e,t)=>{Cn.init(e,t),Z.init(e,t)});var Kc=l("ZodXID",(e,t)=>{In.init(e,t),Z.init(e,t)});var Xc=l("ZodKSUID",(e,t)=>{Tn.init(e,t),Z.init(e,t)});var Yc=l("ZodIPv4",(e,t)=>{Ln.init(e,t),Z.init(e,t)});var Hc=l("ZodIPv6",(e,t)=>{Mn.init(e,t),Z.init(e,t)});var ea=l("ZodCIDRv4",(e,t)=>{Qn.init(e,t),Z.init(e,t)});var ta=l("ZodCIDRv6",(e,t)=>{Un.init(e,t),Z.init(e,t)});var ra=l("ZodBase64",(e,t)=>{Jn.init(e,t),Z.init(e,t)});var na=l("ZodBase64URL",(e,t)=>{Vn.init(e,t),Z.init(e,t)});var oa=l("ZodE164",(e,t)=>{qn.init(e,t),Z.init(e,t)});var sa=l("ZodJWT",(e,t)=>{Wn.init(e,t),Z.init(e,t)});var Ys=l("ZodNumber",(e,t)=>{At.init(e,t),A.init(e,t),e._zod.processJSONSchema=(n,o,s)=>ss(e,n,o,s),Oe(e,"ZodNumber",{gt(n,o){return this.check(Ke(n,o))},gte(n,o){return this.check(Re(n,o))},min(n,o){return this.check(Re(n,o))},lt(n,o){return this.check(Ge(n,o))},lte(n,o){return this.check(Ee(n,o))},max(n,o){return this.check(Ee(n,o))},int(n){return this.check(Js(n))},safe(n){return this.check(Js(n))},positive(n){return this.check(Ke(0,n))},nonnegative(n){return this.check(Re(0,n))},negative(n){return this.check(Ge(0,n))},nonpositive(n){return this.check(Ee(0,n))},multipleOf(n,o){return this.check(Xe(n,o))},step(n,o){return this.check(Xe(n,o))},finite(){return this}});let r=e._zod.bag;e.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),e.isFinite=!0,e.format=r.format??null});function v(e){return Wo(Ys,e)}var ia=l("ZodNumberFormat",(e,t)=>{Gn.init(e,t),Ys.init(e,t)});function Js(e){return Go(ia,e)}var ca=l("ZodBoolean",(e,t)=>{Kn.init(e,t),A.init(e,t),e._zod.processJSONSchema=(r,n,o)=>is(e,r,n,o)});function te(e){return Ko(ca,e)}var aa=l("ZodNull",(e,t)=>{Xn.init(e,t),A.init(e,t),e._zod.processJSONSchema=(r,n,o)=>cs(e,r,n,o)});function ua(e){return Xo(aa,e)}var la=l("ZodUnknown",(e,t)=>{Yn.init(e,t),A.init(e,t),e._zod.processJSONSchema=(r,n,o)=>us(e,r,n,o)});function Vs(){return Yo(la)}var pa=l("ZodNever",(e,t)=>{Hn.init(e,t),A.init(e,t),e._zod.processJSONSchema=(r,n,o)=>as(e,r,n,o)});function Hs(e){return Ho(pa,e)}var da=l("ZodArray",(e,t)=>{eo.init(e,t),A.init(e,t),e._zod.processJSONSchema=(r,n,o)=>ms(e,r,n,o),e.element=t.element,Oe(e,"ZodArray",{min(r,n){return this.check(he(r,n))},nonempty(r){return this.check(he(1,r))},max(r,n){return this.check(Ye(r,n))},length(r,n){return this.check(He(r,n))},unwrap(){return this.element}})});function P(e,t){return es(da,e,t)}var ei=l("ZodObject",(e,t)=>{no.init(e,t),A.init(e,t),e._zod.processJSONSchema=(r,n,o)=>hs(e,r,n,o),b.defineLazy(e,"shape",()=>t.shape),Oe(e,"ZodObject",{keyof(){return G(Object.keys(this._zod.def.shape))},catchall(r){return this.clone({...this._zod.def,catchall:r})},passthrough(){return this.clone({...this._zod.def,catchall:Vs()})},loose(){return this.clone({...this._zod.def,catchall:Vs()})},strict(){return this.clone({...this._zod.def,catchall:Hs()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(r){return b.extend(this,r)},safeExtend(r){return b.safeExtend(this,r)},merge(r){return b.merge(this,r)},pick(r){return b.pick(this,r)},omit(r){return b.omit(this,r)},partial(...r){return b.partial(ri,this,r[0])},required(...r){return b.required(ni,this,r[0])}})});function M(e,t){let r={type:"object",shape:e??{},...b.normalizeParams(t)};return new ei(r)}function S(e,t){return new ei({type:"object",shape:e,catchall:Hs(),...b.normalizeParams(t)})}var ti=l("ZodUnion",(e,t)=>{Zt.init(e,t),A.init(e,t),e._zod.processJSONSchema=(r,n,o)=>ys(e,r,n,o),e.options=t.options});function rt(e,t){return new ti({type:"union",options:e,...b.normalizeParams(t)})}var fa=l("ZodDiscriminatedUnion",(e,t)=>{ti.init(e,t),oo.init(e,t)});function nt(e,t,r){return new fa({type:"union",options:t,discriminator:e,...b.normalizeParams(r)})}var ma=l("ZodIntersection",(e,t)=>{so.init(e,t),A.init(e,t),e._zod.processJSONSchema=(r,n,o)=>gs(e,r,n,o)});function ha(e,t){return new ma({type:"intersection",left:e,right:t})}var qs=l("ZodRecord",(e,t)=>{io.init(e,t),A.init(e,t),e._zod.processJSONSchema=(r,n,o)=>_s(e,r,n,o),e.keyType=t.keyType,e.valueType=t.valueType});function re(e,t,r){return!t||!t._zod?new qs({type:"record",keyType:g(),valueType:e,...b.normalizeParams(t)}):new qs({type:"record",keyType:e,valueType:t,...b.normalizeParams(r)})}var Vt=l("ZodEnum",(e,t)=>{co.init(e,t),A.init(e,t),e._zod.processJSONSchema=(n,o,s)=>ls(e,n,o,s),e.enum=t.entries,e.options=Object.values(t.entries);let r=new Set(Object.keys(t.entries));e.extract=(n,o)=>{let s={};for(let i of n)if(r.has(i))s[i]=t.entries[i];else throw new Error(`Key ${i} not found in enum`);return new Vt({...t,checks:[],...b.normalizeParams(o),entries:s})},e.exclude=(n,o)=>{let s={...t.entries};for(let i of n)if(r.has(i))delete s[i];else throw new Error(`Key ${i} not found in enum`);return new Vt({...t,checks:[],...b.normalizeParams(o),entries:s})}});function G(e,t){let r=Array.isArray(e)?Object.fromEntries(e.map(n=>[n,n])):e;return new Vt({type:"enum",entries:r,...b.normalizeParams(t)})}var ya=l("ZodLiteral",(e,t)=>{ao.init(e,t),A.init(e,t),e._zod.processJSONSchema=(r,n,o)=>ps(e,r,n,o),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function R(e,t){return new ya({type:"literal",values:Array.isArray(e)?e:[e],...b.normalizeParams(t)})}var ga=l("ZodTransform",(e,t)=>{uo.init(e,t),A.init(e,t),e._zod.processJSONSchema=(r,n,o)=>fs(e,r,n,o),e._zod.parse=(r,n)=>{if(n.direction==="backward")throw new le(e.constructor.name);r.addIssue=s=>{if(typeof s=="string")r.issues.push(b.issue(s,r.value,t));else{let i=s;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=r.value),i.inst??(i.inst=e),r.issues.push(b.issue(i))}};let o=t.transform(r.value,r);return o instanceof Promise?o.then(s=>(r.value=s,r.fallback=!0,r)):(r.value=o,r.fallback=!0,r)}});function _a(e){return new ga({type:"transform",transform:e})}var ri=l("ZodOptional",(e,t)=>{St.init(e,t),A.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Jt(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});function Ws(e){return new ri({type:"optional",innerType:e})}var xa=l("ZodExactOptional",(e,t)=>{lo.init(e,t),A.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Jt(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});function ba(e){return new xa({type:"optional",innerType:e})}var wa=l("ZodNullable",(e,t)=>{po.init(e,t),A.init(e,t),e._zod.processJSONSchema=(r,n,o)=>xs(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});function Gs(e){return new wa({type:"nullable",innerType:e})}var va=l("ZodDefault",(e,t)=>{fo.init(e,t),A.init(e,t),e._zod.processJSONSchema=(r,n,o)=>ws(e,r,n,o),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function za(e,t){return new va({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():b.shallowClone(t)}})}var $a=l("ZodPrefault",(e,t)=>{mo.init(e,t),A.init(e,t),e._zod.processJSONSchema=(r,n,o)=>vs(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});function ka(e,t){return new $a({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():b.shallowClone(t)}})}var ni=l("ZodNonOptional",(e,t)=>{ho.init(e,t),A.init(e,t),e._zod.processJSONSchema=(r,n,o)=>bs(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});function Aa(e,t){return new ni({type:"nonoptional",innerType:e,...b.normalizeParams(t)})}var Za=l("ZodCatch",(e,t)=>{yo.init(e,t),A.init(e,t),e._zod.processJSONSchema=(r,n,o)=>zs(e,r,n,o),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Sa(e,t){return new Za({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}var Ea=l("ZodPipe",(e,t)=>{go.init(e,t),A.init(e,t),e._zod.processJSONSchema=(r,n,o)=>$s(e,r,n,o),e.in=t.in,e.out=t.out});function Ks(e,t){return new Ea({type:"pipe",in:e,out:t})}var Ra=l("ZodReadonly",(e,t)=>{_o.init(e,t),A.init(e,t),e._zod.processJSONSchema=(r,n,o)=>ks(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});function Pa(e){return new Ra({type:"readonly",innerType:e})}var Oa=l("ZodLazy",(e,t)=>{xo.init(e,t),A.init(e,t),e._zod.processJSONSchema=(r,n,o)=>As(e,r,n,o),e.unwrap=()=>e._zod.def.getter()});function qt(e){return new Oa({type:"lazy",getter:e})}var Ca=l("ZodCustom",(e,t)=>{bo.init(e,t),A.init(e,t),e._zod.processJSONSchema=(r,n,o)=>ds(e,r,n,o)});function Ia(e,t={}){return ts(Ca,e,t)}function Ta(e,t){return rs(e,t)}function ye(e){let t=qt(()=>rt([g(e),v(),te(),ua(),P(t),re(g(),t)]));return t}var oi=e=>"field"in e?[e]:("all"in e?e.all:e.any).flatMap(oi),si=e=>oi(e);var ot=(e,t)=>{if("field"in e)return t(e);let r="all"in e?e.all:e.any,n=!1;if("all"in e){for(let o of r){let s=ot(o,t);if(s===!1)return!1;n||=s===void 0}return n?void 0:!0}for(let o of r){let s=ot(o,t);if(s===!0)return!0;n||=s===void 0}return n?void 0:!1},ii=e=>JSON.stringify(e),Wt=e=>{if("field"in e)return{conditions:1,depth:0};let t="all"in e?e.all:e.any,r=0,n=1;for(let o of t){let s=Wt(o);r+=s.conditions,n=Math.max(n,s.depth+1)}return{conditions:r,depth:n}},ci=(e,t={})=>{let r=o=>{let s=P(o),i=t.maximumChildren===void 0?s:s.max(t.maximumChildren);return rt([e,S({all:i}),S({any:i})])},n=qt(()=>r(n));return t.maximumConditions===void 0&&t.maximumDepth===void 0?n:n.superRefine((o,s)=>{let{conditions:i,depth:c}=Wt(o);t.maximumConditions!==void 0&&i>t.maximumConditions&&s.addIssue({code:"custom",message:t.maximumConditionsMessage??"Query exceeds the condition limit"}),t.maximumDepth!==void 0&&c>t.maximumDepth&&s.addIssue({code:"custom",message:t.maximumDepthMessage??"Query exceeds the nesting limit"})})};var x={requestBytes:524288,filterCount:32,filterDepth:8,sortCount:8,outputFieldCount:256,fieldPathDepth:9,defaultResultCount:20,resultCount:1e3,resultBytes:16777216,candidateDocuments:1e3,databaseBytes:512e3,frontmatterBytes:65536,frontmatterDepth:8,frontmatterFields:256,frontmatterStringBytes:16384,jsonBytes:1048576,jsonDepth:8,jsonFields:256,jsonStringBytes:16384,indexedPropertiesBytes:65536,excerptBytes:2048,hydratedFileBytes:1048576,hydratedTotalBytes:2097152,hydratedFileCount:20,hydratedRangeBytes:262144,concurrentContentReads:8};var Da=g().min(1).refine(e=>e.startsWith("/")===!1,{error:"Asset path must be relative"}).refine(e=>e.includes("\\")===!1&&e.split("/").every(t=>t.length>0&&t!==".."&&t!=="."),{error:"Asset path must be normalized and must not contain dot segments"}),ui=S({_id:g().min(1),_type:R("asset.file"),name:g().min(1),description:g().optional(),path:Da,key:g(),folderId:g().min(1).optional(),extension:g().regex(/^[a-z0-9]*$/),mimeType:g().min(1),size:v().int().nonnegative(),createdAt:g().datetime().optional(),revision:g().min(1),contentRef:g().min(1),properties:re(g(),ye()),excerpt:g().optional(),metadataError:S({code:g().min(1),message:g().min(1)}).optional()}),Na=ui.partial().required({_id:!0}),Fa=G(["null","boolean","number","string","object","array"]),ja=M({format:R("webstudio-builder-asset-field-catalog"),version:R(1),canonicalRevision:g().regex(/^sha256:[a-f0-9]{64}$/),documentCount:v().int().nonnegative(),fields:re(g().min(1),M({queryPath:P(g().min(1)).min(1).max(x.fieldPathDepth).optional(),types:P(Fa).min(1),occurrences:v().int().positive(),optional:R(!0).optional(),mixed:R(!0).optional()}))}).superRefine((e,t)=>{for(let[r,n]of Object.entries(e.fields)){let o=[...new Set(n.types)].sort();JSON.stringify(n.types)!==JSON.stringify(o)&&t.addIssue({code:"custom",path:["fields",r,"types"],message:"Observed field types must be unique and sorted"}),n.occurrences>e.documentCount&&t.addIssue({code:"custom",path:["fields",r,"occurrences"],message:"Field occurrences cannot exceed the document count"});let s=n.occurrences<e.documentCount;n.optional===!0!==s&&t.addIssue({code:"custom",path:["fields",r,"optional"],message:"Field optionality must match its occurrence count"});let i=o.length>1;n.mixed===!0!==i&&t.addIssue({code:"custom",path:["fields",r,"mixed"],message:"Mixed status must match the observed types"})}}),st=g().regex(/^sha256:[a-f0-9]{64}$/),li=S({fields:P(P(g().min(1)).min(1).max(x.fieldPathDepth)).min(1).max(x.outputFieldCount+1),rows:P(P(ye())).max(x.resultCount),totalCount:v().int().nonnegative().max(x.candidateDocuments),hasMore:te()}).superRefine(({fields:e,rows:t},r)=>{for(let[n,o]of t.entries())o.length!==e.length&&r.addIssue({code:"custom",path:["rows",n],message:"Materialized query rows must match the field count"})}),pi=S({format:R("webstudio-content-database"),version:R(1),assetRevision:st,documents:P(Na),contents:re(g().min(1),g()).optional(),assetReferences:re(g().min(1),P(S({start:v().int().nonnegative(),end:v().int().positive(),assetId:g().min(1),suffix:g().min(1).optional()}).refine(({start:e,end:t})=>t>e,{message:"Markdown asset reference range must not be empty"}))).optional(),fieldCatalog:ja,queries:re(st,li).optional(),database:S({maxBytes:v().int().positive(),unboundedBytes:v().int().nonnegative(),sourceDocumentCount:v().int().nonnegative(),includedDocumentCount:v().int().nonnegative().optional()}).optional(),integrity:S({algorithm:R("sha256"),checksum:st})}).superRefine((e,t)=>{e.documents.length>x.candidateDocuments&&t.addIssue({code:"custom",path:["documents"],message:"Asset index exceeds the document limit"}),(e.fieldCatalog.canonicalRevision!==e.assetRevision||e.fieldCatalog.documentCount!==e.documents.length)&&t.addIssue({code:"custom",path:["fieldCatalog"],message:"Asset index field catalog does not match its documents"}),e.database!==void 0&&e.database.sourceDocumentCount<e.documents.length&&t.addIssue({code:"custom",path:["database","sourceDocumentCount"],message:"Source document count cannot be smaller than the database"}),e.database?.includedDocumentCount!==void 0&&(e.database.includedDocumentCount<e.documents.length||e.database.includedDocumentCount>e.database.sourceDocumentCount)&&t.addIssue({code:"custom",path:["database","includedDocumentCount"],message:"Included document count must match the database bounds"});let r;for(let[o,s]of e.documents.entries())r!==void 0&&s._id<=r&&t.addIssue({code:"custom",path:["documents",o,"_id"],message:"Asset index documents must have unique sorted IDs"}),r=s._id;let n=new Set(e.documents.flatMap(({contentRef:o})=>o===void 0?[]:[o]));for(let o of Object.keys(e.contents??{}))n.has(o)===!1&&t.addIssue({code:"custom",path:["contents",o],message:"Embedded content must belong to an indexed document"});for(let o of Object.keys(e.assetReferences??{}))n.has(o)===!1&&t.addIssue({code:"custom",path:["assetReferences",o],message:"Asset references must belong to an indexed document"})}),La=nt("mode",[M({mode:R("none")}),M({mode:R("full"),maxBytes:v().int().positive().max(x.hydratedFileBytes).optional()}),M({mode:R("range"),offset:v().int().nonnegative(),length:v().int().positive().max(x.hydratedRangeBytes)}),M({mode:R("markdown-body"),maxBytes:v().int().positive().max(x.hydratedFileBytes).optional()})]),Kt={id:["string"],url:["string"],width:["number"],height:["number"],name:["string"],description:["string"],path:["string"],key:["string"],folderId:["string"],extension:["string"],mimeType:["string"],size:["number"],createdAt:["string"],revision:["string"],excerpt:["string"]},di=Object.keys(Kt),fi=["url","width","height"],it=e=>fi.includes(e),mi=di.filter(e=>it(e)===!1&&e!=="excerpt"),hi=mi.filter(e=>e!=="id"),yi=e=>mi.includes(e),Ma=G(di),Ce=P(g().min(1)).min(1).max(x.fieldPathDepth).superRefine((e,t)=>{if(e[0]==="properties"){e.length<2&&t.addIssue({code:"custom",message:"A properties field path must select a property"});return}(e.length!==1||Ma.safeParse(e[0]).success===!1)&&t.addIssue({code:"custom",message:"Asset query field path is unsupported"})}),Gt=te().default(!0),Qa=nt("mode",[S({mode:R("all"),includeMetadata:Gt}),S({mode:R("base"),includeMetadata:Gt}),S({mode:R("fields"),includeMetadata:Gt,fields:P(Ce).max(x.outputFieldCount).refine(e=>new Set(e.map(ii)).size===e.length,{error:"Selected output fields must be unique"})})]),Ua={mode:"fields",includeMetadata:!1,fields:fi.map(e=>[e])},gi=["eq","ne","contains","startsWith","endsWith","gt","gte","lt","lte"],Bp=[...gi,"in","exists","isEmpty"],Ba=S({field:Ce,operator:G(gi),value:ye()}),Ja=S({field:Ce,operator:R("in"),value:P(ye()).max(x.resultCount)}),Va=S({field:Ce,operator:G(["exists","isEmpty"]),value:te()}),qa=nt("operator",[Ba,Ja,Va]),Wa=ci(qa,{maximumChildren:x.filterCount,maximumConditions:x.filterCount,maximumDepth:x.filterDepth,maximumConditionsMessage:"Asset query exceeds the filter limit",maximumDepthMessage:"Asset query exceeds the filter nesting limit"});var Ga=Wa,_i=e=>{let t=new Set(["eq","ne","in","exists"]);return e.some(r=>r==="string"||r==="array")&&t.add("contains"),e.includes("string")&&(t.add("startsWith"),t.add("endsWith")),e.some(r=>r==="string"||r==="number")&&(t.add("gt"),t.add("gte"),t.add("lt"),t.add("lte")),e.some(r=>r==="string"||r==="array"||r==="object")&&t.add("isEmpty"),[...t]},Ka=S({field:Ce,direction:G(["asc","desc"])}),Xa=({output:e,content:t})=>e.includeMetadata||e.mode==="all"||e.mode==="fields"&&e.fields.length>0||t.mode!=="none",ge=S({where:Ga.default({all:[]}),sort:P(Ka).max(x.sortCount).default([]),limit:v().int().nonnegative().max(x.resultCount).default(x.defaultResultCount),offset:v().int().nonnegative().max(x.candidateDocuments).default(0),output:Qa.default(Ua),content:La.default({mode:"none"})}).refine(Xa,{error:"Select at least one asset query output"}),xi=S({query:ge,indexRevision:g().min(1).max(255).optional()}),Ya=M({_id:g().min(1),revision:g().min(1),contentRef:g().min(1),encoding:R("utf-8"),text:g(),range:M({offset:v().int().nonnegative(),length:v().int().nonnegative(),total:v().int().nonnegative()}).optional()}),Ha=Ya.omit({_id:!0,revision:!0,contentRef:!0}),eu=ui.omit({_id:!0,_type:!0,contentRef:!0}).partial().extend({id:g().min(1),url:g().min(1).optional(),width:v().positive().optional(),height:v().positive().optional(),content:Ha.optional()}).refine(e=>e.width===void 0==(e.height===void 0),{error:"Asset dimensions must include both width and height"}),tu=S({format:R("webstudio-content-database"),version:R(1),revision:st,usedBytes:v().int().nonnegative(),maxBytes:v().int().positive(),unboundedBytes:v().int().nonnegative(),includedDocumentCount:v().int().nonnegative(),omittedDocumentCount:v().int().nonnegative(),omissionReason:G(["size","unavailable"]).optional(),truncated:te()}),ai=tu.pick({usedBytes:!0,maxBytes:!0,unboundedBytes:!0,includedDocumentCount:!0,omittedDocumentCount:!0,omissionReason:!0,truncated:!0}),ru=S({scope:R("query-preview"),query:ai,database:ai}),Xt=S({items:P(eu),totalCount:v().int().nonnegative(),hasMore:te()}),Jp=S({data:Xt,__diagnostics__:ru}),nu=G(["INVALID_REQUEST","REQUEST_CANCELLED","UNAUTHORIZED","FORBIDDEN","STALE_INDEX","CONTENT_IDENTITY_REQUIRED","CONTENT_NOT_TEXT","CONTENT_DECODING_FAILED","CONTENT_LIMIT_EXCEEDED","INTERNAL_ERROR"]),ou=M({ok:R(!1),error:M({code:nu,message:g().min(1),retryable:te(),details:re(g(),ye()).optional()}),meta:M({queryHash:g().min(1).optional(),indexRevision:g().min(1).optional(),assetRevision:g().min(1).optional()}).optional()}),bi=({code:e,message:t,retryable:r=!1,details:n})=>ou.parse({ok:!1,error:{code:e,message:t,retryable:r,details:n}});function ie(e,t=new Set){if(typeof e=="number"&&isNaN(e))throw new Error("NaN is not allowed");if(typeof e=="number"&&!isFinite(e))throw new Error("Infinity is not allowed");if(e===null||typeof e!="object")return JSON.stringify(e);if(typeof e.toJSON=="function"){if(t.has(e))throw new Error("Circular reference detected");t.add(e);let n=ie(e.toJSON(),t);return t.delete(e),n}if(t.has(e))throw new Error("Circular reference detected");t.add(e);let r;if(Array.isArray(e))r=`[${e.map(o=>ie(o===void 0||typeof o=="symbol"?null:o,t)).join(",")}]`;else{let n=[];for(let o of Object.keys(e).sort())e[o]===void 0||typeof e[o]=="symbol"||n.push(`${ie(o)}:${ie(e[o],t)}`);r=`{${n.join(",")}}`}return t.delete(e),r}var su=new TextEncoder,_e=e=>su.encode(e),ne=e=>_e(e).byteLength,ce=class extends Error{constructor(){super("Byte stream exceeds the configured limit"),this.name="ByteLimitExceededError"}},iu=(e,t)=>{let r=new Uint8Array(t),n=0;for(let o of e)r.set(o,n),n+=o.byteLength;return r},cu=e=>typeof e=="string"?{async*[Symbol.asyncIterator](){yield _e(e)}}:e instanceof Uint8Array?{async*[Symbol.asyncIterator](){yield e}}:e,au=async(e,t)=>{let r=[],n=0;for await(let o of cu(e)){let s=t-n;if(s<=0)break;let i=o.subarray(0,s);if(r.push(i),n+=i.byteLength,n===t)break}return iu(r,n)},ct=async(e,t)=>{let r=await au(e,t+1);if(r.byteLength>t)throw new ce;return r},ae=e=>new TextDecoder("utf-8",{fatal:!0}).decode(e),wi=e=>e.charCodeAt(0)===65279?e.slice(1):e;var vi=e=>{for(let t=0;t<e.length;t+=1){let r=e.charCodeAt(t);if(r>=55296&&r<=56319){let n=e.charCodeAt(t+1);if(t+1>=e.length||n<56320||n>57343)throw new Error("JSON strings cannot contain lone Unicode surrogates");t+=1;continue}if(r>=56320&&r<=57343)throw new Error("JSON strings cannot contain lone Unicode surrogates")}},Yt=(e,t)=>{if(e===null||typeof e=="boolean")return e;if(typeof e=="string")return vi(e),e;if(typeof e=="number"){if(Number.isFinite(e)===!1)throw new Error("JSON cannot contain non-finite numbers");return e}if(Array.isArray(e)){if(Object.getOwnPropertySymbols(e).length>0)throw new Error("JSON arrays cannot contain symbol properties");if(t.has(e))throw new Error("JSON cannot contain circular references");t.add(e);try{let r=[];for(let n=0;n<e.length;n+=1){if(Object.hasOwn(e,n)===!1)throw new Error("JSON arrays cannot be sparse");let o=e[n];if(o===void 0)throw new Error("JSON arrays cannot contain undefined values");r.push(Yt(o,t))}if(Object.keys(e).length!==e.length)throw new Error("JSON arrays cannot contain named properties");return r}finally{t.delete(e)}}if(typeof e=="object"){let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)throw new Error("JSON can contain only plain objects");if(Object.getOwnPropertySymbols(e).length>0)throw new Error("JSON objects cannot contain symbol properties");if(t.has(e))throw new Error("JSON cannot contain circular references");t.add(e);let n={};try{for(let[o,s]of Object.entries(e))vi(o),s!==void 0&&Object.defineProperty(n,o,{value:Yt(s,t),enumerable:!0,configurable:!0,writable:!0})}finally{t.delete(e)}return n}throw new Error("Value cannot be represented as JSON")},uu=e=>Yt(e,new Set),J=e=>{let t=ie(uu(e));if(t===void 0)throw new Error("Value cannot be represented as canonical JSON");return t},Ie=(e,t)=>e<t?-1:e>t?1:0,Ht=async e=>{let t=typeof e=="string"?_e(e):e,r=await globalThis.crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(r),n=>n.toString(16).padStart(2,"0")).join("")},er=async e=>`sha256:${await Ht(e)}`;var zi=e=>J(pi.parse(e)),$i=e=>[...new Set(Object.values(e.assetReferences??{}).flat().map(({assetId:t})=>t))].sort();var ue=class extends Error{code;constructor(t,r){super(r),this.name="MarkdownMetadataError",this.code=t}};var Te=new Uint8Array([239,187,191]),rd=Te.byteLength+10,lu=(e,t,r=0)=>e.byteLength-r<t.byteLength?!1:t.every((n,o)=>e[r+o]===n),ki=(e,t)=>{let r=0;if(lu(e,Te))r=Te.byteLength;else if(e.byteLength<Te.byteLength&&Te.slice(0,e.byteLength).every((s,i)=>s===e[i]))return t?null:void 0;if(e.byteLength<r+4)return t?null:void 0;if(e[r]!==45||e[r+1]!==45||e[r+2]!==45)return null;let n=r+3;if(e[n]===10)n+=1;else if(e[n]===13){if(e.byteLength===n+1)return t?null:void 0;if(e[n+1]!==10)return null;n+=2}else return null;let o=n;for(let s=n;s<=e.byteLength;s+=1){let i=s===e.byteLength;if(i===!1&&e[s]!==10)continue;if(i&&t===!1)return;let c=s;if(c>o&&e[c-1]===13&&(c-=1),c-o===3&&(e[o]===45&&e[o+1]===45&&e[o+2]===45||e[o]===46&&e[o+1]===46&&e[o+2]===46))return{yamlStart:n,yamlEnd:o,blockEnd:i?s:s+1};o=s+1}};var Ai=async(e,t=x.hydratedFileBytes)=>{if(Number.isInteger(t)===!1||t<=0||t>x.hydratedFileBytes)throw new ue("MARKDOWN_BODY_BYTES_EXCEEDED","Markdown body byte limit is outside the supported range");let r;try{r=await ct(e,t)}catch(c){throw c instanceof ce?new ue("MARKDOWN_BODY_BYTES_EXCEEDED","Markdown content exceeds the byte limit"):c}let n;try{n=ae(r)}catch{throw new ue("MARKDOWN_BODY_DECODING_FAILED","Markdown content is not valid UTF-8")}let s=ki(r,!0)?.blockEnd??0,i;try{i=s===0?wi(n):ae(r.subarray(s))}catch{throw new ue("MARKDOWN_BODY_DECODING_FAILED","Markdown content is not valid UTF-8")}return{body:i,bodyBytes:ne(i),sourceBytes:r.byteLength}};var Zi=async(e,t,r)=>{if(Number.isSafeInteger(t)===!1||t<=0)throw new Error("Concurrency must be a positive safe integer");let n=0,o=new Array(e.length),s=async()=>{for(;n<e.length;){let u=n;n+=1,o[u]=await r(e[u])}},i=Array.from({length:Math.min(t,e.length)},s),a=(await Promise.allSettled(i)).find(u=>u.status==="rejected");if(a!==void 0)throw a.reason;return o};var pu=(e,t)=>{if(t===void 0||t.length===0)return e;let r=new URL("https://content.webstudio.invalid/__assets__/"),n=new URL(e,r),o=new URL(t,r);for(let[c,a]of o.searchParams)n.searchParams.append(c,a);if(o.hash!==""&&(n.hash=o.hash),URL.canParse(e))return n.href;if(e.startsWith("//"))return`//${n.host}${n.pathname}${n.search}${n.hash}`;if(e.startsWith("/"))return`${n.pathname}${n.search}${n.hash}`;let s=r.pathname;return`${n.pathname.startsWith(s)?n.pathname.slice(s.length):n.pathname}${n.search}${n.hash}`},Si=({markdown:e,references:t,assetUrls:r})=>{let n=e.length,o=e;for(let s of[...t].sort((i,c)=>c.start-i.start)){if(s.start<0||s.end<=s.start||s.end>e.length||s.end>n)throw new Error("Markdown asset reference range is invalid");n=s.start;let i=r[s.assetId];if(i===void 0)continue;let c=pu(i,s.suffix);o=`${o.slice(0,s.start)}${c}${o.slice(s.end)}`}return o};var D=class extends Error{code;details;constructor({code:t,message:r,details:n}){super(r),this.name="AssetResourceHydrationError",this.code=t,this.details=n}},du=e=>{if(e===null)return[];let t=Array.isArray(e)?e:[e],r=new Map;for(let n of t){if(typeof n!="object"||n===null||!("_id"in n)||typeof n._id!="string"||!("revision"in n)||typeof n.revision!="string"||!("contentRef"in n)||typeof n.contentRef!="string")throw new D({code:"CONTENT_IDENTITY_REQUIRED",message:"Hydrated query results must retain _id, revision, and contentRef"});let o=r.get(n._id);if(o!==void 0&&(o.revision!==n.revision||o.contentRef!==n.contentRef))throw new D({code:"CONTENT_IDENTITY_REQUIRED",message:"A selected asset ID has conflicting content identity",details:{assetId:n._id}});r.set(n._id,{_id:n._id,revision:n.revision,contentRef:n.contentRef})}return Array.from(r.values())},fu=e=>typeof e.mimeType=="string"&&(e.mimeType.startsWith("text/")||["application/json","application/javascript","application/xml","image/svg+xml"].includes(e.mimeType)),mu=async({read:e,contentRef:t,range:r,maximumBytes:n})=>{if(n===0)return new Uint8Array;let o=await e(t,r);try{return await ct(o.data,n)}catch(s){throw s instanceof ce?new D({code:"CONTENT_LIMIT_EXCEEDED",message:"Asset storage returned more content than requested"}):s}},hu=e=>{try{return ae(e)}catch{throw new D({code:"CONTENT_DECODING_FAILED",message:"Selected asset content is not valid UTF-8"})}},yu=(e,t)=>{if(t.mode==="range")return Math.max(0,Math.min(t.length,e.size-t.offset));let r=t.maxBytes??x.hydratedFileBytes;if(e.size>r)throw new D({code:"CONTENT_LIMIT_EXCEEDED",message:"Selected asset exceeds the per-file content limit",details:{assetId:e._id,assetBytes:e.size,fileByteLimit:r}});return e.size},Ei=async({result:e,documents:t,options:r,read:n,assetReferences:o,assetUrls:s})=>{if(r.mode==="none")return{content:{},hydratedFileCount:0,hydratedBytes:0};let i=du(e);if(i.length>x.hydratedFileCount)throw new D({code:"CONTENT_LIMIT_EXCEEDED",message:"Too many selected assets requested content hydration",details:{fileCount:i.length,fileCountLimit:x.hydratedFileCount}});let c=new Map(t.map(p=>[p._id,p])),a=i.map(p=>{let m=c.get(p._id);if(m===void 0||m.revision!==p.revision||m.contentRef!==p.contentRef||typeof m.size!="number"||typeof m.mimeType!="string")throw new D({code:"CONTENT_IDENTITY_REQUIRED",message:"Selected asset content identity is stale or unavailable",details:{assetId:p._id}});let d={...m,size:m.size,mimeType:m.mimeType};if(fu(d)===!1)throw new D({code:"CONTENT_NOT_TEXT",message:"Selected binary asset cannot be embedded as text",details:{assetId:p._id,mimeType:d.mimeType}});return{identity:p,document:d,readLength:yu(d,r)}}),u=a.reduce((p,m)=>p+m.readLength,0);if(u>x.hydratedTotalBytes)throw new D({code:"CONTENT_LIMIT_EXCEEDED",message:"Selected assets exceed the total hydrated-content limit",details:{totalReadBytes:u,totalByteLimit:x.hydratedTotalBytes}});let f=await Zi(a,x.concurrentContentReads,async p=>{let m=r.mode==="range"?{offset:r.offset,length:p.readLength}:p.readLength===0?void 0:{offset:0,length:p.readLength},d=await mu({read:n,contentRef:p.identity.contentRef,range:m,maximumBytes:p.readLength});if(d.byteLength!==p.readLength)throw new D({code:"CONTENT_IDENTITY_REQUIRED",message:"Selected asset bytes do not match canonical metadata",details:{assetId:p.identity._id}});let y;if(r.mode==="markdown-body")try{y=(await Ai(d,p.readLength||1)).body;let w=o?.[p.identity.contentRef];w!==void 0&&s!==void 0&&(y=Si({markdown:y,references:w,assetUrls:s}))}catch{throw new D({code:"CONTENT_DECODING_FAILED",message:"Selected Markdown body could not be decoded",details:{assetId:p.identity._id}})}else y=hu(d);let O=ne(y);return{id:p.identity._id,returnedBytes:O,content:{...p.identity,encoding:"utf-8",text:y,...r.mode==="range"?{range:{offset:r.offset,length:d.byteLength,total:p.document.size}}:{}}}});return{content:Object.fromEntries(f.map(({id:p,content:m})=>[p,m])),hydratedFileCount:a.length,hydratedBytes:f.reduce((p,{returnedBytes:m})=>p+m,0)}};var _d=g().datetime({offset:!0}).transform(e=>new Date(e).toISOString());var gu=/^[A-Za-z_][A-Za-z0-9_]*$/,Ri=(e,t)=>gu.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`;var Pi=({document:e,includes:t})=>{let r={};for(let n of hi){let o=e[n];o!==void 0&&t(n)&&(r[n]=o)}return r},Oi=({source:e,target:t,path:r})=>{let[n,...o]=r;if(n===void 0||Object.hasOwn(e,n)===!1)return;let s=e[n];if(o.length===0){Object.defineProperty(t,n,{value:s,enumerable:!0,configurable:!0,writable:!0});return}if(typeof s!="object"||s===null||Array.isArray(s))return;let i={};if(Oi({source:s,target:i,path:o}),Object.keys(i).length===0)return;let c=t[n];Object.defineProperty(t,n,{value:{...typeof c=="object"&&c!==null&&Array.isArray(c)===!1?c:{},...i},enumerable:!0,configurable:!0,writable:!0})},Ci=({properties:e,fields:t})=>{let r={};for(let n of t)n[0]==="properties"&&Oi({source:e,target:r,path:n.slice(1)});return r};var K=class extends Error{constructor(t,r){super(t,r),this.name="AssetQueryExecutionError"}},be=class extends Error{constructor(){super("The requested asset index revision is stale"),this.name="AssetIndexRevisionError"}},Ii=e=>{if(e[0]!=="properties")return e[0];let t="properties";for(let r of e.slice(1))t=Ri(t,r);return t},Ti=({filter:e,fieldTypes:t})=>_i(t).includes(e.operator),Di=(e,t)=>Object.hasOwn(e.fields,t)?e.fields[t]:void 0,_u=({query:e,catalog:t})=>{let r=ge.parse(e),n=new Map,o=[];for(let s of si(r.where)){let i=Ii(s.field);if(n.set(i,s.field),s.field[0]==="properties"){let c=Di(t,i);c===void 0?o.push(`Asset field ${i} is not currently observed`):Ti({filter:s,fieldTypes:c.types})===!1&&o.push(`Operator ${s.operator} is not compatible with the currently observed types of ${i}`)}else if(Ti({filter:s,fieldTypes:Kt[s.field[0]]})===!1)throw new K(`Operator ${s.operator} is incompatible with ${i}`)}for(let s of r.sort){let i=Ii(s.field);if(n.set(i,s.field),s.field[0]==="properties"){let c=Di(t,i);c===void 0?o.push(`Asset field ${i} is not currently observed`):c.types.some(a=>a==="object"||a==="array")&&o.push(`Asset field ${i} currently includes structured values that use deterministic JSON sort order`)}}return{query:r,referencedFieldPaths:[...n.values()],warnings:[...new Set(o)]}},tr=(e,t,r)=>{let n=t[0]==="id"?e._id:it(t[0])?r?.[t[0]]:e[t[0]];for(let o of t.slice(1)){if(typeof n!="object"||n===null||Object.hasOwn(n,o)===!1)return;n=n[o]}return n},at=(e,t)=>e===void 0||t===void 0?e===t:J(e)===J(t),xu=e=>typeof e=="string"||Array.isArray(e)?e.length===0:typeof e=="object"&&e!==null&&Object.keys(e).length===0,bu=(e,t)=>{if(typeof e=="number"&&typeof t=="number")return e-t;if(typeof e=="string"&&typeof t=="string")return Ie(e,t)},wu=(e,t,r)=>{let n=tr(e,t.field,r);if(t.operator==="exists")return n!=null===t.value;if(t.operator==="isEmpty")return xu(n)===t.value;if(t.operator==="eq")return at(n,t.value);if(t.operator==="ne")return at(n,t.value)===!1;if(t.operator==="in")return t.value.some(s=>at(n,s));if(t.operator==="contains")return typeof n=="string"&&typeof t.value=="string"?n.includes(t.value):Array.isArray(n)&&n.some(s=>at(s,t.value));if(t.operator==="startsWith")return typeof n=="string"&&typeof t.value=="string"&&n.startsWith(t.value);if(t.operator==="endsWith")return typeof n=="string"&&typeof t.value=="string"&&n.endsWith(t.value);let o=bu(n,t.value);return o===void 0?!1:t.operator==="gt"?o>0:t.operator==="gte"?o>=0:t.operator==="lt"?o<0:o<=0},vu=(e,t,r)=>ot(t,n=>wu(e,n,r))===!0,zu=(e,t)=>{let r=e==null,n=t==null;return r||n?r===n?0:r?1:-1:typeof e=="number"&&typeof t=="number"?e-t:(typeof e=="string"||typeof e=="boolean")&&(typeof t=="string"||typeof t=="boolean")?Ie(String(e),String(t)):Ie(J(e),J(t))},$u=({left:e,right:t,sort:r,runtimeAssets:n})=>{for(let o of r){let s=zu(tr(e,o.field,n?.[e._id]),tr(t,o.field,n?.[t._id]));if(s!==0)return o.direction==="asc"?s:-s}return Ie(e._id,t._id)};var ku=(e,t)=>{if(e.properties===void 0)return;if(t.mode==="all")return Object.keys(e.properties).length===0?void 0:e.properties;if(t.mode!=="fields"||t.fields.some(n=>n[0]==="properties")===!1)return;let r=Ci({properties:e.properties,fields:t.fields});return Object.keys(r).length===0?void 0:r},xe=(e,t)=>e.includeMetadata&&yi(t)||e.mode==="fields"&&e.fields.some(r=>r.length===1&&r[0]===t),Au=e=>e.mode==="all"||e.mode==="fields"&&e.fields.some(t=>t.length===1&&t[0]==="excerpt"),Zu=(e,t,r)=>{if(xe(t,"url")&&r===void 0)throw new Error(`Asset URL is unavailable for ${e._id}`);let n=ku(e,t),o=r?.width!==void 0&&r.height!==void 0;return{...r!==void 0&&xe(t,"url")?{url:r.url}:{},...o&&xe(t,"width")?{width:r.width}:{},...o&&xe(t,"height")?{height:r.height}:{},...Pi({document:e,includes:s=>xe(t,s)}),...n===void 0?{}:{properties:n},...e.excerpt===void 0||Au(t)===!1?{}:{excerpt:e.excerpt},...e.metadataError===void 0||t.includeMetadata===!1?{}:{metadataError:e.metadataError}}},Su=e=>{if(ne(J(e))>x.resultBytes)throw new K("Asset query result exceeds the byte limit")},Ni=async({query:e,catalog:t,documents:r,read:n,runtimeAssets:o,assetReferences:s})=>{let{query:i}=_u({query:e,catalog:t});if(r.length>x.candidateDocuments)throw new K("Asset query document limit was exceeded");let c=r.flatMap(d=>{let y=o?.[d._id];if(vu(d,i.where,y)===!1)return[];let O=Zu(d,i.output,y);return i.content.mode==="none"&&Object.keys(O).length===0&&xe(i.output,"id")===!1?[]:[{document:d,item:{id:d._id,...O}}]}),u=[...c].sort((d,y)=>$u({left:d.document,right:y.document,sort:i.sort,runtimeAssets:o})).slice(i.offset,i.offset+i.limit),f=u.map(({document:d})=>d),p=u.map(({item:d})=>d);if(i.content.mode!=="none"){let d=i.content;if(n===void 0)throw new K("Asset content reader is unavailable");let y=await Ei({result:f,documents:f,options:d,read:n,assetReferences:s,assetUrls:s===void 0?void 0:Object.fromEntries(Object.entries(o??{}).map(([O,w])=>[O,w.url]))});p=f.map((O,w)=>{let j=y.content[O._id];if(j===void 0)throw new K("Selected asset content could not be read");return{...p[w],content:{encoding:j.encoding,text:j.text,...j.range===void 0?{}:{range:j.range}}}})}let m={items:p,totalCount:c.length,hasMore:i.offset+u.length<c.length};return Su(m),m};var Eu=async e=>await er(J(ge.parse(e)));var Ru=({item:e,field:t,value:r})=>{let n=e;for(let[o,s]of t.entries()){if(o===t.length-1){Object.defineProperty(n,s,{value:r,enumerable:!0,configurable:!0,writable:!0});return}let i=Object.hasOwn(n,s)?n[s]:void 0;if(typeof i=="object"&&i!==null){n=i;continue}let c={};Object.defineProperty(n,s,{value:c,enumerable:!0,configurable:!0,writable:!0}),n=c}},Pu=e=>Xt.parse({items:e.rows.map(t=>{let r={};for(let[n,o]of e.fields.entries())Ru({item:r,field:o,value:t[n]});return r}),totalCount:e.totalCount,hasMore:e.hasMore}),Fi=async({queries:e,query:t})=>{if(e===void 0)return;let r=e[await Eu(ge.parse(t))];return r===void 0?void 0:Pu(r)};var rr=({artifact:e,readContent:t})=>{let r=e.database?.includedDocumentCount??e.documents.length,o=(e.database?.sourceDocumentCount??r)-r,s=ne(zi(e)),i=e.database?.maxBytes??Number.MAX_SAFE_INTEGER,c=e.database?.unboundedBytes??s,a={format:e.format,version:e.version,revision:e.integrity.checksum,usedBytes:s,maxBytes:i,unboundedBytes:c,includedDocumentCount:r,omittedDocumentCount:o,omissionReason:o===0?void 0:c>i?"size":"unavailable",truncated:o>0};return{query:async(u,f,p)=>{if(u.indexRevision!==void 0&&u.indexRevision!==e.integrity.checksum)throw new be;let m=await Fi({queries:e.queries,query:u.query});if(m!==void 0)return m;let d=async(O,w)=>{let j=e.contents?.[O];if(j===void 0){let $=f??t;if($===void 0)throw new Error("Content is not embedded in this database");return await $(O,w)}let Fe=_e(j),N=w===void 0?Fe:Fe.slice(w.offset,w.offset+w.length);return{data:async function*(){yield N}(),contentLength:N.byteLength}};return await Ni({query:u.query,catalog:e.fieldCatalog,documents:e.documents,read:d,runtimeAssets:p,assetReferences:e.assetReferences})},getFieldCatalog:()=>e.fieldCatalog,getStats:()=>a}};var ut=class extends Error{constructor(t,r){super(t,r),this.name="AssetQueryRequestError"}},De=class extends Error{},Ou=async(e,t)=>{if(Number.isSafeInteger(t)===!1||t<0)throw new TypeError("Request byte limit must be a non-negative integer");let r=Number(e.headers.get("content-length"));if(Number.isFinite(r)&&r>t)throw new De("Request exceeds the byte limit");let n=e.body?.getReader(),o=[],s=0;if(n!==void 0)for(;;){let{done:a,value:u}=await n.read();if(a)break;if(s+=u.byteLength,s>t){try{await n.cancel()}catch{}throw new De("Request exceeds the byte limit")}o.push(u)}let i=new Uint8Array(s),c=0;for(let a of o)i.set(a,c),c+=a.byteLength;return i},ji=async e=>{let t;try{t=await Ou(e,x.requestBytes)}catch(r){throw r instanceof De?new ut("Asset query request exceeds the byte limit",{cause:r}):r}try{return xi.parse(JSON.parse(ae(t)))}catch(r){throw new ut("Asset query request is invalid",{cause:r})}};var Li=e=>{if(e instanceof be)return{code:"STALE_INDEX",message:e.message,retryable:!1,status:409};if(e instanceof K)return{code:"INVALID_REQUEST",message:e.message,retryable:!1,status:400};if(e instanceof D)return{code:e.code,message:e.message,retryable:!1,details:e.details,status:400}};var Cu="/$resources/assets",Mi=(e,t=200)=>new Response(JSON.stringify(e),{status:t,headers:{"content-type":"application/json; charset=utf-8"}}),Ne=({code:e,message:t,status:r,retryable:n=!1,details:o})=>Mi(bi({code:e,message:t,retryable:n,details:o}),r),Iu=(e,t,r)=>typeof e=="string"||e instanceof URL?new Request(new URL(e,t),r):new Request(e,r),Tu=async({deploymentId:e,artifact:t,request:r})=>{let n=await r.clone().text(),o=r.headers.get("cache-control"),s=await Ht(JSON.stringify([e,t.integrity.checksum,n,o])),i=new URL(r.url);return i.searchParams.set("ws-asset-resource",s),new Request(i,{method:"GET"})},Yd=({deploymentId:e,artifact:t,runtimeAssets:r,cache:n,baseUrl:o})=>(Qi({artifact:t,runtimeAssets:r}),Ui({deploymentId:e,artifact:t,runtimeAssets:r,cache:n,baseUrl:o,database:rr({artifact:t})})),Qi=({artifact:e,runtimeAssets:t})=>{let r=$i(e).find(n=>t[n]===void 0);if(r!==void 0)throw new Error(`Published referenced asset URL is unavailable for ${r}`)},Ui=({deploymentId:e,artifact:t,runtimeAssets:r,cache:n,baseUrl:o,database:s})=>{let i=new URL(o).origin;return async(c,a)=>{let u=Iu(c,o,a),f=new URL(u.url);if(f.origin!==i||f.pathname!==Cu||u.method.toUpperCase()!=="POST")return;let p;try{p=await ji(u.clone())}catch{return Ne({code:"INVALID_REQUEST",message:"Asset resource request is invalid",status:400})}let m=n===void 0||u.headers.has("cache-control")===!1?void 0:await Tu({deploymentId:e,artifact:t,request:u});if(m!==void 0&&n!==void 0){let d=await n.match(m).catch(()=>{});if(d!==void 0)return new Response(d.body,d)}try{if(u.signal.aborted)return Ne({code:"REQUEST_CANCELLED",message:"Published asset query was cancelled",status:499});let d=Mi(await s.query(p,void 0,r));return m!==void 0&&n!==void 0&&u.signal.aborted===!1&&(d.headers.set("cache-control",u.headers.get("cache-control")),await n.put(m,d.clone()).catch(()=>{})),d}catch(d){if(u.signal.aborted)return Ne({code:"REQUEST_CANCELLED",message:"Published asset query was cancelled",status:499});let y=Li(d);return Ne(y!==void 0?y:{code:"INTERNAL_ERROR",message:"Published asset query failed",status:500,retryable:!0})}}},Hd=({deploymentId:e,artifact:t,runtimeAssets:r})=>{let n=globalThis.caches,o,s=()=>(o??=n.open(`webstudio-assets-${e}`),o),i=n===void 0?void 0:{match:async a=>(await s()).match(a),put:async(a,u)=>(await s()).put(a,u)};Qi({artifact:t,runtimeAssets:r});let c=rr({artifact:t});return async({request:a,fallback:u})=>{let f=new URL(a.url).origin,p=Ui({deploymentId:e,artifact:t,runtimeAssets:r,cache:i,baseUrl:f,database:c});return async(m,d)=>await p(m,d)??u(m,d)}};export{Hd as createGeneratedAssetResourceRuntime,Yd as createPublishedAssetResourceFetch};
diff --git a/packages/asset-uploader/src/asset-repository.test.ts b/packages/asset-uploader/src/asset-repository.test.ts
index eea29f0cbf..d7108c0225 100644
--- a/packages/asset-uploader/src/asset-repository.test.ts
+++ b/packages/asset-uploader/src/asset-repository.test.ts
@@ -1208,10 +1208,29 @@ describe("PostgresAssetRepository", () => {
properties: { title: "New post" },
},
};
+ const otherEntry = {
+ ...entry,
+ assetId: "asset-2",
+ revision: "revision-2",
+ document: {
+ ...entry.document,
+ _id: "asset-2",
+ name: "other.md",
+ path: "other.md",
+ key: "other.md",
+ revision: "revision-2",
+ contentRef: "other.md",
+ properties: { title: "Other post" },
+ },
+ };
dependencies.loadCanonicalAssetBaseEntries.mockResolvedValue([
{ ...entry, document: { ...entry.document, properties: {} } },
+ { ...otherEntry, document: { ...otherEntry.document, properties: {} } },
+ ]);
+ dependencies.loadCanonicalAssetFileEntries.mockResolvedValue([
+ entry,
+ otherEntry,
]);
- dependencies.loadCanonicalAssetFileEntries.mockResolvedValue([entry]);
dependencies.createAssetIndex.mockImplementation(createAssetIndex);
const repository = new PostgresAssetRepository({
projectId: "project-1",
@@ -1225,26 +1244,36 @@ describe("PostgresAssetRepository", () => {
data: new Blob(["post"]).stream(),
assetInfoFallback: undefined,
});
- const result = await repository.query({
- query: {
- where: {
- all: [
- {
- field: ["properties", "title"],
- operator: "eq",
- value: "New post",
- },
- ],
+ const result = await repository.query(
+ {
+ query: {
+ where: {
+ all: [
+ {
+ field: ["properties", "title"],
+ operator: "eq",
+ value: "New post",
+ },
+ ],
+ },
+ output: {
+ mode: "fields",
+ includeMetadata: false,
+ fields: [["id"], ["name"]],
+ },
},
- output: { mode: "base", includeMetadata: true },
},
- });
+ createCompilationPlan({
+ where: { all: [] },
+ output: { mode: "all", includeMetadata: true },
+ })
+ );
expect(dependencies.synchronizeCanonicalAssets).toHaveBeenCalledWith({
client: context.postgrest.client,
assetClient,
projectId: "project-1",
- assetIds: ["asset-1"],
+ assetIds: ["asset-1", "asset-2"],
requirements: { structuredProperties: true, excerpt: false },
});
expect(result.data.items).toEqual([
@@ -1254,11 +1283,25 @@ describe("PostgresAssetRepository", () => {
]);
expect(result.__diagnostics__).toMatchObject({
scope: "query-preview",
- includedDocumentCount: 1,
- omittedDocumentCount: 0,
- truncated: false,
+ query: {
+ includedDocumentCount: 1,
+ omittedDocumentCount: 0,
+ truncated: false,
+ },
+ database: {
+ includedDocumentCount: 2,
+ omittedDocumentCount: 0,
+ truncated: false,
+ },
});
+ expect(result.__diagnostics__.database.usedBytes).toBeGreaterThan(
+ result.__diagnostics__.query.usedBytes
+ );
expect(dependencies.loadAssetsByProjectWithClient).not.toHaveBeenCalled();
+ dependencies.loadCanonicalAssetBaseEntries.mockResolvedValue([
+ { ...entry, document: { ...entry.document, properties: {} } },
+ ]);
+ dependencies.loadCanonicalAssetFileEntries.mockResolvedValue([entry]);
const urlResult = await repository.query({
query: {
@@ -1298,8 +1341,8 @@ describe("PostgresAssetRepository", () => {
},
},
});
- expect(idOnlyResult.__diagnostics__.usedBytes).toBeLessThan(
- result.__diagnostics__.usedBytes
+ expect(idOnlyResult.__diagnostics__.query.usedBytes).toBeLessThan(
+ result.__diagnostics__.query.usedBytes
);
expect(dependencies.loadAssetsByProjectWithClient).not.toHaveBeenCalled();
diff --git a/packages/asset-uploader/src/asset-repository.ts b/packages/asset-uploader/src/asset-repository.ts
index f64b0a86cf..6b5adaf214 100644
--- a/packages/asset-uploader/src/asset-repository.ts
+++ b/packages/asset-uploader/src/asset-repository.ts
@@ -170,7 +170,10 @@ export interface AssetRepository {
): Promise<AssetFolder>;
deleteFolder(folderId: string): Promise<void>;
readFieldCatalog(): Promise<BuilderAssetFieldCatalog>;
- query(request: AssetQueryRequestInput): Promise<AssetQueryPreviewResult>;
+ query(
+ request: AssetQueryRequestInput,
+ databasePlan?: ContentCompilationPlan
+ ): Promise<AssetQueryPreviewResult>;
}
/**
@@ -709,7 +712,8 @@ export class PostgresAssetRepository implements AssetRepository {
}
async query(
- request: AssetQueryRequestInput
+ request: AssetQueryRequestInput,
+ databasePlan?: ContentCompilationPlan
): Promise<AssetQueryPreviewResult> {
await this.assertCanView();
const query = assetQuery.parse(request.query);
@@ -718,6 +722,12 @@ export class PostgresAssetRepository implements AssetRepository {
]);
const index = await this.prepareIndexAfterAuthorization(plan, false);
const database = getContentDatabaseForArtifact(index);
+ const publishedDatabase =
+ databasePlan === undefined
+ ? database
+ : getContentDatabaseForArtifact(
+ await this.prepareIndexAfterAuthorization(databasePlan, false)
+ );
const runtimeAssetIds = getContentArtifactRuntimeAssetIds({
artifact: index,
includeDocuments: plan !== undefined && requiresRuntimeDocumentData(plan),
@@ -742,24 +752,27 @@ export class PostgresAssetRepository implements AssetRepository {
this.assetStore.readFile,
runtimeAssets
);
- const {
+ const toCapacityStats = ({
+ usedBytes,
+ maxBytes,
+ unboundedBytes,
+ includedDocumentCount,
+ omittedDocumentCount,
+ truncated,
+ }: ReturnType<typeof database.getStats>) => ({
usedBytes,
maxBytes,
unboundedBytes,
includedDocumentCount,
omittedDocumentCount,
truncated,
- } = database.getStats();
+ });
return {
data,
__diagnostics__: {
scope: "query-preview",
- usedBytes,
- maxBytes,
- unboundedBytes,
- includedDocumentCount,
- omittedDocumentCount,
- truncated,
+ query: toCapacityStats(database.getStats()),
+ database: toCapacityStats(publishedDatabase.getStats()),
},
};
}
diff --git a/packages/asset-uploader/src/publication.test.ts b/packages/asset-uploader/src/publication.test.ts
new file mode 100644
index 0000000000..5a54e66d73
--- /dev/null
+++ b/packages/asset-uploader/src/publication.test.ts
@@ -0,0 +1,96 @@
+import { describe, expect, test, vi } from "vitest";
+import { preparePublishedAssetData } from "./publication";
+
+describe("published asset data", () => {
+ test("keeps authored fonts and content database runtime assets", async () => {
+ const artifact = {
+ documents: [{ _id: "post-document" }],
+ assetReferences: {
+ "post.md": [{ start: 0, end: 1, assetId: "inline-font" }],
+ },
+ } as never;
+ const assetData = {
+ assets: [
+ { id: "authored-font", type: "font" },
+ { id: "inline-font", type: "font" },
+ { id: "post-document", type: "font" },
+ { id: "unused-font", type: "font" },
+ { id: "image", type: "image" },
+ ],
+ assetFolders: [{ id: "folder" }],
+ } as never;
+ const prepareIndex = vi.fn().mockResolvedValue(artifact);
+ const loadAssetDataByProject = vi.fn().mockResolvedValue(assetData);
+ const dependencies = {
+ createRepository: vi.fn(() => ({ prepareIndex })),
+ loadAssetDataByProject,
+ };
+
+ const result = await preparePublishedAssetData(
+ {
+ projectId: "project-1",
+ context: {} as never,
+ assetStore: {} as never,
+ contentDatabaseMaxBytes: 512_000,
+ plan: { queries: [] } as never,
+ retainedAssetIds: ["authored-font"],
+ },
+ dependencies as never
+ );
+
+ expect(result).toEqual({
+ artifact,
+ assets: [
+ { id: "authored-font", type: "font" },
+ { id: "inline-font", type: "font" },
+ { id: "post-document", type: "font" },
+ { id: "image", type: "image" },
+ ],
+ assetFolders: [{ id: "folder" }],
+ });
+ expect(prepareIndex).toHaveBeenCalledWith({ queries: [] });
+ expect(loadAssetDataByProject).toHaveBeenCalledTimes(2);
+ });
+
+ test("retries publication preparation when assets change", async () => {
+ const artifact = {
+ documents: [],
+ assetReferences: {},
+ } as never;
+ const initialAssetData = {
+ assets: [],
+ assetFolders: [],
+ };
+ const changedAssetData = {
+ assets: [{ id: "image", type: "image" }],
+ assetFolders: [],
+ };
+ const prepareIndex = vi.fn().mockResolvedValue(artifact);
+ const loadAssetDataByProject = vi
+ .fn()
+ .mockResolvedValueOnce(initialAssetData)
+ .mockResolvedValueOnce(changedAssetData)
+ .mockResolvedValueOnce(changedAssetData)
+ .mockResolvedValueOnce(changedAssetData);
+
+ await expect(
+ preparePublishedAssetData(
+ {
+ projectId: "project-1",
+ context: {} as never,
+ assetStore: {} as never,
+ contentDatabaseMaxBytes: 512_000,
+ plan: { queries: [] } as never,
+ retainedAssetIds: [],
+ },
+ {
+ createRepository: vi.fn(() => ({ prepareIndex })),
+ loadAssetDataByProject,
+ } as never
+ )
+ ).resolves.toMatchObject({ assets: changedAssetData.assets });
+
+ expect(prepareIndex).toHaveBeenCalledTimes(2);
+ expect(loadAssetDataByProject).toHaveBeenCalledTimes(4);
+ });
+});
diff --git a/packages/asset-uploader/src/publication.ts b/packages/asset-uploader/src/publication.ts
new file mode 100644
index 0000000000..24b795a39d
--- /dev/null
+++ b/packages/asset-uploader/src/publication.ts
@@ -0,0 +1,75 @@
+import {
+ getContentArtifactRuntimeAssetIds,
+ type ContentCompilationPlan,
+} from "@webstudio-is/content-engine";
+import type { Asset } from "@webstudio-is/sdk";
+import type { AppContext } from "@webstudio-is/trpc-interface/index.server";
+import { PostgresAssetRepository } from "./asset-repository";
+import type { AssetObjectStore } from "./client";
+import { loadAssetDataByProject } from "./db";
+
+const defaultDependencies = {
+ createRepository: (
+ options: ConstructorParameters<typeof PostgresAssetRepository>[0]
+ ) => new PostgresAssetRepository(options),
+ loadAssetDataByProject,
+};
+
+export const preparePublishedAssetData = async (
+ {
+ projectId,
+ context,
+ assetStore,
+ contentDatabaseMaxBytes,
+ plan,
+ retainedAssetIds,
+ }: {
+ projectId: string;
+ context: AppContext;
+ assetStore: AssetObjectStore;
+ contentDatabaseMaxBytes: number;
+ plan: ContentCompilationPlan;
+ retainedAssetIds: Iterable<string>;
+ },
+ dependencies = defaultDependencies
+) => {
+ const repository = dependencies.createRepository({
+ projectId,
+ context,
+ assetStore,
+ contentDatabaseMaxBytes,
+ });
+ for (let attempt = 0; attempt < 2; attempt += 1) {
+ const assetDataBefore = await dependencies.loadAssetDataByProject(
+ projectId,
+ context
+ );
+ const artifact = await repository.prepareIndex(plan);
+ const assetDataAfter = await dependencies.loadAssetDataByProject(
+ projectId,
+ context
+ );
+ if (JSON.stringify(assetDataBefore) !== JSON.stringify(assetDataAfter)) {
+ if (attempt === 0) {
+ continue;
+ }
+ throw new Error("Assets changed while preparing publication; retry");
+ }
+
+ const runtimeAssetIds = new Set(retainedAssetIds);
+ for (const assetId of getContentArtifactRuntimeAssetIds({
+ artifact,
+ includeDocuments: true,
+ })) {
+ runtimeAssetIds.add(assetId);
+ }
+ return {
+ artifact,
+ assets: assetDataAfter.assets.filter(
+ (asset: Asset) => asset.type !== "font" || runtimeAssetIds.has(asset.id)
+ ),
+ assetFolders: assetDataAfter.assetFolders,
+ };
+ }
+ throw new Error("Asset index was not prepared");
+};
diff --git a/packages/asset-uploader/src/query-preview.ts b/packages/asset-uploader/src/query-preview.ts
index 0e5501a52c..4e07e20ae7 100644
--- a/packages/asset-uploader/src/query-preview.ts
+++ b/packages/asset-uploader/src/query-preview.ts
@@ -1,4 +1,7 @@
-import { type AssetQueryRequestInput } from "@webstudio-is/content-engine";
+import {
+ type AssetQueryRequestInput,
+ type ContentCompilationPlan,
+} from "@webstudio-is/content-engine";
import type { AssetObjectStore } from "./client";
import type { AppContext } from "@webstudio-is/trpc-interface/index.server";
import { PostgresAssetRepository } from "./asset-repository";
@@ -9,12 +12,14 @@ export const previewAssetResourceQuery = async ({
context,
assetClient,
contentDatabaseMaxBytes,
+ databasePlan,
}: {
projectId: string;
request: AssetQueryRequestInput;
context: AppContext;
assetClient: Pick<AssetObjectStore, "readFile">;
contentDatabaseMaxBytes?: number;
+ databasePlan?: ContentCompilationPlan;
}) => {
const repository = new PostgresAssetRepository({
projectId,
@@ -22,5 +27,5 @@ export const previewAssetResourceQuery = async ({
assetStore: assetClient,
contentDatabaseMaxBytes,
});
- return await repository.query(request);
+ return await repository.query(request, databasePlan);
};
diff --git a/packages/asset-uploader/src/server.ts b/packages/asset-uploader/src/server.ts
index af2637ba12..7fce448c56 100644
--- a/packages/asset-uploader/src/server.ts
+++ b/packages/asset-uploader/src/server.ts
@@ -11,6 +11,7 @@ export * from "./folder-persistence";
export * from "./revision";
export * from "./field-catalog";
export * from "./query-preview";
+export * from "./publication";
export * from "./clients/fs/fs";
export * from "./clients/s3/s3";
export { assetDataOverride } from "./utils/get-asset-data";
diff --git a/packages/cli/scripts/release-versioning.test.ts b/packages/cli/scripts/release-versioning.test.ts
new file mode 100644
index 0000000000..5d7f1eb8b2
--- /dev/null
+++ b/packages/cli/scripts/release-versioning.test.ts
@@ -0,0 +1,71 @@
+import { access, readdir, readFile } from "node:fs/promises";
+import { join, relative } from "node:path";
+import { fileURLToPath } from "node:url";
+import { expect, test } from "vitest";
+
+const workspaceRoot = fileURLToPath(new URL("../../..", import.meta.url));
+const releaseVersionPlaceholder = "0.0.0-webstudio-version";
+const dependencyGroups = [
+ "dependencies",
+ "devDependencies",
+ "optionalDependencies",
+ "peerDependencies",
+] as const;
+
+const listPackageFiles = async (parent: string) => {
+ const directories = await readdir(join(workspaceRoot, parent), {
+ withFileTypes: true,
+ });
+ const candidates = directories
+ .filter((entry) => entry.isDirectory())
+ .map((entry) => join(workspaceRoot, parent, entry.name, "package.json"));
+ return (
+ await Promise.all(
+ candidates.map(async (path) => {
+ try {
+ await access(path);
+ return path;
+ } catch {
+ return;
+ }
+ })
+ )
+ ).filter((path) => path !== undefined);
+};
+
+test("keeps release placeholders out of workspace dependency protocols", async () => {
+ const packageFiles = (
+ await Promise.all(
+ ["apps", "packages", "fixtures", "packages/cli/templates"].map(
+ listPackageFiles
+ )
+ )
+ ).flat();
+ const invalidDependencies: string[] = [];
+
+ for (const packageFile of packageFiles) {
+ const manifest = JSON.parse(await readFile(packageFile, "utf8")) as Record<
+ string,
+ unknown
+ >;
+ for (const group of dependencyGroups) {
+ const dependencies = manifest[group];
+ if (typeof dependencies !== "object" || dependencies === null) {
+ continue;
+ }
+ for (const [name, specifier] of Object.entries(dependencies)) {
+ if (
+ typeof specifier === "string" &&
+ specifier.startsWith("workspace:") &&
+ specifier.includes(releaseVersionPlaceholder)
+ ) {
+ invalidDependencies.push(
+ `${relative(workspaceRoot, packageFile)}: ${name}=${specifier}`
+ );
+ }
+ }
+ }
+ }
+
+ expect(invalidDependencies).toEqual([]);
+});
diff --git a/packages/cli/src/cli.test.ts b/packages/cli/src/cli.test.ts
index f5f7454098..5b272dc66f 100644
--- a/packages/cli/src/cli.test.ts
+++ b/packages/cli/src/cli.test.ts
@@ -168,6 +168,7 @@ describe("registerCommands", () => {
for (const command of [
"get-marketplace-product",
"update-marketplace-product",
+ "submit-marketplace-product",
"set-redirects",
]) {
expect(
@@ -180,6 +181,7 @@ describe("registerCommands", () => {
test.each([
"get-marketplace-product",
"update-marketplace-product",
+ "submit-marketplace-product",
"set-redirects",
])("shows registered top-level help for %s", async (command) => {
const output = await getHelpOutput([command, "--help"]);
diff --git a/packages/cli/src/commands/api-command-docs.test.ts b/packages/cli/src/commands/api-command-docs.test.ts
index f2c76cddea..6bb6617ad8 100644
--- a/packages/cli/src/commands/api-command-docs.test.ts
+++ b/packages/cli/src/commands/api-command-docs.test.ts
@@ -214,7 +214,9 @@ test("documents storage-efficient Assets queries for agents", () => {
expect(contents).toContain('output.mode:"fields"');
expect(contents).toContain("only fields");
expect(contents).toContain("includeMetadata:false");
- expect(contents).toContain("__diagnostics__.usedBytes");
+ expect(contents).toContain("__diagnostics__.query");
+ expect(contents).toContain("__diagnostics__.database");
+ expect(contents).toContain("must not be summed");
expect(contents).toContain("truncated");
}
});
diff --git a/packages/cli/src/commands/api-command-metadata.ts b/packages/cli/src/commands/api-command-metadata.ts
index 2a5032ad6b..1d72bc8a07 100644
--- a/packages/cli/src/commands/api-command-metadata.ts
+++ b/packages/cli/src/commands/api-command-metadata.ts
@@ -144,6 +144,8 @@ const apiCommandOptionsByCommand: Partial<
"get-marketplace-product": apiCommand.projectSettingsCommandOptions,
"update-marketplace-product":
apiCommand.updateMarketplaceProductCommandOptions,
+ "submit-marketplace-product":
+ apiCommand.submitMarketplaceProductCommandOptions,
"list-redirects": apiCommand.paginatedListCommandOptions,
"create-redirect": apiCommand.createRedirectCommandOptions,
"update-redirect": apiCommand.updateRedirectCommandOptions,
@@ -256,6 +258,10 @@ export const highLevelCliCommands = [
command: "update-marketplace-product",
operation: "update-marketplace-product",
},
+ {
+ command: "submit-marketplace-product",
+ operation: "submit-marketplace-product",
+ },
{ command: "set-redirects", operation: "set-redirects" },
{ command: "publish deploy", operation: "publish" },
{ command: "publish list", operation: "list-publishes" },
diff --git a/packages/cli/src/commands/api-command.test.ts b/packages/cli/src/commands/api-command.test.ts
index 5b2297b887..4fbd022478 100644
--- a/packages/cli/src/commands/api-command.test.ts
+++ b/packages/cli/src/commands/api-command.test.ts
@@ -984,6 +984,17 @@ test("updates marketplace product from input file", async () => {
});
});
+test("submits marketplace product for review", async () => {
+ await expectCommandCall({
+ options: {
+ command: "submit-marketplace-product",
+ confirm: true,
+ },
+ call: apiCalls.submitMarketplaceProduct,
+ connection: { acknowledgePublicSubmission: true },
+ });
+});
+
test("lists redirects with shared output detail options", async () => {
await expectCommandCall({
options: {
diff --git a/packages/cli/src/commands/api-command.ts b/packages/cli/src/commands/api-command.ts
index f73e5e8a4d..dacecbc81d 100644
--- a/packages/cli/src/commands/api-command.ts
+++ b/packages/cli/src/commands/api-command.ts
@@ -290,6 +290,14 @@ export const updateMarketplaceProductCommandOptions = (
"Required JSON file with marketplace product metadata."
);
+export const submitMarketplaceProductCommandOptions = (
+ yargs: CommonYargsArgv
+) =>
+ confirmOption(
+ apiCommandOptions(yargs),
+ "Required. Confirm submitting the marketplace product for public review"
+ );
+
export const createRedirectCommandOptions = (yargs: CommonYargsArgv) =>
apiCommandOptions(yargs)
.option("old", {
@@ -2098,6 +2106,13 @@ const apiCommandHandlers: Partial<Record<ApiCommandName, ApiCommandHandler>> = {
dependencies
);
},
+ "submit-marketplace-product": async (_options, connection, dependencies) =>
+ runProjectSessionCommand(
+ "submit-marketplace-product",
+ { acknowledgePublicSubmission: true },
+ connection,
+ dependencies
+ ),
"list-redirects": async (options, connection, dependencies) =>
runProjectSessionCommand(
"list-redirects",
diff --git a/packages/cli/src/commands/man.ts b/packages/cli/src/commands/man.ts
index b7ccc6276a..52eaaa774f 100644
--- a/packages/cli/src/commands/man.ts
+++ b/packages/cli/src/commands/man.ts
@@ -157,6 +157,7 @@ const taskRecipeUseCases = {
"Read project settings",
"Update project settings",
"Update marketplace product",
+ "Submit marketplace product",
"List redirects",
"Create redirect",
"Update redirect",
@@ -486,6 +487,7 @@ const apiCommandsByArea = {
[
"get-marketplace-product",
"update-marketplace-product",
+ "submit-marketplace-product",
"set-redirects",
].includes(cliCommand)
)
diff --git a/packages/cli/src/docs.generated.ts b/packages/cli/src/docs.generated.ts
index 0fffc57320..3c437f1be4 100644
--- a/packages/cli/src/docs.generated.ts
+++ b/packages/cli/src/docs.generated.ts
@@ -2,11 +2,11 @@
// 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## 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\n- webstudio schema mcp\n- webstudio man --json\n- webstudio man llm --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- webstudio mcp list-resources\n- webstudio mcp read-resource webstudio://project/guide\n- webstudio mcp read-resource webstudio://project/expressions\n\nNotes:\n\n- Use `webstudio schema mcp` for a compact machine-readable MCP tool overview. Add `--verbose` or use focused `meta.get_more_tools` calls only when exact input schemas are needed.\n- Use focused MCP tools for discovery first: `meta.index`, `meta.guide`, `meta.get_more_tools`, `components.list`, `components.summary`, `components.search`, `components.get`, `templates.list`, and `templates.get`. Protocol clients can use `resources/list` and `resources/read`; shell agents can use `webstudio mcp list-resources` and `webstudio mcp read-resource <uri>`. Read longer resources such as `webstudio://project/tools` and `webstudio://project/components` only when focused tools are insufficient.\n- `components.summary` returns counts by default; request `{"detail":"components","limit":20}` for paginated entries. Registry list tools return compact metadata, while `components.get` and `templates.get` return focused full details.\n- Read `webstudio://project/expressions` before authoring unfamiliar computed text, prop bindings, resource expressions, actions, or Collection item bindings.\n- From a shell, call one MCP tool with the shortcut form `webstudio <tool> \'<json>\'`, for example `webstudio components.summary`. The explicit equivalent is `webstudio mcp single-op-call <tool> \'<json>\'`. Use `--input-file` for large payloads.\n\n## Inspect external shadcn registry items\n\nCommands:\n\n- webstudio registry inspect --source https://example.com/r/registry.json --item button --json\n- webstudio registry inspect --source ./registry.json --item dialog --json\n- webstudio registry inspect --source https://example.com/r/button.json --json\n\nNotes:\n\n- Reads a local or remote registry item without installing files or changing the configured Webstudio project.\n- Returns the item name, description, package and registry dependencies, file paths/targets, available docs, and a read-only compatibility report.\n- The report explicitly says whether installation or editable-component conversion is supported, lists declared requirements and manual steps, and says when arbitrary source code was not analyzed.\n- This is an inspection step only. It does not install files or change the configured project.\n\n## Understand what MCP can do\n\nCommands:\n\n- webstudio man mcp\n- MCP tool: meta.index {}\n- MCP tool: meta.guide {"brief":"What can Webstudio MCP do?"}\n\nMCP lets agents work on one configured Webstudio project. Agents can:\n\n- Inspect the linked project, token permissions, and latest editable build.\n- Read selected project data for audits, migrations, and repair.\n- Search labels, text, props, resource URLs, asset metadata, and styles.\n- Audit accessibility, security, SEO, performance settings, unused assets, ineffective Collection styles, and unused or duplicate style data.\n- Create and edit pages, folders, redirects, breakpoints, and page templates.\n- Create pages from reusable templates.\n- Update page metadata, SEO fields, auth settings, and marketplace metadata.\n- Insert components and styled JSX sections.\n- Create data-driven lists, grids, cards, and similar repeated UI from array or object data in one Collection operation.\n- Move, copy, wrap, unwrap, convert, rename, retag, and delete elements.\n- Update text, rich text, props, bindings, and actions.\n- Create and update local styles, design tokens, style sources, and CSS variables.\n- Create static data variables and JSON variables.\n- Create HTTP, GraphQL, and system resources.\n- Use system resources for sitemap, current date, and assets.\n- Bind resources to rendered data or form/action props.\n- Manage nested asset folders and upload, inspect, move, duplicate, download, replace, delete, and inspect usage for assets.\n- Publish, unpublish, inspect publish jobs, and manage custom domains.\n- Start preview, capture screenshots, compare screenshot diffs, and use OCR when installed.\n\n## Inspect and refresh MCP session cache\n\nCommands:\n\n- MCP tool: status {}\n- MCP tool: status {"verbose":true}\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 status with `{"verbose":true}` only when debugging full namespaces, freshness, compatibility, or diagnostics.\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: preview.stop {}\n- MCP tool: screenshot {"path":"/","output":".webstudio/screenshots/home-current.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot {"path":"/pricing","output":".webstudio/screenshots/pricing-current.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot {"baseUrl":"http://127.0.0.1:5177","path":"/pricing","output":".webstudio/screenshots/pricing-current.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot.diff {"baselinePath":".webstudio/screenshots/home-before.png","currentPath":".webstudio/screenshots/home-current.png","outputDir":".webstudio/screenshots/diff"}\n- MCP tool: screenshot.diff {"baselinePath":".webstudio/screenshots/home-before.png","currentPath":".webstudio/screenshots/home-current.png","outputDir":".webstudio/screenshots/diff","expectedText":["Pricing","Start free"]}\n- MCP tool: screenshot.diff {"baselinePath":".webstudio/screenshots/home-before.png","currentPath":".webstudio/screenshots/home-current.png","outputDir":".webstudio/screenshots/diff","expectedVisual":{"maxMismatchPercentage":2,"maxChangedRegions":3,"dominantColorChange":{"channel":"luminance","direction":"increase","minMagnitude":10}}}\n- MCP tool: screenshot.diff {"baselinePath":".webstudio/screenshots/pricing-before.png","currentPath":".webstudio/screenshots/pricing-current.png","outputDir":".webstudio/screenshots/diff"}\n- MCP tool: vision.install-ocr {"confirm":true}\n\nNotes:\n\n- Use this after page/content/style mutations so a vision-capable AI can see the generated site from the current MCP session. Use `path`; never pass a Webstudio Builder/share URL or capture Builder chrome.\n- For multi-page work, capture every changed page by `path` through the same preview server; no click navigation is required.\n- Iterative mode is the default: after MCP mutations, path screenshots ensure generated project files are current, wait for the exact session version, and perform an ordinary page reload without Vite HMR. The preview server and browser stay alive. Use `{"mode":"production"}` only for release-like verification; rendered audit does this automatically.\n- Do not call `preview.start` through one-shot `webstudio mcp single-op-call`: it is long-lived. From a shell, use `webstudio mcp run` with preview.start, screenshot, and preview.stop in one shared process, or use a real long-running MCP client.\n- From one-shot shell calls or another process, pass `baseUrl` with `path` to capture an already-running preview/site without generating, building, starting, or restarting preview.\n- Use preview.stop only in the same long-running MCP server or `webstudio mcp run` process that started preview. A separate one-shot `single-op-call` process does not own another process\'s preview controller.\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- Preview installs generated app dependencies under `.webstudio/preview` and reuses them across regenerations.\n- Do not add generated-preview dependencies to the repository root `package.json` or `pnpm-lock.yaml`.\n- If dependency installation fails, check npm and network configuration, then reinstall or update the Webstudio CLI if the problem persists.\n- When a baseline exists, use screenshot.diff once per baseline/current page or viewport pair to get changed regions, OCR textAnalysis, and diff artifact paths before deciding whether the result matches. Pass expectedText for explicit pass/fail current-screen text assertions with found and missing text. Pass expectedVisual for pass/fail limits on pixel mismatch percentage, changed-region count, or the overall dominant color/brightness direction.\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 screenshot --path /pricing --output pricing.png` generates a temporary production preview, captures that route, and stops the server. For repeated captures, keep `webstudio preview` running and pass its absolute URL to `webstudio screenshot`.\n\n## List pages\n\nCommands:\n\n- MCP tool: list-pages {}\n- MCP tool: list-folders {}\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- MCP tool: create-page {"name":"Pricing","path":"/pricing","title":"Pricing","meta":{"description":"Plans for teams"}}\n\nNotes:\n\n- `name`, `path`, page `title`, and metadata text fields accept plain fixed values.\n- For computed page titles or metadata, send JavaScript expression code such as `pageTitle ?? "Pricing"`.\n\n## Update page settings/metadata\n\nCommands:\n\n- MCP tool: update-page {"pageId":"<pageId>","values":{"title":"Pricing","meta":{"description":"Plans","status":200}}}\n- MCP tool: update-page {"pageId":"<pageId>","values":{"meta":{"auth":{"method":"basic","login":"<login>","password":"<password>"}}}}\n\nNotes:\n\n- Page `title` and metadata text fields accept plain fixed values.\n- For computed page titles or metadata, send JavaScript expression code such as `pageTitle ?? "Pricing"`.\n- Page `status` accepts a fixed HTTP status code as a number from 200 through 599 or a JavaScript expression string for a dynamic status.\n\n## Read project settings\n\nCommands:\n\n- MCP tool: get-project-settings {}\n\nNotes:\n\n- Read `meta.agentInstructions` before making project changes. It contains the project\'s own guidance for AI agents.\n- Agent instructions are shared project guidance. Do not store credentials or other secrets there.\n\n## Update project settings\n\nCommands:\n\n- MCP tool: update-project-settings {"meta":{"siteName":"Acme"}}\n- MCP tool: update-project-settings {"meta":{"agentInstructions":"Use existing design tokens and keep product copy concise."}}\n\n## Read marketplace product\n\nCommands:\n\n- MCP tool: get-marketplace-product {}\n\n## Update marketplace product\n\nCommands:\n\n- MCP tool: update-marketplace-product {"category":"pageTemplates","name":"Acme Template","thumbnailAssetId":"asset-id","author":"Acme Studio","email":"[email protected]","website":"https://example.com","issues":"","description":"Reusable template project for Acme landing pages."}\n\n## List redirects\n\nCommands:\n\n- MCP tool: list-redirects {}\n\n## Create redirect\n\nCommands:\n\n- MCP tool: create-redirect {"old":"/old","new":"/new","status":301}\n\n## Update redirect\n\nCommands:\n\n- MCP tool: update-redirect {"old":"/old","values":{"new":"/newer","status":302}}\n- MCP tool: update-redirect {"old":"/old","values":{"status":null}}\n\n## Delete redirect\n\nCommands:\n\n- MCP tool: delete-redirect {"old":"/old"}\n\n## Set redirects\n\nCommands:\n\n- MCP tool: set-redirects {"redirects":[{"old":"/old","new":"/new","status":"301"}]}\n\n## List breakpoints\n\nCommands:\n\n- MCP tool: list-breakpoints {}\n\n## Create breakpoint\n\nCommands:\n\n- MCP tool: create-breakpoint {"label":"Tablet","maxWidth":991}\n\n## Update breakpoint\n\nCommands:\n\n- MCP tool: update-breakpoint {"breakpointId":"tablet","values":{"label":"Tablet","maxWidth":1023}}\n- MCP tool: update-breakpoint {"breakpointId":"tablet","values":{"condition":null,"minWidth":768}}\n- MCP tool: update-breakpoint {"breakpointId":"tablet","values":{"minWidth":null,"maxWidth":null,"condition":"(hover: hover)"}}\n\n## Delete breakpoint\n\nCommands:\n\n- MCP tool: delete-breakpoint {"breakpointId":"tablet"}\n\n## Duplicate page\n\nCommands:\n\n- MCP tool: duplicate-page {"pageId":"<pageId>","name":"Pricing Copy","path":"/pricing-copy"}\n- MCP tool: duplicate-page {"pageId":"<pageId>","name":"Paris","path":"/paris","substitutions":{"text":{"London":"Paris"},"variables":{"city":{"type":"string","value":"Paris"}}}}\n- webstudio duplicate-page --page <pageId> --name Paris --path /paris --substitutions \'{"text":{"London":"Paris"},"variables":{"city":{"type":"string","value":"Paris"}}}\' --json\n\nNotes:\n\n- Text substitutions replace exact fixed text only in the duplicated page\'s text children, string props, title, and metadata.\n- Variable substitutions are keyed by copied source-variable name and use typed variable values. The operation rejects missing or ambiguous names without committing a partial duplicate.\n- Existing expressions and cloned variable/resource references keep their remapped ids.\n\n## List page templates\n\nCommands:\n\n- MCP tool: list-page-templates {}\n\n## Create page template\n\nCommands:\n\n- MCP tool: create-page-template {"name":"Landing Template","title":"Landing"}\n\n## Update page template\n\nCommands:\n\n- MCP tool: update-page-template {"templateId":"<templateId>","values":{"name":"Article Template","meta":{"description":"Reusable article layout"}}}\n\n## Delete page template\n\nCommands:\n\n- MCP tool: delete-page-template {"templateId":"<templateId>"}\n\n## Duplicate page template\n\nCommands:\n\n- MCP tool: duplicate-page-template {"templateId":"<templateId>"}\n\n## Reorder page template\n\nCommands:\n\n- MCP tool: reorder-page-template {"sourceTemplateId":"<sourceTemplateId>","targetTemplateId":"<targetTemplateId>","position":"before"}\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 {}\n- MCP tool: list-pages {}\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>","values":{"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## Insert authored JSX or one component template\n\nCommands:\n\n- MCP tool: insert-fragment {"parentInstanceId":"<instanceId>","fragment":"<ws.element ws:tag=\\"section\\" ws:style={css`padding: 32px;`}><ws.element ws:tag=\\"h2\\">Product OS</ws.element><radix.Switch><radix.SwitchThumb /></radix.Switch></ws.element>"}\n- MCP tool: insert-component {"parentInstanceId":"<instanceId>","component":"@webstudio-is/sdk-components-react-radix:Switch"}\n- MCP tool: insert-component {"parentInstanceId":"<instanceId>","component":"Form"}\n\nNotes:\n\n- Use MCP `insert-fragment` as the default way to author styled component trees. It converts JSX to a structured fragment before mutation.\n- Use only exact component ids returned by `components.search`, `components.get`, or `templates.get`. Never derive or guess component ids.\n- The `ws:` namespace contains specific Webstudio core components; it is not HTML-tag shorthand. Use `<ws.element ws:tag="div">` for a native `div` and `<ws.element ws:tag="form">` for a native form, never `<ws.div>` or `<ws.form>`.\n- For Webstudio\'s complete form structure, discover the Form component and insert its automatic template with `insert-component` using component `"Form"`.\n- MCP receives JSX as a JSON string because MCP arguments are JSON. The CLI converts it locally before the runtime mutation, so the project session receives structured Webstudio data, not JSX source.\n- In `insert-fragment` JSX, use `ws:style={css\\`...\\`}`for Webstudio-native CSS, or use React-style object syntax such as`style={{ padding: 24 }}` when that is simpler. Both forms create editable Webstudio style data.\n- Do not access host globals or dynamic code APIs in JSX fragments, including `process`, `globalThis`, `eval`, `Function`, or `constructor`.\n- Use Webstudio prop names such as `class` and `for`; do not use React aliases `className` or `htmlFor`.\n- Use Webstudio actions for event/action props, for example `onClick={new ActionValue(["event"], expression\\`console.log(event)\\`)}`. Do not pass JavaScript functions such as `onClick={() => ...}`.\n- Plain prop values must be JSON-compatible: `null`, strings, booleans, finite numbers, arrays, and plain objects. Do not pass `undefined`, `Symbol`, `BigInt`, `NaN`, `Infinity`, `Date`, `Map`, `Set`, class instances, or circular objects; omit the prop, use plain data, or use `expression`/`ActionValue` when the value is dynamic.\n- Template-backed components used in JSX must include required child/part components explicitly under the same parent structure as the template, for example `<radix.Switch><radix.SwitchThumb /></radix.Switch>`.\n- Webstudio applies a registered template automatically when using `insert-component`, so composed components such as Switch include required child parts and styles.\n- Use `components.list`, `components.summary`, `components.search`, `components.get`, `templates.list`, and `templates.get` to discover known registry items, component ids, props, templates, insertability, and content model. Read `webstudio://project/components` only when those focused tools are insufficient.\n- Component/template registry items use a shadcn-compatible top-level shape plus Webstudio-specific superset metadata in `meta`. They are for Builder/MCP discovery, not a published shadcn install registry yet.\n- Known components with `contentModel.category: "none"` are not standalone-insertable; insert their root component template instead so required providers/parents are included.\n- Unknown custom component ids are a low-level extension mechanism, not a discovery fallback. Agents must not synthesize them.\n\n## Make a region editable in Content mode\n\nCommands:\n\n- MCP tool: insert-component {"parentInstanceId":"<instanceId>","component":"ws:block"}\n- MCP tool: inspect-instance {"instanceId":"<instanceId>","include":["children"]}\n\nNotes:\n\n- When a page will be handed to a Content-mode editor, wrap every region they should be able to edit in a Content Block (`ws:block`). Content-mode editors can edit text and supported props only in Content Block descendants. Content outside those blocks remains read-only, even when it looks like ordinary editable text.\n- Put reusable insertable options inside the Content Block\'s `ws:block-template` child. A template is source material, not editor content: editors cannot edit or delete it directly. When an editor inserts a template, its copy becomes a direct child of the Content Block and is editable.\n- Before handing off a page, verify with `inspect-instance` that the intended text, images, and links are inside a Content Block, and that templates include all required styling because Content-mode editors cannot use the Style panel.\n\n## Move elements\n\nCommands:\n\n- MCP tool: move-instance {"moves":"moves.json contents"}\n\nNotes:\n\n- Use `position: "end"` to append an instance. Repeating this for A and then B preserves the final order A, B.\n- A numeric `insertIndex` addresses the target parent\'s children before the moved instance is removed. Use it for exact placement; do not calculate the last index to append.\n- Moves in one `moves` array are applied sequentially in array order.\n\n## Clone element subtree\n\nCommands:\n\n- MCP tool: clone-instance {"sourceInstanceId":"<instanceId>","targetParentInstanceId":"<targetParentId>"}\n\n## Delete element subtree\n\nCommands:\n\n- MCP tool: delete-instance {"instanceIds":["<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## Replace bounded literal text\n\nCommands:\n\n- MCP tool: replace-text {"find":"Start free","replace":"Get started","match":"exact","pagePath":"/pricing","limit":20}\n\nNotes:\n\n- This changes only literal text children, never expression children. Scope it to pagePath or pageId and set a limit before a broad replacement.\n\n## Replace bounded static prop text\n\nCommands:\n\n- MCP tool: replace-prop-text {"find":"old.example.com","replace":"www.example.com","match":"substring","names":["href","code"],"limit":20}\n\nNotes:\n\n- This changes only static string props such as href, alt, aria-label, title, and HTML embed code. It never changes expressions, resources, actions, assets, or other dynamic bindings. Use names or instanceIds and a limit to narrow the change.\n\n## Replace bounded resource text\n\nCommands:\n\n- MCP tool: replace-resource-text {"find":"api.old.example.com","replace":"api.example.com","fields":["url"],"limit":20}\n\nNotes:\n\n- This changes resource names and fixed URL literals only. It skips dynamic URL expressions, headers, search parameters, request bodies, and GraphQL query code.\n\n## Update props\n\nCommands:\n\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: replace-prop-text {"find":"Old label","replace":"New label","names":["aria-label","title"],"limit":20}\n\nNotes:\n\n- Use this for fixed prop values such as `aria-label`, `alt`, `id`, static `href`, and other direct string/number/boolean/json prop values.\n\n## Add JSON-LD structured data\n\nCommands:\n\n- MCP tool: components.get {"component":"JsonLd"}\n- MCP tool: insert-component {"parentInstanceId":"<headSlotInstanceId>","component":"JsonLd"}\n- MCP tool: update-props {"updates":[{"instanceId":"<jsonLdInstanceId>","name":"code","type":"string","value":"{\\"@context\\":\\"https://schema.org\\",\\"@type\\":\\"Organization\\",\\"name\\":\\"Acme\\"}"}]}\n- MCP tool: audit {"scopes":["seo"],"pagePath":"/"}\n\nNotes:\n\n- Prefer placing `JsonLd` inside `HeadSlot`.\n- Store `code` as a JSON object or array encoded as a compact string. The Builder formats it for editing.\n- The semantic prop update rejects malformed JSON and structurally invalid fixed JSON-LD with a precise JSON path.\n- The SEO audit also warns about a missing top-level `@context`, unknown or superseded Schema.org terms, properties unsupported by the supplied type, and incompatible primitive value types.\n- Schema.org vocabulary findings are warnings because custom vocabularies and extensions remain valid. Dynamic JSON-LD is marked as skipped for rendered validation.\n- Do not use bindings just to set static text.\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\nNotes:\n\n- Use this only when the prop should remain dynamic: expression, resource, action, or an existing scoped runtime context value such as `system`.\n- For a fixed string value, use `update-props` with `type:"string"` and a direct `value` instead.\n\n## Read styles\n\nCommands:\n\n- MCP tool: get-styles {"instanceIds":["<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 {"property":"color","fromValue":{"type":"keyword","value":"red"},"toValue":{"type":"keyword","value":"blue"}}\n\n## List design tokens\n\nCommands:\n\n- MCP tool: list-design-tokens {}\n- MCP tool: list-design-tokens {"withUsage":true}\n- MCP tool: list-design-tokens {"verbose":true}\n\nNotes:\n\n- The default response is compact and includes token id, name, declaration count, and optional usage count.\n- Use `verbose:true` only when you need the full inline style declarations.\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 {"designTokenId":"<tokenId>","updates":"styles.json contents"}\n\n## Delete design token styles\n\nCommands:\n\n- MCP tool: delete-design-token-styles {"designTokenId":"<tokenId>","deletions":"styles.json contents"}\n\n## Attach design token to instances\n\nCommands:\n\n- MCP tool: attach-design-token {"designTokenId":"<tokenId>","instanceIds":"instances.json contents"}\n\n## Detach design token from instances\n\nCommands:\n\n- MCP tool: detach-design-token {"designTokenId":"<tokenId>","instanceIds":"instances.json contents"}\n\n## Extract design token from local styles\n\nCommands:\n\n- MCP tool: extract-design-token {"instanceIds":["<instanceId>"],"name":"Brand Primary","removeLocalProps":["color"]}\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 {"vars":"vars.json contents"}\n\n## Delete CSS variables\n\nCommands:\n\n- MCP tool: delete-css-variable {"names":"names.json contents","force":true}\n\n## Rewrite CSS variable references\n\nCommands:\n\n- MCP tool: rewrite-css-variable-refs {"map":"variables.json contents"}\n\n## List data variables\n\nCommands:\n\n- MCP tool: list-variables {}\n- MCP tool: list-variables {"scopeInstanceId":"<instanceId>"}\n\nNotes:\n\n- Data variables live in the internal `dataSources` namespace.\n- For raw `snapshot`, request the public `variables` namespace rather than the internal `dataSources` name. Raw patch payloads still use `dataSources` when applying direct changes.\n- Scope variables to the instance where they should become available. Descendants can use them in expressions, and nested variables with the same name mask outer variables.\n\n## Create data variable\n\nCommands:\n\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"title","value":{"type":"string","value":"Hello"}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"count","value":{"type":"number","value":3}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"featured","value":{"type":"boolean","value":true}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"tags","value":{"type":"json","value":["news","product"]}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"filters","value":{"type":"json","value":{"tag":"news"}}}\n\nNotes:\n\n- Data variable values support `string`, `number`, `boolean`, and `json`. Use `json` for all arrays and objects.\n- Parameters are internal scoped runtime values provided by pages, collections, or components. They are not a public authoring surface: do not create, update, or delete parameter records. Use data variables/resources for user-authored data, and reference documented context values such as `system` only where they are already in scope.\n\n## Update data variable\n\nCommands:\n\n- MCP tool: update-variable {"dataSourceId":"<variableId>","values":{"value":{"type":"json","value":{"count":1}}}}\n\n## Delete data variable\n\nCommands:\n\n- MCP tool: delete-variable {"dataSourceId":"<variableId>"}\n\n## List resources\n\nCommands:\n\n- MCP tool: list-resources {}\n- MCP tool: list-resources {"scopeInstanceId":"<instanceId>"}\n\n## Create resource\n\nCommands:\n\n- MCP tool: create-resource {"resource":{"name":"Posts","method":"get","url":"https://api.example.com/posts","headers":[]}}\n- MCP tool: create-resource {"resource":{"name":"Posts","method":"get","url":"\\"https://api.example.com/posts?tag=\\" + filters.tag","headers":[]},"scopeInstanceId":"<instanceId>","dataSourceName":"posts"}\n- MCP tool: create-resource {"resource":{"name":"Filtered Posts","method":"get","url":"https://api.example.com/posts","searchParams":[{"name":"tag","value":"filters.tag"},{"name":"source","value":{"type":"literal","value":"website"}}],"headers":[{"name":"Authorization","value":"\\"Bearer \\" + auth.token"}]},"scopeInstanceId":"<instanceId>","dataSourceName":"posts"}\n- MCP tool: create-resource {"resource":{"name":"Post GraphQL","control":"graphql","method":"post","url":"https://api.example.com/graphql","headers":[{"name":"Content-Type","value":{"type":"literal","value":"application/json"}}],"body":"{ query: \\"query Post($slug: String!) { post(slug: $slug) { title } }\\", variables: { slug: system.params.slug } }"},"scopeInstanceId":"<instanceId>","dataSourceName":"post"}\n- MCP tool: create-resource {"resource":{"name":"Current Date","control":"system","method":"get","url":"/$resources/current-date","headers":[]},"scopeInstanceId":"<instanceId>","dataSourceName":"currentDate"}\n\nNotes:\n\n- Resource `url` accepts plain fixed URLs and paths such as `https://api.example.com/posts` and `/$resources/current-date`.\n- Resource `url` can also be a JavaScript expression when it is computed, such as `"https://api.example.com/posts?tag=" + filters.tag`.\n- Header values, search parameter values, and body accept expressions for dynamic values. For fixed text, use `{"type":"literal","value":"application/json"}`; Webstudio stores the required string expression for you.\n- Search parameter values, header values, and body expressions can read scoped variables and documented runtime context values such as `system` when they are available at the resource scope.\n- Add `scopeInstanceId` and `dataSourceName` when the resource result should be exposed as a scoped read data variable. Scoped resources are generated into the page resource `data` map and may be loaded during page rendering. Use this for read-oriented resources such as GET CMS/API data.\n- For submit/write/action resources, create the resource without `scopeInstanceId`, then bind a component prop such as a Form `action` with `bind-props` and `binding.type: "resource"`. Prop-bound resources are generated into the page resource `action` map instead of the read `data` map. Use this for POST, PUT, DELETE, webhooks, GraphQL submissions, and other explicit action flows.\n- Resource `method` can be `get`, `post`, `put`, or `delete`. Use GET for read data, POST for creates/GraphQL/webhooks/form submissions, PUT for full updates or replacements, and DELETE for deletion actions.\n- Optional `control` values are `graphql` and `system`. Use `graphql` for GraphQL-style requests, usually POST with a query body. Use `system` for built-in resources such as `"/$resources/sitemap.xml"`, `"/$resources/current-date"`, and `"/$resources/assets"` and when the resource should use the built-in `system` parameter. System fields are `system.origin`, `system.pathname`, `system.params`, and `system.search`.\n\n## Update resource\n\nCommands:\n\n- MCP tool: update-resource {"resourceId":"<resourceId>","values":{"url":"https://api.example.com/posts"}}\n- MCP tool: replace-resource-text {"find":"api.old.example.com","replace":"api.example.com","fields":["url"],"limit":20}\n\n## Query Markdown assets\n\nCommands:\n\n- MCP tool: get-asset-field-catalog {}\n- MCP tool: validate-asset-query {"query":{"where":{"all":[{"field":["extension"],"operator":"eq","value":"md"},{"field":["properties","draft"],"operator":"ne","value":true}]},"limit":20}}\n- MCP tool: create-assets-resource {"name":"All assets","scopeInstanceId":"<instanceId>","dataSourceName":"assets"}\n- MCP tool: create-assets-resource {"name":"Published posts","scopeInstanceId":"<instanceId>","dataSourceName":"posts","query":{"where":{"all":[{"field":["extension"],"operator":"eq","value":{"type":"literal","value":"md"}},{"field":["properties","draft"],"operator":"ne","value":{"type":"literal","value":true}}]},"sort":[{"field":["properties","publishedAt"],"direction":"desc"}],"limit":{"type":"literal","value":20},"output":{"mode":"fields","includeMetadata":false,"fields":[["properties","title"],["properties","slug"],["properties","publishedAt"],["excerpt"]]},"content":{"mode":"none"}}}\n- MCP tool: create-assets-resource {"name":"Post by slug or ID","scopeInstanceId":"<instanceId>","dataSourceName":"post","query":{"where":{"any":[{"field":["properties","slug"],"operator":"eq","value":"system.params.slug"},{"field":["id"],"operator":"eq","value":"system.params.slug"}]},"limit":{"type":"literal","value":1},"output":{"mode":"fields","includeMetadata":false,"fields":[["properties","title"],["properties","publishedAt"]]},"content":{"mode":"markdown-body","maxBytes":1048576}}}\n- MCP tool: list-assets-resources {}\n- MCP tool: get-assets-resource {"resourceId":"<resourceId>"}\n- MCP tool: update-assets-resource {"resourceId":"<resourceId>","values":{"query":null}}\n- MCP tool: preview-asset-query {"query":{"where":{"all":[{"field":["properties","slug"],"operator":"eq","value":"hello-world"}]},"limit":1,"content":{"mode":"markdown-body","maxBytes":1048576}}}\n\nNotes:\n\n- Read the field catalog before authoring unfamiliar queries. It includes dynamic schema-less frontmatter paths such as `properties.author.name`, observed types, optionality, and mixed-type state without downloading Markdown files.\n- Minimize the deployed content database by using `output.mode:"fields"` and selecting only fields the rendered page needs. Keep `includeMetadata:false` unless the rendered value needs file metadata such as name, path, MIME type, or creation date, and avoid `output.mode:"all"` as a convenience default. Query diagnostics are returned separately and do not require metadata output. Filters and sorting may still require their referenced fields in the database.\n- Combine filters with `where.all` (AND) and `where.any` (OR), including nested groups. Filter values, limit, and offset on a saved resource may be Webstudio expressions evaluated at render time. Preview queries use concrete JSON values.\n- Use `content.mode:"none"` for listings. Request `markdown-body`, `full`, or a bounded `range` only after filtering to the intended files, normally with `limit:1` for a slug detail route.\n- In Markdown, reference sibling Assets with conventional relative URLs such as `../images/hero.png`. When `markdown-body` is requested, the content engine resolves matching files against the Markdown file\'s folder and emits the correct Builder or published Asset URL. Keep external URLs absolute.\n- Markdown Embed renders sanitized authored HTML for figures, captions, audio, video, and iframes. Scripts, inline event handlers, `srcdoc`, and unsafe URL protocols are removed. Executable component composition remains separate future MDX work.\n- Preview each query with concrete values before saving it. Inspect `__diagnostics__.usedBytes`, `maxBytes`, `unboundedBytes`, and `truncated`; when usage approaches the limit, remove unused output fields, narrow candidate files, and reduce embedded content in that order.\n- Read Assets from the ID-keyed map at `<dataSourceName>.data`, with collection information such as `totalCount` and `hasMore` at `<dataSourceName>.meta`. Bind a listing Collection to `posts.data` and a one-result detail Collection to `post.data`. On each value, selected file fields such as `id`, `name`, and `extension` are top-level; Markdown frontmatter and JSON fields are under `properties`; the derived `excerpt` is top-level; and requested Markdown is at `content.text`.\n- Assets has one response shape and always executes a structured query. Omit `query` to use the default query, which selects URL and optional image dimensions. Provide query configuration to control filtering, sorting, pagination, selected fields, or file content. Set `values.query:null` to restore the default query.\n- `create-assets-resource` and `update-assets-resource` are the semantic authoring path. Do not construct the internal query URL, headers, or body expression manually.\n- The shared metadata index is maintained automatically and is emitted only when a configured Assets resource is reachable.\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- MCP tool: list-assets {"verbose":true}\n\nNotes:\n\n- Compact results include each asset\'s folder id. Use `verbose:true` to include complete records for a page of assets, or `get-asset` to read one complete record including description, folder, creation time, and image/font metadata.\n- Image asset descriptions are the default alt text for asset-backed Image components.\n- To generate missing descriptions, inspect the image in its rendered page or asset source, write a concise description of its purpose, and save it on the asset rather than duplicating it on each Image instance.\n\n## Get asset\n\nCommands:\n\n- MCP tool: get-asset {"assetId":"<assetId>"}\n\n## List asset folders\n\nCommands:\n\n- MCP tool: list-asset-folders {}\n\n## Create asset folder\n\nCommands:\n\n- MCP tool: create-asset-folder {"name":"Marketing"}\n- MCP tool: create-asset-folder {"name":"Photos","parentId":"<parentFolderId>"}\n\n## Update asset folder\n\nCommands:\n\n- MCP tool: update-asset-folder {"folderId":"<folderId>","values":{"name":"Brand"}}\n- MCP tool: update-asset-folder {"folderId":"<folderId>","values":{"parentId":"<parentFolderId>"}}\n- MCP tool: update-asset-folder {"folderId":"<folderId>","values":{"parentId":null}}\n\nNotes:\n\n- Updating `parentId` is the folder equivalent of cut and paste. Use `null` to move a folder to Root.\n\n## Duplicate asset folder\n\nCommands:\n\n- MCP tool: duplicate-asset-folder {"folderId":"<folderId>"}\n- MCP tool: duplicate-asset-folder {"folderId":"<folderId>","parentId":"<targetFolderId>"}\n\nNotes:\n\n- Duplication recursively copies descendant folders and assets. This is the folder equivalent of copy and paste.\n\n## Delete asset folder\n\nCommands:\n\n- MCP tool: delete-asset-folder {"folderId":"<folderId>"}\n\nNotes:\n\n- Deleting a folder recursively deletes its descendant folders and assets.\n\n## Update asset metadata\n\nCommands:\n\n- MCP tool: update-asset {"assetId":"<assetId>","values":{"description":"Team collaborating around a whiteboard"}}\n- MCP tool: update-asset {"assetId":"<fontAssetId>","values":{"meta":{"family":"Rajdhani","style":"normal","weight":600}}}\n\nNotes:\n\n- Use an empty description only when the image is intentionally decorative.\n- Updating an image asset description updates the default alt text wherever that asset is used with an asset-backed alt prop.\n- Font metadata updates merge with the detected metadata and are validated before committing; use this to correct a family, style, or weight after upload.\n\n## Generate missing image descriptions with an agent\n\nCommands:\n\n- MCP tool: audit {"scopes":["accessibility"],"verbose":true}\n- MCP tool: set-image-descriptions {"updates":[{"assetId":"hero-id","description":"Team collaborating around a whiteboard"},{"assetId":"texture-id","decorative":true}]}\n- MCP tool: audit {"scopes":["accessibility"]}\n\nNotes:\n\n- Start from `missing-image-description` findings. Inspect each image in its rendered page context before writing text.\n- The vision-capable agent generates the wording; the CLI validates and stores it but does not contain its own vision model.\n- Use `decorative:true` only when the image adds no information. This intentionally stores an empty description so later audits do not report it as missing.\n- Re-run the accessibility audit after the update. Asset-backed Image components use the saved asset description as their default alt text.\n\n## Manage fonts\n\nCommands:\n\n- MCP tool: list-fonts {"includeSystem":true}\n- MCP tool: list-assets {"type":"font"}\n- MCP tool: upload-asset {"asset":{"name":"acme-sans.woff2","type":"font","format":"woff2","meta":{"family":"Acme Sans","style":"normal","weight":400}},"assetsDir":".webstudio/assets"}\n- MCP tool: update-styles {"updates":"styles.json contents"}\n\nNotes:\n\n- Use `list-fonts` to discover uploaded families and system stacks. Upload/delete fonts through the existing asset tools, then apply a family with a `font-family` style declaration.\n\n## Upload one asset\n\nCommands:\n\n- MCP tool: upload-asset {"asset":{"name":"image.png","type":"image","format":"png","meta":{"width":1200,"height":630}},"assetsDir":".webstudio/assets"}\n- MCP tool: upload-asset {"asset":{"name":"image.png","type":"image","format":"png","folderId":"<folderId>","meta":{"width":1200,"height":630}},"assetsDir":".webstudio/assets"}\n\n## Upload asset batch\n\nCommands:\n\n- MCP tool: upload-assets {"assets":[{"name":"image.png","type":"image","format":"png","meta":{"width":1200,"height":630}}],"assetsDir":".webstudio/assets"}\n\n## Duplicate asset\n\nCommands:\n\n- MCP tool: duplicate-asset {"assetId":"<assetId>"}\n- MCP tool: duplicate-asset {"assetId":"<assetId>","folderId":"<targetFolderId>"}\n- MCP tool: duplicate-asset {"assetId":"<assetId>","folderId":null}\n\nNotes:\n\n- Duplication is the asset equivalent of copy and paste. Updating `folderId` is the equivalent of cut and paste; use `null` for Root.\n\n## Download asset\n\nCommands:\n\n- MCP tool: download-asset {"assetId":"<assetId>"}\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>"}\n\n## Delete assets\n\nCommands:\n\n- MCP tool: delete-asset {"assetIdsOrPrefixes":["<assetId>"],"force":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: get-marketplace-product {}\n- MCP tool: update-marketplace-product {"category":"pageTemplates","name":"Acme Template","thumbnailAssetId":"asset-id","author":"Acme Studio","email":"[email protected]","website":"https://example.com","issues":"","description":"Reusable template project for Acme landing pages."}\n\nPatch namespaces:\n\n- marketplaceProduct\n\n## Search and inspect safely\n\nCommands:\n\n- MCP tool: search-project {"query":"pricing"}\n- MCP tool: search-project {"query":"api.example.com","scopes":["resources"]}\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 `search-project` for query-driven lookup across labels, text, prop values, resource URLs, asset metadata, and styles. Use `audit` for project health findings.\n\n## Audit project quality\n\nCommands:\n\n- webstudio audit --json\n- webstudio audit --scopes accessibility --scopes seo --json\n- webstudio audit --page-path /pricing --json\n- webstudio audit --scopes accessibility --verbose --json\n- webstudio audit --rendered --page-path /pricing --json\n- webstudio audit --rendered --route-example post=/blog/hello --json\n- webstudio audit --rendered --image-domain images.example.com --json\n- MCP tool: audit {}\n- MCP tool: audit {"scopes":["accessibility","security"],"severities":["error","warning"]}\n- MCP tool: audit {"scopes":["accessibility"],"verbose":true}\n- MCP tool: audit {"scopes":["craft"],"verbose":true}\n- MCP tool: audit {"rendered":true,"verbose":true}\n\nNotes:\n\n- With no scopes, `audit` checks accessibility, security, SEO, performance settings, unused assets, ineffective Collection styles, non-GET resources exposed as render-time data, and unused or duplicate style data.\n- Craft is opt-in and read-only. Run `audit` with `scopes:["craft"]` to detect whether the project is not using Craft, partially compatible, or compatible with the versioned Craft 1.2 profile. `profileStatuses` includes the University-doc provenance and the smallest safe next action. The audit never installs Craft or changes a non-Craft project.\n- The `performance` scope reports disabled atomic CSS generation. A rendered audit also measures broken, eager below-fold, and oversized images, browser-marked render-blocking resources, and legacy font formats.\n- Rendered image and resource metrics run only when the selected scopes include `performance`; responsive layout dimensions remain available whenever `rendered:true` is requested.\n- Compact findings include stable ids, severity, message, and location. Use `--verbose` or `{"verbose":true}` for evidence, explanation, suggested remediation, skipped-check details, and manual-check workflows.\n- `summary` counts all findings before severity filtering and pagination.\n- `contractVersion` identifies the audit response contract. Handle a new value before assuming existing fields retain the same meaning.\n- Expression-, resource-, and parameter-backed values that cannot be checked reliably appear in `skippedChecks`; they are not treated as passing or failing.\n- Page filters apply to page-owned accessibility, security, and SEO checks. Asset and style usage remain project-wide to avoid false unused findings.\n- Continue paginated results with `cursor`. Restart the audit if the project version changes.\n- Verbose skipped-check and manual-check details are included on the first findings page only; their total counts remain available on every page.\n- `manualChecks` describes responsive, hierarchy, and contrast checks that require preview screenshots and vision.\n- Focused audits return only manual checks relevant to their selected scopes.\n- In a long-lived MCP session, `{"rendered":true}` reuses preview and screenshot\n tools to capture every static page at mobile, desktop, and Builder breakpoint\n edges. Compact output reports rendered check/issue/failure counts; verbose\n output includes screenshot paths and measured layout dimensions.\n- Dynamic route templates are skipped unless `--route-example <pageId>=<path>`\n (or MCP `routeExamples`) supplies a concrete path. The path must not contain\n unresolved `:` or `*` parameters.\n- Plans above 120 captures return a short-lived confirmation token. Review the\n unchanged plan, then rerun with `--confirm-large-run` and\n `--confirmation-token`.\n- Detailed rendered evidence is stored in a versioned manifest under\n `.webstudio/audits`; compact output includes its path and screenshot count.\n- Rendered checks also report broken images, eager images below the fold, and\n image sources more than 2x their rendered dimensions in both axes, including\n Webstudio instance ids and measured dimensions when available.\n- Rendered checks include sanitized Resource Timing evidence and report\n browser-marked render-blocking resources plus legacy `.ttf`, `.otf`, and\n `.woff` fonts without applying a universal transfer-size threshold.\n- Fix findings through semantic mutation commands, then rerun `audit` to confirm their deterministic finding ids disappeared.\n\n## Verify dynamic bindings\n\nCommands:\n\n- webstudio verify-bindings --json\n- MCP tool: verify-bindings {"pagePath":"/pricing"}\n- MCP tool: verify-bindings {"instanceId":"<instanceId>","limit":50}\n\nNotes:\n\n- Statically checks persisted text expressions, expression/action/resource/parameter props, resource expressions, and page metadata.\n- Findings distinguish invalid syntax, unknown or out-of-scope variables, stale internal data-source ids, and missing resource or parameter references.\n- Page and instance filters can be combined when the instance belongs to the selected page. Continue findings with `cursor`.\n- This operation does not resolve rendered values or execute external resources. Preview representative loading, empty, error, and populated states after static findings are fixed.\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: replace-text {"find":"Old headline","replace":"New headline","match":"exact","pagePath":"/pricing","limit":20}\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: update-page {"pageId":"<pageId>","values":{"title":"Pricing","meta":{"description":"Plans"}}}\n- MCP tool: update-resource {"resourceId":"<resourceId>","values":{"url":"https://api.example.com/posts"}}\n- MCP tool: replace-asset {"fromAssetId":"<oldAssetId>","toAssetId":"<newAssetId>"}\n- MCP tool: replace-styles {"property":"color","fromValue":{"type":"keyword","value":"red"},"toValue":{"type":"keyword","value":"blue"}}\n- MCP tool: rewrite-css-variable-refs {"map":"variables.json contents"}\n\nNotes:\n\n- Use focused reads first, then mutate only matching instances, props, metadata, resource URLs, assets, or style references. Use `replace-text` for bounded literal text changes, `replace-prop-text` for bounded static prop text, `replace-resource-text` for fixed resource names/URLs, and `update-text` for one known child or expressions.\n\n## Optimize existing project\n\nCommands:\n\n- MCP tool: list-pages {}\n- MCP tool: list-folders {}\n- MCP tool: update-page {"pageId":"<pageId>","values":{"title":"Pricing","meta":{"description":"Plans"}}}\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: list-breakpoints {}\n- MCP tool: update-breakpoint {"breakpointId":"tablet","values":{"maxWidth":1023}}\n- MCP tool: get-styles {"instanceIds":["<instanceId>"],"includeTokens":true}\n- MCP tool: update-styles {"updates":"styles.json contents"}\n- MCP tool: attach-design-token {"designTokenId":"<tokenId>","instanceIds":"instances.json contents"}\n- MCP tool: update-project-settings {"meta":{"siteName":"Acme"}}\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-variable {"scopeInstanceId":"<instanceId>","name":"tags","value":{"type":"json","value":["news","product"]}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"filters","value":{"type":"json","value":{"tag":"news"}}}\n- MCP tool: create-resource {"resource":{"name":"Posts","method":"get","url":"https://api.example.com/posts","searchParams":[{"name":"tag","value":"filters.tag"},{"name":"source","value":{"type":"literal","value":"website"}}],"headers":[]},"scopeInstanceId":"<instanceId>","dataSourceName":"posts"}\n- MCP tool: create-resource {"resource":{"name":"Post GraphQL","control":"graphql","method":"post","url":"https://api.example.com/graphql","headers":[{"name":"Content-Type","value":{"type":"literal","value":"application/json"}}],"body":"{ query: \\"query Post($slug: String!) { post(slug: $slug) { title } }\\", variables: { slug: system.params.slug } }"},"scopeInstanceId":"<instanceId>","dataSourceName":"post"}\n- MCP tool: create-resource {"resource":{"name":"Current Date","control":"system","method":"get","url":"/$resources/current-date","headers":[]},"scopeInstanceId":"<instanceId>","dataSourceName":"currentDate"}\n- MCP tool: update-resource {"resourceId":"<resourceId>","values":{"url":"https://api.example.com/posts"}}\n- MCP tool: bind-props {"bindings":"bindings.json contents"}\n- MCP tool: insert-fragment {"parentInstanceId":"<instanceId>","fragment":"<ws.collection>{/_ collection content _/}</ws.collection>"}\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- For read data, expose GET resources as scoped data variables with `scopeInstanceId`/`dataSourceName` and read the loaded result from the resource result wrapper, usually `.data`.\n- For writes, webhooks, GraphQL submissions, and deletes, prefer unscoped resources bound to Form `action` props so they become action resources instead of auto-loaded read resources.\n- Use direct props for fixed values and prop bindings only when a prop must read a data variable, resource, action, or documented runtime context value such as `system`.\n\n## Render an array or object as repeated content\n\nCommands:\n\n- MCP tool: insert-collection {"parentInstanceId":"<instanceId>","data":{"type":"expression","value":"posts.data.items"},"itemFragment":"<ws.element ws:tag=\\"article\\"><ws.element ws:tag=\\"h2\\">{expression`collectionItem.title`}</ws.element></ws.element>"}\n- MCP tool: inspect-instance {"instanceId":"<collectionId>","include":["props","bindings","children"]}\n\nNotes:\n\n- Use Collection whenever an array or object from a resource or data variable should render a list, grid, cards, table rows, options, tabs, or other repeated UI.\n- Pass `insert-collection` the complete array or object. Do not pass the resource response wrapper or one indexed item. External resource arrays are commonly nested under the scoped resource result\'s `data` field or deeper.\n- Pass one repeated-item Webstudio JSX root. The command creates the Collection, its private current-item/current-key parameters, the iterable binding, and descendant item bindings atomically.\n- Collection renders the item root once for every entry. Use `expression` values such as `collectionItem.title` in descendant text and props. Object iteration also exposes `collectionItemKey`.\n- Wrap multiple repeated sibling instances in one Element inside Collection.\n- For repeated Radix items such as accordion items, tabs, or menu options, bind a stable unique id or slug to every required `value` prop.\n- See the [Collection documentation](https://docs.webstudio.is/university/core-components/collection) for the equivalent Builder workflow.\n\n## Support dynamic runtime behavior\n\nCommands:\n\n- MCP tool: integrate-runtime-ui {"parentInstanceId":"<instanceId>","resources":[{"resource":{"name":"Seats","method":"get","url":"https://api.example.com/seats","headers":[]},"dataSourceName":"Seats","exposeAsDataSource":true}],"structure":{"type":"collection","data":{"type":"expression","value":"Seats.data"},"itemFragment":{"children":[{"type":"id","value":"seat"}],"instances":[{"type":"instance","id":"seat","component":"Text","children":[{"type":"expression","value":"collectionItem.label"}]}],"props":[],"dataSources":[],"resources":[],"styleSources":[],"styleSourceSelections":[],"styles":[],"breakpoints":[],"assets":[]}},"retainedBehavior":[{"instanceId":"<scriptInstanceId>","responsibility":"Seat selection behavior"}]}\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: bind-props {"bindings":"bindings.json contents"}\n- MCP tool: create-resource {"resource":{"name":"Seats","method":"get","url":"https://api.example.com/seats","headers":[]}}\n- MCP tool: snapshot {"include":["instances","props","resources"]}\n- MCP tool: apply-patch {"baseVersion":"<version>","transactions":"patch.json contents"}\n\nNotes:\n\n- Use `integrate-runtime-ui` to create variables/resources, insert one editable fragment or Collection, and add safe data bindings in one transaction.\n- List existing script-owned responsibilities under `retainedBehavior`. The operation preserves those instances and never evaluates or accepts replacement script bodies.\n- `unsupportedConversions` records behavior that cannot be represented safely. Dry-run returns the complete transaction and the same retained/unsupported report without changing the project.\n- New actions and HtmlEmbed scripts are intentionally rejected. Create normal editable components and data bindings; keep opaque runtime behavior in existing script instances.\n\n## Build authenticated pages\n\nCommands:\n\n- MCP tool: meta.guide {"brief":"Build a Supabase-authenticated account page"}\n- MCP tool: create-page {"name":"Account","path":"/account"}\n- MCP tool: update-page {"pageId":"<pageId>","values":{"meta":{"auth":{"method":"basic","login":"<login>","password":"<password>"}}}}\n- MCP tool: create-resource {"resource":{"name":"Session","method":"get","url":"https://api.example.com/session","headers":[]}}\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- Inspect and reuse the project\'s existing auth convention before authoring. Do\n not add a second provider or session model implicitly.\n- Model signed-out, loading, signed-in, and failed-auth states explicitly.\n- Never store credentials, service-role keys, refresh tokens, private session\n values, or authenticated response bodies in project data, command output,\n screenshots, agent instructions, or error reports. Privileged provider calls\n and authorization enforcement belong server-side.\n- Basic auth is semantic today. Provider-specific Supabase/Firebase setup still\n uses the existing resource, variable, prop, binding, and embed tools; there is\n no provider-specific installer.\n\n## Generate from design input\n\nCommands:\n\n- MCP tool: meta.guide {"brief":"Recreate this Figma design as a responsive page"}\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 {"vars":"vars.json contents"}\n- MCP tool: list-breakpoints {}\n- MCP tool: insert-fragment {"parentInstanceId":"<instanceId>","fragment":"<ws.element ws:tag=\\"section\\"><ws.element ws:tag=\\"p\\">Section copy</ws.element></ws.element>"}\n- MCP tool: update-styles {"updates":[{"instanceId":"<instanceId>","breakpointId":"<breakpointId-from-list-breakpoints>","property":"padding-left","value":{"type":"unit","unit":"px","value":24}}]}\n- MCP tool: preview.start {"host":"127.0.0.1","port":5173}\n- MCP tool: screenshot {"path":"/landing","output":"landing-desktop.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot {"path":"/landing","output":"landing-mobile.png","viewport":{"width":390,"height":844},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot {"baseUrl":"http://127.0.0.1:5177","path":"/landing","output":"landing-desktop.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n\nNotes:\n\n- Use this after the agent can inspect the supplied design. There is no direct\n Figma, screenshot, Inception, or `design.md` import command.\n- Inspect and reuse existing variables, tokens, styles, components, assets, and\n page patterns before authoring. Build semantic editable structure rather than\n flattening the design into an image or absolute-positioned approximation.\n- Verify one familiar viewport inside every distinct Builder breakpoint range,\n then run rendered audit and inspect the screenshots before completion.\n\n## Cross-project maintenance\n\nCommands:\n\n- webstudio mcp run .temp/projects.json\n- webstudio mcp run .temp/projects.json --dry-run\n- webstudio mcp run .temp/projects.json --approve-mutations --concurrency 2\n\nNotes:\n\n- Put shared `calls` and a `projects` array of independently linked project roots in the existing `mcp run` manifest. Project roots are relative to the manifest file.\n- Each project uses its own config, authentication, ProjectSession storage, checkpoint, and failure boundary. Confirmed successful calls are checkpointed. Reads can resume automatically; a mutation interrupted after dispatch is reported as ambiguous and is not replayed automatically, preventing silent duplicate writes.\n- Focus the manifest on bounded reads or audits first. Use per-call `dryRun`, global `--dry-run`, or explicitly approve committed mutations with `--approve-mutations` after reviewing the manifest.\n\n# Known CLI Gaps\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:\nCall `meta.guide` with the provider-authenticated page goal, then create the\npage, resources, variables, props, bindings, and embeds with existing semantic\ntools.\n\nSuggested commands:\n\n- setup-auth-page\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:\nCall `meta.guide` with the design-input goal, let the agent inspect the supplied\ndesign, then use semantic page, token, asset, fragment, style, preview,\nscreenshot, and audit tools. Use `apply-patch` only when no semantic operation\nfits.\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\n- webstudio schema mcp\n- webstudio man --json\n- webstudio man llm --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- webstudio mcp list-resources\n- webstudio mcp read-resource webstudio://project/guide\n- webstudio mcp read-resource webstudio://project/expressions\n\nNotes:\n\n- Use `webstudio schema mcp` for a compact machine-readable MCP tool overview. Add `--verbose` or use focused `meta.get_more_tools` calls only when exact input schemas are needed.\n- Use focused MCP tools for discovery first: `meta.index`, `meta.guide`, `meta.get_more_tools`, `components.list`, `components.summary`, `components.search`, `components.get`, `templates.list`, and `templates.get`. Protocol clients can use `resources/list` and `resources/read`; shell agents can use `webstudio mcp list-resources` and `webstudio mcp read-resource <uri>`. Read longer resources such as `webstudio://project/tools` and `webstudio://project/components` only when focused tools are insufficient.\n- `components.summary` returns counts by default; request `{"detail":"components","limit":20}` for paginated entries. Registry list tools return compact metadata, while `components.get` and `templates.get` return focused full details.\n- Read `webstudio://project/expressions` before authoring unfamiliar computed text, prop bindings, resource expressions, actions, or Collection item bindings.\n- From a shell, call one MCP tool with the shortcut form `webstudio <tool> \'<json>\'`, for example `webstudio components.summary`. The explicit equivalent is `webstudio mcp single-op-call <tool> \'<json>\'`. Use `--input-file` for large payloads.\n\n## Inspect external shadcn registry items\n\nCommands:\n\n- webstudio registry inspect --source https://example.com/r/registry.json --item button --json\n- webstudio registry inspect --source ./registry.json --item dialog --json\n- webstudio registry inspect --source https://example.com/r/button.json --json\n\nNotes:\n\n- Reads a local or remote registry item without installing files or changing the configured Webstudio project.\n- Returns the item name, description, package and registry dependencies, file paths/targets, available docs, and a read-only compatibility report.\n- The report explicitly says whether installation or editable-component conversion is supported, lists declared requirements and manual steps, and says when arbitrary source code was not analyzed.\n- This is an inspection step only. It does not install files or change the configured project.\n\n## Understand what MCP can do\n\nCommands:\n\n- webstudio man mcp\n- MCP tool: meta.index {}\n- MCP tool: meta.guide {"brief":"What can Webstudio MCP do?"}\n\nMCP lets agents work on one configured Webstudio project. Agents can:\n\n- Inspect the linked project, token permissions, and latest editable build.\n- Read selected project data for audits, migrations, and repair.\n- Search labels, text, props, resource URLs, asset metadata, and styles.\n- Audit accessibility, security, SEO, performance settings, unused assets, ineffective Collection styles, and unused or duplicate style data.\n- Create and edit pages, folders, redirects, breakpoints, and page templates.\n- Create pages from reusable templates.\n- Update page metadata, SEO fields, auth settings, and marketplace metadata.\n- Insert components and styled JSX sections.\n- Create data-driven lists, grids, cards, and similar repeated UI from array or object data in one Collection operation.\n- Move, copy, wrap, unwrap, convert, rename, retag, and delete elements.\n- Update text, rich text, props, bindings, and actions.\n- Create and update local styles, design tokens, style sources, and CSS variables.\n- Create static data variables and JSON variables.\n- Create HTTP, GraphQL, and system resources.\n- Use system resources for sitemap, current date, and assets.\n- Bind resources to rendered data or form/action props.\n- Manage nested asset folders and upload, inspect, move, duplicate, download, replace, delete, and inspect usage for assets.\n- Publish, unpublish, inspect publish jobs, and manage custom domains.\n- Start preview, capture screenshots, compare screenshot diffs, and use OCR when installed.\n\n## Inspect and refresh MCP session cache\n\nCommands:\n\n- MCP tool: status {}\n- MCP tool: status {"verbose":true}\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 status with `{"verbose":true}` only when debugging full namespaces, freshness, compatibility, or diagnostics.\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: preview.stop {}\n- MCP tool: screenshot {"path":"/","output":".webstudio/screenshots/home-current.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot {"path":"/pricing","output":".webstudio/screenshots/pricing-current.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot {"baseUrl":"http://127.0.0.1:5177","path":"/pricing","output":".webstudio/screenshots/pricing-current.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot.diff {"baselinePath":".webstudio/screenshots/home-before.png","currentPath":".webstudio/screenshots/home-current.png","outputDir":".webstudio/screenshots/diff"}\n- MCP tool: screenshot.diff {"baselinePath":".webstudio/screenshots/home-before.png","currentPath":".webstudio/screenshots/home-current.png","outputDir":".webstudio/screenshots/diff","expectedText":["Pricing","Start free"]}\n- MCP tool: screenshot.diff {"baselinePath":".webstudio/screenshots/home-before.png","currentPath":".webstudio/screenshots/home-current.png","outputDir":".webstudio/screenshots/diff","expectedVisual":{"maxMismatchPercentage":2,"maxChangedRegions":3,"dominantColorChange":{"channel":"luminance","direction":"increase","minMagnitude":10}}}\n- MCP tool: screenshot.diff {"baselinePath":".webstudio/screenshots/pricing-before.png","currentPath":".webstudio/screenshots/pricing-current.png","outputDir":".webstudio/screenshots/diff"}\n- MCP tool: vision.install-ocr {"confirm":true}\n\nNotes:\n\n- Use this after page/content/style mutations so a vision-capable AI can see the generated site from the current MCP session. Use `path`; never pass a Webstudio Builder/share URL or capture Builder chrome.\n- For multi-page work, capture every changed page by `path` through the same preview server; no click navigation is required.\n- Iterative mode is the default: after MCP mutations, path screenshots ensure generated project files are current, wait for the exact session version, and perform an ordinary page reload without Vite HMR. The preview server and browser stay alive. Use `{"mode":"production"}` only for release-like verification; rendered audit does this automatically.\n- Do not call `preview.start` through one-shot `webstudio mcp single-op-call`: it is long-lived. From a shell, use `webstudio mcp run` with preview.start, screenshot, and preview.stop in one shared process, or use a real long-running MCP client.\n- From one-shot shell calls or another process, pass `baseUrl` with `path` to capture an already-running preview/site without generating, building, starting, or restarting preview.\n- Use preview.stop only in the same long-running MCP server or `webstudio mcp run` process that started preview. A separate one-shot `single-op-call` process does not own another process\'s preview controller.\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- Preview installs generated app dependencies under `.webstudio/preview` and reuses them across regenerations.\n- Do not add generated-preview dependencies to the repository root `package.json` or `pnpm-lock.yaml`.\n- If dependency installation fails, check npm and network configuration, then reinstall or update the Webstudio CLI if the problem persists.\n- When a baseline exists, use screenshot.diff once per baseline/current page or viewport pair to get changed regions, OCR textAnalysis, and diff artifact paths before deciding whether the result matches. Pass expectedText for explicit pass/fail current-screen text assertions with found and missing text. Pass expectedVisual for pass/fail limits on pixel mismatch percentage, changed-region count, or the overall dominant color/brightness direction.\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 screenshot --path /pricing --output pricing.png` generates a temporary production preview, captures that route, and stops the server. For repeated captures, keep `webstudio preview` running and pass its absolute URL to `webstudio screenshot`.\n\n## List pages\n\nCommands:\n\n- MCP tool: list-pages {}\n- MCP tool: list-folders {}\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- MCP tool: create-page {"name":"Pricing","path":"/pricing","title":"Pricing","meta":{"description":"Plans for teams"}}\n\nNotes:\n\n- `name`, `path`, page `title`, and metadata text fields accept plain fixed values.\n- For computed page titles or metadata, send JavaScript expression code such as `pageTitle ?? "Pricing"`.\n\n## Update page settings/metadata\n\nCommands:\n\n- MCP tool: update-page {"pageId":"<pageId>","values":{"title":"Pricing","meta":{"description":"Plans","status":200}}}\n- MCP tool: update-page {"pageId":"<pageId>","values":{"meta":{"auth":{"method":"basic","login":"<login>","password":"<password>"}}}}\n\nNotes:\n\n- Page `title` and metadata text fields accept plain fixed values.\n- For computed page titles or metadata, send JavaScript expression code such as `pageTitle ?? "Pricing"`.\n- Page `status` accepts a fixed HTTP status code as a number from 200 through 599 or a JavaScript expression string for a dynamic status.\n\n## Read project settings\n\nCommands:\n\n- MCP tool: get-project-settings {}\n\nNotes:\n\n- Read `meta.agentInstructions` before making project changes. It contains the project\'s own guidance for AI agents.\n- Agent instructions are shared project guidance. Do not store credentials or other secrets there.\n\n## Update project settings\n\nCommands:\n\n- MCP tool: update-project-settings {"meta":{"siteName":"Acme"}}\n- MCP tool: update-project-settings {"meta":{"agentInstructions":"Use existing design tokens and keep product copy concise."}}\n\n## Read marketplace product\n\nCommands:\n\n- MCP tool: get-marketplace-product {}\n\n## Update marketplace product\n\nCommands:\n\n- MCP tool: update-marketplace-product {"category":"pageTemplates","name":"Acme Template","thumbnailAssetId":"asset-id","author":"Acme Studio","email":"[email protected]","website":"https://example.com","issues":"","description":"Reusable template project for Acme landing pages."}\n\n## Submit marketplace product\n\nCommands:\n\n- MCP tool: upload-asset {"asset":{"name":"marketplace-thumbnail.png","type":"image","format":"png","meta":{"width":1200,"height":630}},"assetsDir":".webstudio/assets"}\n- MCP tool: update-marketplace-product {"category":"pageTemplates","name":"Acme Template","thumbnailAssetId":"<uploadedAssetId>","author":"Acme Studio","email":"[email protected]","website":"https://example.com","issues":"","description":"Reusable template project for Acme landing pages."}\n- MCP tool: publish {"target":"production"}\n- MCP tool: submit-marketplace-product {"acknowledgePublicSubmission":true}\n\nNotes:\n\n- Wait for the production publish to complete before submitting the product for review.\n- Submission requires complete, valid marketplace metadata.\n\n## List redirects\n\nCommands:\n\n- MCP tool: list-redirects {}\n\n## Create redirect\n\nCommands:\n\n- MCP tool: create-redirect {"old":"/old","new":"/new","status":301}\n\n## Update redirect\n\nCommands:\n\n- MCP tool: update-redirect {"old":"/old","values":{"new":"/newer","status":302}}\n- MCP tool: update-redirect {"old":"/old","values":{"status":null}}\n\n## Delete redirect\n\nCommands:\n\n- MCP tool: delete-redirect {"old":"/old"}\n\n## Set redirects\n\nCommands:\n\n- MCP tool: set-redirects {"redirects":[{"old":"/old","new":"/new","status":"301"}]}\n\n## List breakpoints\n\nCommands:\n\n- MCP tool: list-breakpoints {}\n\n## Create breakpoint\n\nCommands:\n\n- MCP tool: create-breakpoint {"label":"Tablet","maxWidth":991}\n\n## Update breakpoint\n\nCommands:\n\n- MCP tool: update-breakpoint {"breakpointId":"tablet","values":{"label":"Tablet","maxWidth":1023}}\n- MCP tool: update-breakpoint {"breakpointId":"tablet","values":{"condition":null,"minWidth":768}}\n- MCP tool: update-breakpoint {"breakpointId":"tablet","values":{"minWidth":null,"maxWidth":null,"condition":"(hover: hover)"}}\n\n## Delete breakpoint\n\nCommands:\n\n- MCP tool: delete-breakpoint {"breakpointId":"tablet"}\n\n## Duplicate page\n\nCommands:\n\n- MCP tool: duplicate-page {"pageId":"<pageId>","name":"Pricing Copy","path":"/pricing-copy"}\n- MCP tool: duplicate-page {"pageId":"<pageId>","name":"Paris","path":"/paris","substitutions":{"text":{"London":"Paris"},"variables":{"city":{"type":"string","value":"Paris"}}}}\n- webstudio duplicate-page --page <pageId> --name Paris --path /paris --substitutions \'{"text":{"London":"Paris"},"variables":{"city":{"type":"string","value":"Paris"}}}\' --json\n\nNotes:\n\n- Text substitutions replace exact fixed text only in the duplicated page\'s text children, string props, title, and metadata.\n- Variable substitutions are keyed by copied source-variable name and use typed variable values. The operation rejects missing or ambiguous names without committing a partial duplicate.\n- Existing expressions and cloned variable/resource references keep their remapped ids.\n\n## List page templates\n\nCommands:\n\n- MCP tool: list-page-templates {}\n\n## Create page template\n\nCommands:\n\n- MCP tool: create-page-template {"name":"Landing Template","title":"Landing"}\n\n## Update page template\n\nCommands:\n\n- MCP tool: update-page-template {"templateId":"<templateId>","values":{"name":"Article Template","meta":{"description":"Reusable article layout"}}}\n\n## Delete page template\n\nCommands:\n\n- MCP tool: delete-page-template {"templateId":"<templateId>"}\n\n## Duplicate page template\n\nCommands:\n\n- MCP tool: duplicate-page-template {"templateId":"<templateId>"}\n\n## Reorder page template\n\nCommands:\n\n- MCP tool: reorder-page-template {"sourceTemplateId":"<sourceTemplateId>","targetTemplateId":"<targetTemplateId>","position":"before"}\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 {}\n- MCP tool: list-pages {}\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>","values":{"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## Insert authored JSX or one component template\n\nCommands:\n\n- MCP tool: insert-fragment {"parentInstanceId":"<instanceId>","fragment":"<ws.element ws:tag=\\"section\\" ws:style={css`padding: 32px;`}><ws.element ws:tag=\\"h2\\">Product OS</ws.element><radix.Switch><radix.SwitchThumb /></radix.Switch></ws.element>"}\n- MCP tool: insert-component {"parentInstanceId":"<instanceId>","component":"@webstudio-is/sdk-components-react-radix:Switch"}\n- MCP tool: insert-component {"parentInstanceId":"<instanceId>","component":"Form"}\n\nNotes:\n\n- Use MCP `insert-fragment` as the default way to author styled component trees. It converts JSX to a structured fragment before mutation.\n- Use only exact component ids returned by `components.search`, `components.get`, or `templates.get`. Never derive or guess component ids.\n- The `ws:` namespace contains specific Webstudio core components; it is not HTML-tag shorthand. Use `<ws.element ws:tag="div">` for a native `div` and `<ws.element ws:tag="form">` for a native form, never `<ws.div>` or `<ws.form>`.\n- For Webstudio\'s complete form structure, discover the Form component and insert its automatic template with `insert-component` using component `"Form"`.\n- MCP receives JSX as a JSON string because MCP arguments are JSON. The CLI converts it locally before the runtime mutation, so the project session receives structured Webstudio data, not JSX source.\n- In `insert-fragment` JSX, use `ws:style={css\\`...\\`}`for Webstudio-native CSS, or use React-style object syntax such as`style={{ padding: 24 }}` when that is simpler. Both forms create editable Webstudio style data.\n- Do not access host globals or dynamic code APIs in JSX fragments, including `process`, `globalThis`, `eval`, `Function`, or `constructor`.\n- Use Webstudio prop names such as `class` and `for`; do not use React aliases `className` or `htmlFor`.\n- Use Webstudio actions for event/action props, for example `onClick={new ActionValue(["event"], expression\\`console.log(event)\\`)}`. Do not pass JavaScript functions such as `onClick={() => ...}`.\n- Plain prop values must be JSON-compatible: `null`, strings, booleans, finite numbers, arrays, and plain objects. Do not pass `undefined`, `Symbol`, `BigInt`, `NaN`, `Infinity`, `Date`, `Map`, `Set`, class instances, or circular objects; omit the prop, use plain data, or use `expression`/`ActionValue` when the value is dynamic.\n- Template-backed components used in JSX must include required child/part components explicitly under the same parent structure as the template, for example `<radix.Switch><radix.SwitchThumb /></radix.Switch>`.\n- Webstudio applies a registered template automatically when using `insert-component`, so composed components such as Switch include required child parts and styles.\n- Use `components.list`, `components.summary`, `components.search`, `components.get`, `templates.list`, and `templates.get` to discover known registry items, component ids, props, templates, insertability, and content model. Read `webstudio://project/components` only when those focused tools are insufficient.\n- Component/template registry items use a shadcn-compatible top-level shape plus Webstudio-specific superset metadata in `meta`. They are for Builder/MCP discovery, not a published shadcn install registry yet.\n- Known components with `contentModel.category: "none"` are not standalone-insertable; insert their root component template instead so required providers/parents are included.\n- Unknown custom component ids are a low-level extension mechanism, not a discovery fallback. Agents must not synthesize them.\n\n## Make a region editable in Content mode\n\nCommands:\n\n- MCP tool: insert-component {"parentInstanceId":"<instanceId>","component":"ws:block"}\n- MCP tool: inspect-instance {"instanceId":"<instanceId>","include":["children"]}\n\nNotes:\n\n- When a page will be handed to a Content-mode editor, wrap every region they should be able to edit in a Content Block (`ws:block`). Content-mode editors can edit text and supported props only in Content Block descendants. Content outside those blocks remains read-only, even when it looks like ordinary editable text.\n- Put reusable insertable options inside the Content Block\'s `ws:block-template` child. A template is source material, not editor content: editors cannot edit or delete it directly. When an editor inserts a template, its copy becomes a direct child of the Content Block and is editable.\n- Before handing off a page, verify with `inspect-instance` that the intended text, images, and links are inside a Content Block, and that templates include all required styling because Content-mode editors cannot use the Style panel.\n\n## Move elements\n\nCommands:\n\n- MCP tool: move-instance {"moves":"moves.json contents"}\n\nNotes:\n\n- Use `position: "end"` to append an instance. Repeating this for A and then B preserves the final order A, B.\n- A numeric `insertIndex` addresses the target parent\'s children before the moved instance is removed. Use it for exact placement; do not calculate the last index to append.\n- Moves in one `moves` array are applied sequentially in array order.\n\n## Clone element subtree\n\nCommands:\n\n- MCP tool: clone-instance {"sourceInstanceId":"<instanceId>","targetParentInstanceId":"<targetParentId>"}\n\n## Delete element subtree\n\nCommands:\n\n- MCP tool: delete-instance {"instanceIds":["<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## Replace bounded literal text\n\nCommands:\n\n- MCP tool: replace-text {"find":"Start free","replace":"Get started","match":"exact","pagePath":"/pricing","limit":20}\n\nNotes:\n\n- This changes only literal text children, never expression children. Scope it to pagePath or pageId and set a limit before a broad replacement.\n\n## Replace bounded static prop text\n\nCommands:\n\n- MCP tool: replace-prop-text {"find":"old.example.com","replace":"www.example.com","match":"substring","names":["href","code"],"limit":20}\n\nNotes:\n\n- This changes only static string props such as href, alt, aria-label, title, and HTML embed code. It never changes expressions, resources, actions, assets, or other dynamic bindings. Use names or instanceIds and a limit to narrow the change.\n\n## Replace bounded resource text\n\nCommands:\n\n- MCP tool: replace-resource-text {"find":"api.old.example.com","replace":"api.example.com","fields":["url"],"limit":20}\n\nNotes:\n\n- This changes resource names and fixed URL literals only. It skips dynamic URL expressions, headers, search parameters, request bodies, and GraphQL query code.\n\n## Update props\n\nCommands:\n\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: replace-prop-text {"find":"Old label","replace":"New label","names":["aria-label","title"],"limit":20}\n\nNotes:\n\n- Use this for fixed prop values such as `aria-label`, `alt`, `id`, static `href`, and other direct string/number/boolean/json prop values.\n\n## Add JSON-LD structured data\n\nCommands:\n\n- MCP tool: components.get {"component":"JsonLd"}\n- MCP tool: insert-component {"parentInstanceId":"<headSlotInstanceId>","component":"JsonLd"}\n- MCP tool: update-props {"updates":[{"instanceId":"<jsonLdInstanceId>","name":"code","type":"string","value":"{\\"@context\\":\\"https://schema.org\\",\\"@type\\":\\"Organization\\",\\"name\\":\\"Acme\\"}"}]}\n- MCP tool: audit {"scopes":["seo"],"pagePath":"/"}\n\nNotes:\n\n- Prefer placing `JsonLd` inside `HeadSlot`.\n- Store `code` as a JSON object or array encoded as a compact string. The Builder formats it for editing.\n- The semantic prop update rejects malformed JSON and structurally invalid fixed JSON-LD with a precise JSON path.\n- The SEO audit also warns about a missing top-level `@context`, unknown or superseded Schema.org terms, properties unsupported by the supplied type, and incompatible primitive value types.\n- Schema.org vocabulary findings are warnings because custom vocabularies and extensions remain valid. Dynamic JSON-LD is marked as skipped for rendered validation.\n- Do not use bindings just to set static text.\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\nNotes:\n\n- Use this only when the prop should remain dynamic: expression, resource, action, or an existing scoped runtime context value such as `system`.\n- For a fixed string value, use `update-props` with `type:"string"` and a direct `value` instead.\n\n## Read styles\n\nCommands:\n\n- MCP tool: get-styles {"instanceIds":["<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 {"property":"color","fromValue":{"type":"keyword","value":"red"},"toValue":{"type":"keyword","value":"blue"}}\n\n## List design tokens\n\nCommands:\n\n- MCP tool: list-design-tokens {}\n- MCP tool: list-design-tokens {"withUsage":true}\n- MCP tool: list-design-tokens {"verbose":true}\n\nNotes:\n\n- The default response is compact and includes token id, name, declaration count, and optional usage count.\n- Use `verbose:true` only when you need the full inline style declarations.\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 {"designTokenId":"<tokenId>","updates":"styles.json contents"}\n\n## Delete design token styles\n\nCommands:\n\n- MCP tool: delete-design-token-styles {"designTokenId":"<tokenId>","deletions":"styles.json contents"}\n\n## Attach design token to instances\n\nCommands:\n\n- MCP tool: attach-design-token {"designTokenId":"<tokenId>","instanceIds":"instances.json contents"}\n\n## Detach design token from instances\n\nCommands:\n\n- MCP tool: detach-design-token {"designTokenId":"<tokenId>","instanceIds":"instances.json contents"}\n\n## Extract design token from local styles\n\nCommands:\n\n- MCP tool: extract-design-token {"instanceIds":["<instanceId>"],"name":"Brand Primary","removeLocalProps":["color"]}\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 {"vars":"vars.json contents"}\n\n## Delete CSS variables\n\nCommands:\n\n- MCP tool: delete-css-variable {"names":"names.json contents","force":true}\n\n## Rewrite CSS variable references\n\nCommands:\n\n- MCP tool: rewrite-css-variable-refs {"map":"variables.json contents"}\n\n## List data variables\n\nCommands:\n\n- MCP tool: list-variables {}\n- MCP tool: list-variables {"scopeInstanceId":"<instanceId>"}\n\nNotes:\n\n- Data variables live in the internal `dataSources` namespace.\n- For raw `snapshot`, request the public `variables` namespace rather than the internal `dataSources` name. Raw patch payloads still use `dataSources` when applying direct changes.\n- Scope variables to the instance where they should become available. Descendants can use them in expressions, and nested variables with the same name mask outer variables.\n\n## Create data variable\n\nCommands:\n\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"title","value":{"type":"string","value":"Hello"}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"count","value":{"type":"number","value":3}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"featured","value":{"type":"boolean","value":true}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"tags","value":{"type":"json","value":["news","product"]}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"filters","value":{"type":"json","value":{"tag":"news"}}}\n\nNotes:\n\n- Data variable values support `string`, `number`, `boolean`, and `json`. Use `json` for all arrays and objects.\n- Parameters are internal scoped runtime values provided by pages, collections, or components. They are not a public authoring surface: do not create, update, or delete parameter records. Use data variables/resources for user-authored data, and reference documented context values such as `system` only where they are already in scope.\n\n## Update data variable\n\nCommands:\n\n- MCP tool: update-variable {"dataSourceId":"<variableId>","values":{"value":{"type":"json","value":{"count":1}}}}\n\n## Delete data variable\n\nCommands:\n\n- MCP tool: delete-variable {"dataSourceId":"<variableId>"}\n\n## List resources\n\nCommands:\n\n- MCP tool: list-resources {}\n- MCP tool: list-resources {"scopeInstanceId":"<instanceId>"}\n\n## Create resource\n\nCommands:\n\n- MCP tool: create-resource {"resource":{"name":"Posts","method":"get","url":"https://api.example.com/posts","headers":[]}}\n- MCP tool: create-resource {"resource":{"name":"Posts","method":"get","url":"\\"https://api.example.com/posts?tag=\\" + filters.tag","headers":[]},"scopeInstanceId":"<instanceId>","dataSourceName":"posts"}\n- MCP tool: create-resource {"resource":{"name":"Filtered Posts","method":"get","url":"https://api.example.com/posts","searchParams":[{"name":"tag","value":"filters.tag"},{"name":"source","value":{"type":"literal","value":"website"}}],"headers":[{"name":"Authorization","value":"\\"Bearer \\" + auth.token"}]},"scopeInstanceId":"<instanceId>","dataSourceName":"posts"}\n- MCP tool: create-resource {"resource":{"name":"Post GraphQL","control":"graphql","method":"post","url":"https://api.example.com/graphql","headers":[{"name":"Content-Type","value":{"type":"literal","value":"application/json"}}],"body":"{ query: \\"query Post($slug: String!) { post(slug: $slug) { title } }\\", variables: { slug: system.params.slug } }"},"scopeInstanceId":"<instanceId>","dataSourceName":"post"}\n- MCP tool: create-resource {"resource":{"name":"Current Date","control":"system","method":"get","url":"/$resources/current-date","headers":[]},"scopeInstanceId":"<instanceId>","dataSourceName":"currentDate"}\n\nNotes:\n\n- Resource `url` accepts plain fixed URLs and paths such as `https://api.example.com/posts` and `/$resources/current-date`.\n- Resource `url` can also be a JavaScript expression when it is computed, such as `"https://api.example.com/posts?tag=" + filters.tag`.\n- Header values, search parameter values, and body accept expressions for dynamic values. For fixed text, use `{"type":"literal","value":"application/json"}`; Webstudio stores the required string expression for you.\n- Search parameter values, header values, and body expressions can read scoped variables and documented runtime context values such as `system` when they are available at the resource scope.\n- Add `scopeInstanceId` and `dataSourceName` when the resource result should be exposed as a scoped read data variable. Scoped resources are generated into the page resource `data` map and may be loaded during page rendering. Use this for read-oriented resources such as GET CMS/API data.\n- For submit/write/action resources, create the resource without `scopeInstanceId`, then bind a component prop such as a Form `action` with `bind-props` and `binding.type: "resource"`. Prop-bound resources are generated into the page resource `action` map instead of the read `data` map. Use this for POST, PUT, DELETE, webhooks, GraphQL submissions, and other explicit action flows.\n- Resource `method` can be `get`, `post`, `put`, or `delete`. Use GET for read data, POST for creates/GraphQL/webhooks/form submissions, PUT for full updates or replacements, and DELETE for deletion actions.\n- Optional `control` values are `graphql` and `system`. Use `graphql` for GraphQL-style requests, usually POST with a query body. Use `system` for built-in resources such as `"/$resources/sitemap.xml"`, `"/$resources/current-date"`, and `"/$resources/assets"` and when the resource should use the built-in `system` parameter. System fields are `system.origin`, `system.pathname`, `system.params`, and `system.search`.\n\n## Update resource\n\nCommands:\n\n- MCP tool: update-resource {"resourceId":"<resourceId>","values":{"url":"https://api.example.com/posts"}}\n- MCP tool: replace-resource-text {"find":"api.old.example.com","replace":"api.example.com","fields":["url"],"limit":20}\n\n## Query Markdown assets\n\nCommands:\n\n- MCP tool: get-asset-field-catalog {}\n- MCP tool: validate-asset-query {"query":{"where":{"all":[{"field":["extension"],"operator":"eq","value":"md"},{"field":["properties","draft"],"operator":"ne","value":true}]},"limit":20}}\n- MCP tool: create-assets-resource {"name":"All assets","scopeInstanceId":"<instanceId>","dataSourceName":"assets"}\n- MCP tool: create-assets-resource {"name":"Published posts","scopeInstanceId":"<instanceId>","dataSourceName":"posts","query":{"where":{"all":[{"field":["extension"],"operator":"eq","value":{"type":"literal","value":"md"}},{"field":["properties","draft"],"operator":"ne","value":{"type":"literal","value":true}}]},"sort":[{"field":["properties","publishedAt"],"direction":"desc"}],"limit":{"type":"literal","value":20},"output":{"mode":"fields","includeMetadata":false,"fields":[["properties","title"],["properties","slug"],["properties","publishedAt"],["excerpt"]]},"content":{"mode":"none"}}}\n- MCP tool: create-assets-resource {"name":"Post by slug or ID","scopeInstanceId":"<instanceId>","dataSourceName":"post","query":{"where":{"all":[{"field":["extension"],"operator":"eq","value":{"type":"literal","value":"md"}},{"any":[{"field":["properties","slug"],"operator":"eq","value":"system.params.slug"},{"field":["id"],"operator":"eq","value":"system.params.slug"}]}]},"limit":{"type":"literal","value":1},"output":{"mode":"fields","includeMetadata":false,"fields":[["properties","title"],["properties","publishedAt"]]},"content":{"mode":"markdown-body","maxBytes":1048576}}}\n- MCP tool: list-assets-resources {}\n- MCP tool: get-assets-resource {"resourceId":"<resourceId>"}\n- MCP tool: update-assets-resource {"resourceId":"<resourceId>","values":{"query":null}}\n- MCP tool: preview-asset-query {"query":{"where":{"all":[{"field":["properties","slug"],"operator":"eq","value":"hello-world"}]},"limit":1,"content":{"mode":"markdown-body","maxBytes":1048576}}}\n\nNotes:\n\n- Read the field catalog before authoring unfamiliar queries. It includes dynamic schema-less frontmatter paths such as `properties.author.name`, observed types, optionality, and mixed-type state without downloading Markdown files.\n- Minimize the deployed content database by using `output.mode:"fields"` and selecting only fields the rendered page needs. Keep `includeMetadata:false` unless the rendered value needs file metadata such as name, path, MIME type, or creation date, and avoid `output.mode:"all"` as a convenience default. Query diagnostics are returned separately and do not require metadata output. Filters and sorting may still require their referenced fields in the database.\n- Combine filters with `where.all` (AND) and `where.any` (OR), including nested groups. Filter values, limit, and offset on a saved resource may be Webstudio expressions evaluated at render time. Preview queries use concrete JSON values.\n- Use `content.mode:"none"` for listings. Request `markdown-body`, `full`, or a bounded `range` only after filtering to the intended files, normally with `limit:1` for a slug detail route.\n- In Markdown, reference sibling Assets with conventional relative URLs such as `../images/hero.png`. When `markdown-body` is requested, the content engine resolves matching files against the Markdown file\'s folder and emits the correct Builder or published Asset URL. Keep external URLs absolute.\n- Markdown Embed renders sanitized authored HTML for figures, captions, audio, video, and iframes. Scripts, inline event handlers, `srcdoc`, and unsafe URL protocols are removed. Executable component composition remains separate future MDX work.\n- Preview each query with concrete values before saving it. Inspect `__diagnostics__.query` for the temporary query-only footprint and `__diagnostics__.database` for the merged database built from all reachable Assets queries. Only `database.usedBytes` counts toward `database.maxBytes`; query sizes must not be summed and are not separate allowances. Compare `usedBytes`, `unboundedBytes`, and `truncated` within both scopes. When merged usage approaches the limit, remove unused output fields, narrow candidate files, and reduce embedded content in that order.\n- Read Assets from the ID-keyed map at `<dataSourceName>.data`, with collection information such as `totalCount` and `hasMore` at `<dataSourceName>.meta`. Bind a listing Collection to `posts.data` and a one-result detail Collection to `post.data`. On each value, selected file fields such as `id`, `name`, and `extension` are top-level; Markdown frontmatter and JSON fields are under `properties`; the derived `excerpt` is top-level; and requested Markdown is at `content.text`.\n- Assets has one response shape and always executes a structured query. Omit `query` to use the default query, which selects URL and optional image dimensions. Provide query configuration to control filtering, sorting, pagination, selected fields, or file content. Set `values.query:null` to restore the default query.\n- `create-assets-resource` and `update-assets-resource` are the semantic authoring path. Do not construct the internal query URL, headers, or body expression manually.\n- The shared metadata index is maintained automatically and is emitted only when a configured Assets resource is reachable.\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- MCP tool: list-assets {"verbose":true}\n\nNotes:\n\n- Compact results include each asset\'s folder id. Use `verbose:true` to include complete records for a page of assets, or `get-asset` to read one complete record including description, folder, creation time, and image/font metadata.\n- Image asset descriptions are the default alt text for asset-backed Image components.\n- To generate missing descriptions, inspect the image in its rendered page or asset source, write a concise description of its purpose, and save it on the asset rather than duplicating it on each Image instance.\n\n## Get asset\n\nCommands:\n\n- MCP tool: get-asset {"assetId":"<assetId>"}\n\n## List asset folders\n\nCommands:\n\n- MCP tool: list-asset-folders {}\n\n## Create asset folder\n\nCommands:\n\n- MCP tool: create-asset-folder {"name":"Marketing"}\n- MCP tool: create-asset-folder {"name":"Photos","parentId":"<parentFolderId>"}\n\n## Update asset folder\n\nCommands:\n\n- MCP tool: update-asset-folder {"folderId":"<folderId>","values":{"name":"Brand"}}\n- MCP tool: update-asset-folder {"folderId":"<folderId>","values":{"parentId":"<parentFolderId>"}}\n- MCP tool: update-asset-folder {"folderId":"<folderId>","values":{"parentId":null}}\n\nNotes:\n\n- Updating `parentId` is the folder equivalent of cut and paste. Use `null` to move a folder to Root.\n\n## Duplicate asset folder\n\nCommands:\n\n- MCP tool: duplicate-asset-folder {"folderId":"<folderId>"}\n- MCP tool: duplicate-asset-folder {"folderId":"<folderId>","parentId":"<targetFolderId>"}\n\nNotes:\n\n- Duplication recursively copies descendant folders and assets. This is the folder equivalent of copy and paste.\n\n## Delete asset folder\n\nCommands:\n\n- MCP tool: delete-asset-folder {"folderId":"<folderId>"}\n\nNotes:\n\n- Deleting a folder recursively deletes its descendant folders and assets.\n\n## Update asset metadata\n\nCommands:\n\n- MCP tool: update-asset {"assetId":"<assetId>","values":{"description":"Team collaborating around a whiteboard"}}\n- MCP tool: update-asset {"assetId":"<fontAssetId>","values":{"meta":{"family":"Rajdhani","style":"normal","weight":600}}}\n\nNotes:\n\n- Use an empty description only when the image is intentionally decorative.\n- Updating an image asset description updates the default alt text wherever that asset is used with an asset-backed alt prop.\n- Font metadata updates merge with the detected metadata and are validated before committing; use this to correct a family, style, or weight after upload.\n\n## Generate missing image descriptions with an agent\n\nCommands:\n\n- MCP tool: audit {"scopes":["accessibility"],"verbose":true}\n- MCP tool: set-image-descriptions {"updates":[{"assetId":"hero-id","description":"Team collaborating around a whiteboard"},{"assetId":"texture-id","decorative":true}]}\n- MCP tool: audit {"scopes":["accessibility"]}\n\nNotes:\n\n- Start from `missing-image-description` findings. Inspect each image in its rendered page context before writing text.\n- The vision-capable agent generates the wording; the CLI validates and stores it but does not contain its own vision model.\n- Use `decorative:true` only when the image adds no information. This intentionally stores an empty description so later audits do not report it as missing.\n- Re-run the accessibility audit after the update. Asset-backed Image components use the saved asset description as their default alt text.\n\n## Manage fonts\n\nCommands:\n\n- MCP tool: list-fonts {"includeSystem":true}\n- MCP tool: list-assets {"type":"font"}\n- MCP tool: upload-asset {"asset":{"name":"acme-sans.woff2","type":"font","format":"woff2","meta":{"family":"Acme Sans","style":"normal","weight":400}},"assetsDir":".webstudio/assets"}\n- MCP tool: update-styles {"updates":"styles.json contents"}\n\nNotes:\n\n- Use `list-fonts` to discover uploaded families and system stacks. Upload/delete fonts through the existing asset tools, then apply a family with a `font-family` style declaration.\n\n## Upload one asset\n\nCommands:\n\n- MCP tool: upload-asset {"asset":{"name":"image.png","type":"image","format":"png","meta":{"width":1200,"height":630}},"assetsDir":".webstudio/assets"}\n- MCP tool: upload-asset {"asset":{"name":"image.png","type":"image","format":"png","folderId":"<folderId>","meta":{"width":1200,"height":630}},"assetsDir":".webstudio/assets"}\n\n## Upload asset batch\n\nCommands:\n\n- MCP tool: upload-assets {"assets":[{"name":"image.png","type":"image","format":"png","meta":{"width":1200,"height":630}}],"assetsDir":".webstudio/assets"}\n\n## Duplicate asset\n\nCommands:\n\n- MCP tool: duplicate-asset {"assetId":"<assetId>"}\n- MCP tool: duplicate-asset {"assetId":"<assetId>","folderId":"<targetFolderId>"}\n- MCP tool: duplicate-asset {"assetId":"<assetId>","folderId":null}\n\nNotes:\n\n- Duplication is the asset equivalent of copy and paste. Updating `folderId` is the equivalent of cut and paste; use `null` for Root.\n\n## Download asset\n\nCommands:\n\n- MCP tool: download-asset {"assetId":"<assetId>"}\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>"}\n\n## Delete assets\n\nCommands:\n\n- MCP tool: delete-asset {"assetIdsOrPrefixes":["<assetId>"],"force":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: get-marketplace-product {}\n- MCP tool: update-marketplace-product {"category":"pageTemplates","name":"Acme Template","thumbnailAssetId":"asset-id","author":"Acme Studio","email":"[email protected]","website":"https://example.com","issues":"","description":"Reusable template project for Acme landing pages."}\n- MCP tool: submit-marketplace-product {"acknowledgePublicSubmission":true}\n\nPatch namespaces:\n\n- marketplaceProduct\n\n## Search and inspect safely\n\nCommands:\n\n- MCP tool: search-project {"query":"pricing"}\n- MCP tool: search-project {"query":"api.example.com","scopes":["resources"]}\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 `search-project` for query-driven lookup across labels, text, prop values, resource URLs, asset metadata, and styles. Use `audit` for project health findings.\n\n## Audit project quality\n\nCommands:\n\n- webstudio audit --json\n- webstudio audit --scopes accessibility --scopes seo --json\n- webstudio audit --page-path /pricing --json\n- webstudio audit --scopes accessibility --verbose --json\n- webstudio audit --rendered --page-path /pricing --json\n- webstudio audit --rendered --route-example post=/blog/hello --json\n- webstudio audit --rendered --image-domain images.example.com --json\n- MCP tool: audit {}\n- MCP tool: audit {"scopes":["accessibility","security"],"severities":["error","warning"]}\n- MCP tool: audit {"scopes":["accessibility"],"verbose":true}\n- MCP tool: audit {"scopes":["craft"],"verbose":true}\n- MCP tool: audit {"rendered":true,"verbose":true}\n\nNotes:\n\n- With no scopes, `audit` checks accessibility, security, SEO, performance settings, unused assets, ineffective Collection styles, non-GET resources exposed as render-time data, and unused or duplicate style data.\n- Craft is opt-in and read-only. Run `audit` with `scopes:["craft"]` to detect whether the project is not using Craft, partially compatible, or compatible with the versioned Craft 1.2 profile. `profileStatuses` includes the University-doc provenance and the smallest safe next action. The audit never installs Craft or changes a non-Craft project.\n- The `performance` scope reports disabled atomic CSS generation. A rendered audit also measures broken, eager below-fold, and oversized images, browser-marked render-blocking resources, and legacy font formats.\n- Rendered image and resource metrics run only when the selected scopes include `performance`; responsive layout dimensions remain available whenever `rendered:true` is requested.\n- Compact findings include stable ids, severity, message, and location. Use `--verbose` or `{"verbose":true}` for evidence, explanation, suggested remediation, skipped-check details, and manual-check workflows.\n- `summary` counts all findings before severity filtering and pagination.\n- `contractVersion` identifies the audit response contract. Handle a new value before assuming existing fields retain the same meaning.\n- Expression-, resource-, and parameter-backed values that cannot be checked reliably appear in `skippedChecks`; they are not treated as passing or failing.\n- Page filters apply to page-owned accessibility, security, and SEO checks. Asset and style usage remain project-wide to avoid false unused findings.\n- Continue paginated results with `cursor`. Restart the audit if the project version changes.\n- Verbose skipped-check and manual-check details are included on the first findings page only; their total counts remain available on every page.\n- `manualChecks` describes responsive, hierarchy, and contrast checks that require preview screenshots and vision.\n- Focused audits return only manual checks relevant to their selected scopes.\n- In a long-lived MCP session, `{"rendered":true}` reuses preview and screenshot\n tools to capture every static page at mobile, desktop, and Builder breakpoint\n edges. Compact output reports rendered check/issue/failure counts; verbose\n output includes screenshot paths and measured layout dimensions.\n- Dynamic route templates are skipped unless `--route-example <pageId>=<path>`\n (or MCP `routeExamples`) supplies a concrete path. The path must not contain\n unresolved `:` or `*` parameters.\n- Plans above 120 captures return a short-lived confirmation token. Review the\n unchanged plan, then rerun with `--confirm-large-run` and\n `--confirmation-token`.\n- Detailed rendered evidence is stored in a versioned manifest under\n `.webstudio/audits`; compact output includes its path and screenshot count.\n- Rendered checks also report broken images, eager images below the fold, and\n image sources more than 2x their rendered dimensions in both axes, including\n Webstudio instance ids and measured dimensions when available.\n- Rendered checks include sanitized Resource Timing evidence and report\n browser-marked render-blocking resources plus legacy `.ttf`, `.otf`, and\n `.woff` fonts without applying a universal transfer-size threshold.\n- Fix findings through semantic mutation commands, then rerun `audit` to confirm their deterministic finding ids disappeared.\n\n## Verify dynamic bindings\n\nCommands:\n\n- webstudio verify-bindings --json\n- MCP tool: verify-bindings {"pagePath":"/pricing"}\n- MCP tool: verify-bindings {"instanceId":"<instanceId>","limit":50}\n\nNotes:\n\n- Statically checks persisted text expressions, expression/action/resource/parameter props, resource expressions, and page metadata.\n- Findings distinguish invalid syntax, unknown or out-of-scope variables, stale internal data-source ids, and missing resource or parameter references.\n- Page and instance filters can be combined when the instance belongs to the selected page. Continue findings with `cursor`.\n- This operation does not resolve rendered values or execute external resources. Preview representative loading, empty, error, and populated states after static findings are fixed.\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: replace-text {"find":"Old headline","replace":"New headline","match":"exact","pagePath":"/pricing","limit":20}\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: update-page {"pageId":"<pageId>","values":{"title":"Pricing","meta":{"description":"Plans"}}}\n- MCP tool: update-resource {"resourceId":"<resourceId>","values":{"url":"https://api.example.com/posts"}}\n- MCP tool: replace-asset {"fromAssetId":"<oldAssetId>","toAssetId":"<newAssetId>"}\n- MCP tool: replace-styles {"property":"color","fromValue":{"type":"keyword","value":"red"},"toValue":{"type":"keyword","value":"blue"}}\n- MCP tool: rewrite-css-variable-refs {"map":"variables.json contents"}\n\nNotes:\n\n- Use focused reads first, then mutate only matching instances, props, metadata, resource URLs, assets, or style references. Use `replace-text` for bounded literal text changes, `replace-prop-text` for bounded static prop text, `replace-resource-text` for fixed resource names/URLs, and `update-text` for one known child or expressions.\n\n## Optimize existing project\n\nCommands:\n\n- MCP tool: list-pages {}\n- MCP tool: list-folders {}\n- MCP tool: update-page {"pageId":"<pageId>","values":{"title":"Pricing","meta":{"description":"Plans"}}}\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: list-breakpoints {}\n- MCP tool: update-breakpoint {"breakpointId":"tablet","values":{"maxWidth":1023}}\n- MCP tool: get-styles {"instanceIds":["<instanceId>"],"includeTokens":true}\n- MCP tool: update-styles {"updates":"styles.json contents"}\n- MCP tool: attach-design-token {"designTokenId":"<tokenId>","instanceIds":"instances.json contents"}\n- MCP tool: update-project-settings {"meta":{"siteName":"Acme"}}\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-variable {"scopeInstanceId":"<instanceId>","name":"tags","value":{"type":"json","value":["news","product"]}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"filters","value":{"type":"json","value":{"tag":"news"}}}\n- MCP tool: create-resource {"resource":{"name":"Posts","method":"get","url":"https://api.example.com/posts","searchParams":[{"name":"tag","value":"filters.tag"},{"name":"source","value":{"type":"literal","value":"website"}}],"headers":[]},"scopeInstanceId":"<instanceId>","dataSourceName":"posts"}\n- MCP tool: create-resource {"resource":{"name":"Post GraphQL","control":"graphql","method":"post","url":"https://api.example.com/graphql","headers":[{"name":"Content-Type","value":{"type":"literal","value":"application/json"}}],"body":"{ query: \\"query Post($slug: String!) { post(slug: $slug) { title } }\\", variables: { slug: system.params.slug } }"},"scopeInstanceId":"<instanceId>","dataSourceName":"post"}\n- MCP tool: create-resource {"resource":{"name":"Current Date","control":"system","method":"get","url":"/$resources/current-date","headers":[]},"scopeInstanceId":"<instanceId>","dataSourceName":"currentDate"}\n- MCP tool: update-resource {"resourceId":"<resourceId>","values":{"url":"https://api.example.com/posts"}}\n- MCP tool: bind-props {"bindings":"bindings.json contents"}\n- MCP tool: insert-fragment {"parentInstanceId":"<instanceId>","fragment":"<ws.collection>{/_ collection content _/}</ws.collection>"}\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- For read data, expose GET resources as scoped data variables with `scopeInstanceId`/`dataSourceName` and read the loaded result from the resource result wrapper, usually `.data`.\n- For writes, webhooks, GraphQL submissions, and deletes, prefer unscoped resources bound to Form `action` props so they become action resources instead of auto-loaded read resources.\n- Use direct props for fixed values and prop bindings only when a prop must read a data variable, resource, action, or documented runtime context value such as `system`.\n\n## Render an array or object as repeated content\n\nCommands:\n\n- MCP tool: insert-collection {"parentInstanceId":"<instanceId>","data":{"type":"expression","value":"posts.data.items"},"itemFragment":"<ws.element ws:tag=\\"article\\"><ws.element ws:tag=\\"h2\\">{expression`collectionItem.title`}</ws.element></ws.element>"}\n- MCP tool: inspect-instance {"instanceId":"<collectionId>","include":["props","bindings","children"]}\n\nNotes:\n\n- Use Collection whenever an array or object from a resource or data variable should render a list, grid, cards, table rows, options, tabs, or other repeated UI.\n- Pass `insert-collection` the complete array or object. Do not pass the resource response wrapper or one indexed item. External resource arrays are commonly nested under the scoped resource result\'s `data` field or deeper.\n- Pass one repeated-item Webstudio JSX root. The command creates the Collection, its private current-item/current-key parameters, the iterable binding, and descendant item bindings atomically.\n- Collection renders the item root once for every entry. Use `expression` values such as `collectionItem.title` in descendant text and props. Object iteration also exposes `collectionItemKey`.\n- Wrap multiple repeated sibling instances in one Element inside Collection.\n- For repeated Radix items such as accordion items, tabs, or menu options, bind a stable unique id or slug to every required `value` prop.\n- See the [Collection documentation](https://docs.webstudio.is/university/core-components/collection) for the equivalent Builder workflow.\n\n## Support dynamic runtime behavior\n\nCommands:\n\n- MCP tool: integrate-runtime-ui {"parentInstanceId":"<instanceId>","resources":[{"resource":{"name":"Seats","method":"get","url":"https://api.example.com/seats","headers":[]},"dataSourceName":"Seats","exposeAsDataSource":true}],"structure":{"type":"collection","data":{"type":"expression","value":"Seats.data"},"itemFragment":{"children":[{"type":"id","value":"seat"}],"instances":[{"type":"instance","id":"seat","component":"Text","children":[{"type":"expression","value":"collectionItem.label"}]}],"props":[],"dataSources":[],"resources":[],"styleSources":[],"styleSourceSelections":[],"styles":[],"breakpoints":[],"assets":[]}},"retainedBehavior":[{"instanceId":"<scriptInstanceId>","responsibility":"Seat selection behavior"}]}\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: bind-props {"bindings":"bindings.json contents"}\n- MCP tool: create-resource {"resource":{"name":"Seats","method":"get","url":"https://api.example.com/seats","headers":[]}}\n- MCP tool: snapshot {"include":["instances","props","resources"]}\n- MCP tool: apply-patch {"baseVersion":"<version>","transactions":"patch.json contents"}\n\nNotes:\n\n- Use `integrate-runtime-ui` to create variables/resources, insert one editable fragment or Collection, and add safe data bindings in one transaction.\n- List existing script-owned responsibilities under `retainedBehavior`. The operation preserves those instances and never evaluates or accepts replacement script bodies.\n- `unsupportedConversions` records behavior that cannot be represented safely. Dry-run returns the complete transaction and the same retained/unsupported report without changing the project.\n- New actions and HtmlEmbed scripts are intentionally rejected. Create normal editable components and data bindings; keep opaque runtime behavior in existing script instances.\n\n## Build authenticated pages\n\nCommands:\n\n- MCP tool: meta.guide {"brief":"Build a Supabase-authenticated account page"}\n- MCP tool: create-page {"name":"Account","path":"/account"}\n- MCP tool: update-page {"pageId":"<pageId>","values":{"meta":{"auth":{"method":"basic","login":"<login>","password":"<password>"}}}}\n- MCP tool: create-resource {"resource":{"name":"Session","method":"get","url":"https://api.example.com/session","headers":[]}}\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- Inspect and reuse the project\'s existing auth convention before authoring. Do\n not add a second provider or session model implicitly.\n- Model signed-out, loading, signed-in, and failed-auth states explicitly.\n- Never store credentials, service-role keys, refresh tokens, private session\n values, or authenticated response bodies in project data, command output,\n screenshots, agent instructions, or error reports. Privileged provider calls\n and authorization enforcement belong server-side.\n- Basic auth is semantic today. Provider-specific Supabase/Firebase setup still\n uses the existing resource, variable, prop, binding, and embed tools; there is\n no provider-specific installer.\n\n## Generate from design input\n\nCommands:\n\n- MCP tool: meta.guide {"brief":"Recreate this Figma design as a responsive page"}\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 {"vars":"vars.json contents"}\n- MCP tool: list-breakpoints {}\n- MCP tool: insert-fragment {"parentInstanceId":"<instanceId>","fragment":"<ws.element ws:tag=\\"section\\"><ws.element ws:tag=\\"p\\">Section copy</ws.element></ws.element>"}\n- MCP tool: update-styles {"updates":[{"instanceId":"<instanceId>","breakpointId":"<breakpointId-from-list-breakpoints>","property":"padding-left","value":{"type":"unit","unit":"px","value":24}}]}\n- MCP tool: preview.start {"host":"127.0.0.1","port":5173}\n- MCP tool: screenshot {"path":"/landing","output":"landing-desktop.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot {"path":"/landing","output":"landing-mobile.png","viewport":{"width":390,"height":844},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot {"baseUrl":"http://127.0.0.1:5177","path":"/landing","output":"landing-desktop.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n\nNotes:\n\n- Use this after the agent can inspect the supplied design. There is no direct\n Figma, screenshot, Inception, or `design.md` import command.\n- Inspect and reuse existing variables, tokens, styles, components, assets, and\n page patterns before authoring. Build semantic editable structure rather than\n flattening the design into an image or absolute-positioned approximation.\n- Verify one familiar viewport inside every distinct Builder breakpoint range,\n then run rendered audit and inspect the screenshots before completion.\n\n## Cross-project maintenance\n\nCommands:\n\n- webstudio mcp run .temp/projects.json\n- webstudio mcp run .temp/projects.json --dry-run\n- webstudio mcp run .temp/projects.json --approve-mutations --concurrency 2\n\nNotes:\n\n- Put shared `calls` and a `projects` array of independently linked project roots in the existing `mcp run` manifest. Project roots are relative to the manifest file.\n- Each project uses its own config, authentication, ProjectSession storage, checkpoint, and failure boundary. Confirmed successful calls are checkpointed. Reads can resume automatically; a mutation interrupted after dispatch is reported as ambiguous and is not replayed automatically, preventing silent duplicate writes.\n- Focus the manifest on bounded reads or audits first. Use per-call `dryRun`, global `--dry-run`, or explicitly approve committed mutations with `--approve-mutations` after reviewing the manifest.\n\n# Known CLI Gaps\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:\nCall `meta.guide` with the provider-authenticated page goal, then create the\npage, resources, variables, props, bindings, and embeds with existing semantic\ntools.\n\nSuggested commands:\n\n- setup-auth-page\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:\nCall `meta.guide` with the design-input goal, let the agent inspect the supplied\ndesign, then use semantic page, token, asset, fragment, style, preview,\nscreenshot, and audit tools. Use `apply-patch` only when no semantic operation\nfits.\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\n- Pass --json to API/discovery commands that support it. Do not add --json to top-level commands unless their help/schema documents it.\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 compact meta.session with operationId, buildId, version, source, committed, namespaceCounts, diagnosticCount, non-empty diagnostic summaries, and optional compatibilityVersion.\n\n## CLI Capability Inventory\n\nFor a short end-consumer summary of what MCP can do, see\n`manual mcp` / `webstudio man mcp`. The MCP inventory describes the same\nproject, page, element, style, data, asset, publish, domain, and visual\nverification capabilities without internal command names.\n\n### Top-Level Commands\n\n{{topLevelCapabilityIndex}}\n\n### High-Level API Commands By Area\n\n{{apiCapabilityIndex}}\n\n### MCP Tool Operations\n\nThese are MCP tools. From a shell, call them with the shortcut form `webstudio <tool> \'<json>\'` or with the explicit form `webstudio mcp single-op-call <tool> \'<json>\'`:\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": "patch-transaction-label",\n"payload": [\n{\n"namespace": "projectSettings",\n"patches": [\n{ "op": "replace", "path": ["meta", "siteName"], "value": "New Site" }\n]\n}\n]\n}\n\nThe transaction id is a patch label used for optimistic synchronization. It is\nnot a Builder record id. Do not invent ids for pages, instances, props,\nbreakpoints, resources, variables, folders, assets, or other project records.\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: redirects, page records, and folders\n- projectSettings: project-wide metadata and 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\n## Data Sources\n\n`dataSources` is the internal Builder namespace for variables. Public API, CLI,\nand MCP tools expose it through two user-facing groups:\n\n- data variables: `list-variables`, `create-variable`, `update-variable`, and\n `delete-variable`\n- data resources: `list-resources`, `create-resource`, `update-resource`, and\n `delete-resource`\n\nFor raw `snapshot`, request the public `variables` namespace rather than the\ninternal `dataSources` name. Raw patch payloads still use `dataSources` when\napplying direct changes.\n\nVariables can be scoped to an instance. Expressions under that instance can use\nthe variable by name; nested variables with the same name mask outer variables.\nVariable values support `string`, `number`, `boolean`, and `json`. Use `json`\nfor all arrays and objects, including tags, selected categories, and nested API\nfilter state.\nParameters are internal scoped runtime values provided by pages, collections,\nor components. They are not a public authoring surface: do not create, update,\nor delete parameter records. Public tools should preserve existing parameter\nrecords and may reference documented context values such as `system` in\nexpressions where they are already in scope.\n\nResource `url` accepts plain fixed URLs and paths, for example\n`https://api.example.com/posts` or `/$resources/current-date`. Dynamic URLs can\ncombine strings and variables, for example\n`"https://api.example.com/posts?tag=" + filters.tag`. Prefer `searchParams` for\nquery parameters that should be encoded separately:\n`[{ "name": "tag", "value": "filters.tag" }]`. Header values, search parameter\nvalues, and bodies are expressions for dynamic content. For fixed text, use\n`{ "type": "literal", "value": "application/json" }`; Webstudio stores the\nrequired string expression. Headers can still read variables such as\n`"Bearer " + auth.token`, and GraphQL bodies can return objects such as\n`{ query: "...", variables: { slug: system.params.slug } }`.\n\nCreate a GET resource with `scopeInstanceId` when the fetched resource result\nshould be available as a read data variable. Scoped GET resources default to\n`exposeAsDataSource: true`, are generated into the page resource `data` map,\nand may be loaded during page rendering. Use `dataSourceName` to choose the\nvariable name.\n\nFor submit/write/action resources, create the resource without\n`scopeInstanceId`, then bind a component prop such as a Form `action` to the\nresource with `bind-props` and `binding.type: "resource"`. Prop-bound resources\nare generated into the page resource `action` map instead of the read `data`\nmap. Use this shape for POST, PUT, DELETE, webhook, and other resources that\nshould run only from an explicit form/action flow, not merely because the page\nrendered.\n\nPOST, PUT, and DELETE resources default to `exposeAsDataSource: false` even\nwhen a scope is supplied. Set `exposeAsDataSource: true` only when a write-method\nresource intentionally provides render-time data, such as a read-only GraphQL\nPOST query. A scope is required, and the result includes a warning because the\nrequest may execute during page rendering. Set `exposeAsDataSource: false` on\n`update-resource` to detach an existing render-time data source.\n\nResource `method` can be `get`, `post`, `put`, or `delete`. Use GET for read\ndata. Use POST for creates, GraphQL requests, webhooks, and form submissions.\nUse PUT for full updates/replacements. Use DELETE for deletion actions.\nOptional `control` values are `graphql` and `system`: `graphql` marks a\nGraphQL-style resource, usually POST with a query body; `system` marks a\nresource intended to use the built-in `system` parameter or one of the built-in\nlocal resource URLs: `"/$resources/sitemap.xml"`,\n`"/$resources/current-date"`, and `"/$resources/assets"`. The system parameter\nfields are `system.origin`, `system.pathname`, `system.params`, and\n`system.search`.\n\nUse prop bindings for dynamic values that read variables or resources; use\ndirect props for static values.\n\nCommit raw patch:\n\nMCP tool: apply-patch\n\n## Raw Patch Examples\n\nRename the site:\n\n[\n{\n"id": "patch-site-name",\n"payload": [\n{\n"namespace": "projectSettings",\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": "patch-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": "patch-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 records with semantic operations such as create-variable,\ncreate-resource, create-design-token, create-page, create-folder,\nand create-breakpoint. Raw patch rejects generated record\ncreation, collection replacement, record replacement with a different `id`, and\nrecord id field mutations in id-keyed namespaces because Webstudio must generate\nand preserve record ids.\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- Do not create generated records, replace generated record collections, replace records with different ids, or mutate record id fields with raw patch. Use semantic create operations so Webstudio generates ids.\n- If apply-patch reports a version conflict, read the latest build and regenerate the patch.\n- Prefer semantic MCP read tools for discovery, then use MCP snapshot for exact patch paths.\n\n## Command Index\n\n{{commandIndex}}\n',
"manual-llm":
- '# Webstudio CLI Manual for LLMs\n\nUse this order. Stop only when a command returns ok:false.\n\nIf you are inside the Webstudio monorepo, the first command discovery should use\nthe local CLI exactly as `node packages/cli/local.js ...` from the repo root. Do\nnot use `packages/cli/bin.js` for local source-tree work; it is the packaged\nbuild entry and may use stale built output. Do not use `pnpm exec webstudio`,\n`pnpm --filter webstudio exec webstudio`, or a global `webstudio`: they can\nresolve an older binary.\n\nFor delegated design-system or “use every component” tasks, skip the generic warm-up sequence and start with exactly one MCP command: `webstudio workflow.next \'{"goal":"design-system-page"}\'`. Report that returned checkpoint to the parent/user and stop until continued.\n\n## Use MCP locally or optionally connect a client\n\nDo not install, register, or connect an MCP server merely because the user asks\nyou to edit a Webstudio project. If Webstudio MCP tools are already available,\nuse them. If you have shell access, use the local CLI shortcuts such as\n`webstudio meta.index` and `webstudio list-pages`; they expose the same project\noperations without changing client configuration or restarting the app.\n\nOnly when the user explicitly asks for persistent native MCP integration, run\nthe command for their client:\n\n- Claude Code: `webstudio connect claude`\n- Codex: `webstudio connect codex`\n- Cursor: `webstudio connect cursor`\n- VS Code or GitHub Copilot: `webstudio connect vscode`\n\nRun project operations from the linked project root. If the folder is not\nlinked, ask for an editable Builder share link and run\n`webstudio init --link <share-link> --json`. You can then use local CLI\nshortcuts immediately. Do not run `webstudio sync`, `webstudio connect`, or\nrestart the app unless the user specifically wants native MCP registration:\nMCP reads and edits the latest editable Builder build directly, including for\nprojects that have never been published. Treat the share link as a credential\nand do not include it in committed files, logs, screenshots, or issue reports.\n\nThe optional `connect` command verifies project access before changing client configuration. For\nClaude Code, Cursor, and VS Code it safely merges the `webstudio` server into\nthe client\'s project configuration. For Codex it runs both `codex mcp add` and\n`codex mcp get webstudio`; do not repeat those commands separately. Follow the\nreload, restart, or approval instruction printed by `connect`, then verify the\nloaded MCP connection by asking the client to use Webstudio MCP and list the\nproject pages. Use `--print` only to inspect the generated setup without\nchanging configuration or requiring project access.\n\n## Always\n\n1. webstudio permissions --json\n2. For bounded shell workflows, call MCP tools directly through the CLI shortcut, for example `webstudio meta.index` or `webstudio insert-fragment \'<json>\' --dry-run`. The explicit form `webstudio mcp single-op-call <tool> \'<json>\'` is equivalent and useful when you need to make the MCP boundary obvious. Use `webstudio mcp run \'[{"tool":"components.find","input":{"brief":"button"}}]\'` for multiple calls in one shared CLI session. Use a normal JSON file path for large batches. Use long-running `webstudio mcp` only when your environment is a real MCP client. Do not manually send raw JSON-RPC to `webstudio mcp` from a shell or PTY.\n3. Read MCP `meta.index`, for example `webstudio meta.index`.\n4. Use focused MCP calls with concrete JSON: `webstudio meta.guide \'{"brief":"Create a design system page using every component"}\'`, `webstudio meta.get_more_tools \'{"tools":["insert-fragment"]}\'`, `webstudio components.list \'{"source":"all"}\'`, `webstudio components.coverage-plan`, `webstudio components.search \'{"brief":"radix select"}\'`, `webstudio components.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'`, `webstudio templates.list`, and `webstudio templates.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'`.\n5. Read overview resources `webstudio://project/tools-overview` or `webstudio://project/components-overview` when useful. Read full resources `webstudio://project/tools` or `webstudio://project/components` only when focused tools are insufficient.\n6. Pick focused MCP read tool.\n7. Pick semantic MCP write tool.\n\nUse `webstudio schema mcp` for a compact MCP tool overview. Add `--verbose` only when exact input schemas for all tools are truly needed; otherwise prefer focused `meta.get_more_tools` and `components.*` calls.\n\nRun these commands from the linked project root. Use the MCP startup status line\'s absolute root for local files; write temporary scripts and artifacts under `<project root>/.temp`, not under a parent workspace.\n\nMonorepo quick path for a simple styled section:\n\n```sh\nnode packages/cli/local.js mcp single-op-call meta.index\nnode packages/cli/local.js mcp single-op-call meta.get_more_tools \'{"tools":["insert-fragment"]}\'\nnode packages/cli/local.js mcp single-op-call insert-fragment \'{"parentInstanceId":"parent-id","fragment":"<ws.element ws:tag=\\"section\\" ws:style={css`padding: 32px; display: grid; gap: 12px;`}><ws.element ws:tag="h2">Launch Kit</ws.element><ws.element ws:tag="p">A focused section created with Webstudio JSX.</ws.element><ws.element ws:tag="button">Get started</ws.element></ws.element>"}\' --dry-run\n```\n\nThe same local shortcut form is shorter and preferred for simple shell steps:\n\n```sh\nnode packages/cli/local.js meta.index\nnode packages/cli/local.js meta.get_more_tools \'{"tools":["insert-fragment"]}\'\nnode packages/cli/local.js insert-fragment \'{"parentInstanceId":"parent-id","fragment":"<ws.element ws:tag=\\"section\\" ws:style={css`padding: 32px; display: grid; gap: 12px;`}><ws.element ws:tag="h2">Launch Kit</ws.element><ws.element ws:tag="p">A focused section created with Webstudio JSX.</ws.element><ws.element ws:tag="button">Get started</ws.element></ws.element>"}\' --dry-run\n```\n\nFor this simple path, do not grep source files, dump full MCP resources, or write parser scripts first. Use `list-pages`, `get-page-by-path`, or `list-instances` only to get the target `parentInstanceId`.\n\nWhen authoring JSX for `insert-fragment`, use Webstudio component helpers and Webstudio style syntax. Use `ws:style={css\\`...\\`}`for Webstudio-native CSS, or use React-style object syntax such as`style={{ padding: 24 }}` when that is simpler. Both forms create editable Webstudio style data.\n\nWhen the task says another user will edit a page in Content mode, use a Content Block (`ws:block`) around every editable region. Content-mode users can edit text and supported props only in descendants of that block; content outside it is read-only. Put reusable insertable options in the block\'s `ws:block-template` child. Do not put intended editor content inside that template container: templates are protected source material, while an inserted template copy becomes an editable direct child of the Content Block. Verify this structure before handoff.\n\nDo not access host globals or dynamic code APIs in JSX fragments, including `process`, `globalThis`, `eval`, `Function`, or `constructor`. JSX fragments are declarative project data; use the built-in Webstudio helpers instead.\n\nUse Webstudio prop names in JSX: `class`, `for`, `aria-label`, and other HTML/Webstudio names. Do not use React-only aliases such as `className` or `htmlFor`; the runtime rejects them with the Webstudio prop name to use.\n\nUse Webstudio actions for event/action props. Do not pass JavaScript functions such as `onClick={() => ...}`; the runtime rejects them because functions cannot be persisted as Webstudio project data.\n\n```tsx\n<ws.element\n ws:tag="button"\n onClick={new ActionValue(["event"], expression`console.log(event)`)}\n>\n Open\n</ws.element>\n```\n\nPlain JSX prop values must be JSON-compatible: `null`, strings, booleans, finite numbers, arrays, and plain objects. Do not pass `undefined`, `Symbol`, `BigInt`, `NaN`, `Infinity`, `Date`, `Map`, `Set`, class instances, or circular objects; omit the prop, use plain data, or use `expression`/`ActionValue` when the value is dynamic.\n\nIf a component has a registered template with required parts, JSX must include those parts explicitly under the same parent structure as the template, for example `<radix.Switch><radix.SwitchThumb /></radix.Switch>`. Use `insert-component` when you want Webstudio to apply one component template automatically.\n\n## Animation Components\n\nBefore creating animation examples, inspect the exact components with focused discovery:\n\n```sh\nwebstudio components.get \'{"component":"@webstudio-is/sdk-components-animation:AnimateChildren"}\'\nwebstudio components.get \'{"component":"@webstudio-is/sdk-components-animation:AnimateText"}\'\nwebstudio components.get \'{"component":"@webstudio-is/sdk-components-animation:StaggerAnimation"}\'\nwebstudio components.get \'{"component":"@webstudio-is/sdk-components-animation:VideoAnimation"}\'\n```\n\nUse Animation Group (`AnimateChildren`) as the controller. Put normal instances directly inside it, or put Text Animation, Stagger Animation, or Video Animation directly inside it. Text, Stagger, and Video are helper components with `contentModel.category: "none"` and should not be used as standalone section roots.\n\nDefine timing and CSS changes on the Animation Group `action` prop. Use `type:"view"` for viewport entry/exit progress and `type:"scroll"` for scroll-progress timelines. For in animations, keep the canvas styles as the final state and use `fill:"backwards"` with keyframes that describe the starting state. For out animations, use `fill:"forwards"` with keyframes that describe the ending state.\n\nText Animation settings: `slidingWindow` defaults to `5`, `easing` defaults to `linear`, and `splitBy` defaults to `char`. Use `splitBy:"space"` for word-by-word animation. The parent Animation Group keyframes provide the actual opacity, translate, scale, or other styles.\n\nStagger Animation settings: `slidingWindow` defaults to `1` and `easing` defaults to `linear`. It applies parent Animation Group progress across its direct children. Use `slidingWindow:0` for instant sequential steps, `1` for one child at a time, and values above `1` for overlapping waves.\n\nVideo Animation settings: `timeline` is a boolean. Prefer `insert-component` for Video Animation so the Video child template is inserted, then configure the Video child asset/source. Use short, seek-friendly videos for smooth scroll-linked playback.\n\nUse JSX fragments for authored animation structures when you need styled, editable examples. Put the final visual state in `ws:style` and put the starting or ending animated state in the Animation Group `action` keyframes. Include an explicit `offset` on every keyframe: use `offset: 0` for starting-state keyframes with `fill:"backwards"` and `offset: 1` for ending-state keyframes with `fill:"forwards"`.\n\n```tsx\n<animation.AnimateChildren\n action={{\n type: "view",\n axis: "block",\n animations: [\n {\n name: "Fade up on entry",\n timing: {\n fill: "backwards",\n rangeStart: ["entry", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["entry", { type: "unit", value: 100, unit: "%" }],\n },\n keyframes: [\n {\n offset: 0,\n styles: {\n opacity: { type: "unit", value: 0, unit: "number" },\n translate: {\n type: "tuple",\n value: [\n { type: "unit", value: 0, unit: "number" },\n { type: "unit", value: 24, unit: "px" },\n ],\n },\n },\n },\n ],\n },\n ],\n }}\n>\n <ws.element\n ws:tag="section"\n ws:style={css`\n display: grid;\n gap: 16px;\n padding: 48px;\n border-radius: 24px;\n background: #111827;\n color: white;\n `}\n >\n <ws.element ws:tag="h2">Launch metrics</ws.element>\n <ws.element ws:tag="p">\n A polished card that fades up as it enters the viewport.\n </ws.element>\n </ws.element>\n</animation.AnimateChildren>\n```\n\nFor Text Animation, keep `animation.AnimateText` as the direct child of Animation Group and place the text-containing element inside it:\n\n```tsx\n<animation.AnimateChildren\n action={{\n type: "view",\n animations: [\n {\n name: "Parallax In",\n timing: {\n fill: "backwards",\n rangeStart: ["cover", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["cover", { type: "unit", value: 70, unit: "%" }],\n },\n keyframes: [\n {\n offset: 0,\n styles: {\n translate: {\n type: "tuple",\n value: [\n { type: "unit", value: 0, unit: "number" },\n { type: "unit", value: 100, unit: "px" },\n ],\n },\n },\n },\n ],\n },\n {\n name: "Opacity In",\n timing: {\n fill: "backwards",\n rangeStart: ["cover", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["cover", { type: "unit", value: 70, unit: "%" }],\n },\n keyframes: [\n {\n offset: 0,\n styles: {\n opacity: { type: "unit", value: 0, unit: "number" },\n },\n },\n ],\n },\n {\n name: "Scale In",\n timing: {\n fill: "backwards",\n rangeStart: ["cover", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["cover", { type: "unit", value: 70, unit: "%" }],\n },\n keyframes: [\n {\n offset: 0,\n styles: {\n scale: {\n type: "tuple",\n value: [\n { type: "unit", value: 5, unit: "number" },\n { type: "unit", value: 5, unit: "number" },\n ],\n },\n },\n },\n ],\n },\n {\n name: "Parallax Out",\n timing: {\n fill: "forwards",\n rangeStart: ["cover", { type: "unit", value: 50, unit: "%" }],\n rangeEnd: ["cover", { type: "unit", value: 100, unit: "%" }],\n },\n keyframes: [\n {\n offset: 1,\n styles: {\n translate: {\n type: "tuple",\n value: [\n { type: "unit", value: 0, unit: "number" },\n { type: "unit", value: -100, unit: "px" },\n ],\n },\n scale: {\n type: "tuple",\n value: [\n { type: "unit", value: 5, unit: "number" },\n { type: "unit", value: 5, unit: "number" },\n ],\n },\n opacity: { type: "unit", value: 0, unit: "number" },\n },\n },\n ],\n },\n ],\n insetStart: { type: "unit", value: 5, unit: "%" },\n insetEnd: { type: "unit", value: 5, unit: "%" },\n isPinned: true,\n }}\n>\n <animation.AnimateText\n splitBy="space"\n slidingWindow={5}\n easing="easeOutQuart"\n >\n <ws.element ws:tag="h2">Animate words with controlled rhythm</ws.element>\n </animation.AnimateText>\n</animation.AnimateChildren>\n```\n\nFor Stagger Animation, put the repeated cards or rows directly inside `animation.StaggerAnimation`:\n\n```tsx\n<animation.AnimateChildren\n action={{\n type: "view",\n animations: [\n {\n timing: {\n fill: "backwards",\n rangeStart: ["contain", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["contain", { type: "unit", value: 30, unit: "%" }],\n },\n keyframes: [\n {\n offset: 0,\n styles: {\n opacity: { type: "unit", value: 0, unit: "number" },\n },\n },\n ],\n },\n ],\n }}\n>\n <animation.StaggerAnimation>\n <ws.element\n ws:tag="article"\n ws:style={css`\n padding: 20px;\n border: 1px solid #d1d5db;\n border-radius: 16px;\n `}\n >\n Plan\n </ws.element>\n <ws.element\n ws:tag="article"\n ws:style={css`\n padding: 20px;\n border: 1px solid #d1d5db;\n border-radius: 16px;\n `}\n >\n Build\n </ws.element>\n <ws.element\n ws:tag="article"\n ws:style={css`\n padding: 20px;\n border: 1px solid #d1d5db;\n border-radius: 16px;\n `}\n >\n Launch\n </ws.element>\n </animation.StaggerAnimation>\n</animation.AnimateChildren>\n```\n\nFor Video Animation, use the registered template via `insert-component` when possible. If you author JSX, include the Video child explicitly:\n\n```tsx\n<animation.AnimateChildren\n action={{\n type: "view",\n animations: [\n {\n name: "Video progress",\n timing: {\n fill: "both",\n rangeStart: ["cover", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["cover", { type: "unit", value: 100, unit: "%" }],\n },\n keyframes: [{ offset: 0, styles: {} }],\n },\n ],\n }}\n>\n <animation.VideoAnimation timeline={true}>\n <$.Video\n preload="auto"\n autoPlay={true}\n muted={true}\n playsInline={true}\n crossOrigin="anonymous"\n />\n </animation.VideoAnimation>\n</animation.AnimateChildren>\n```\n\n## Command Surface Boundary\n\n- Use top-level `webstudio ...` shell commands for setup, sync/import/build/preview/screenshot, permissions, publish/domains, schema, registry inspection, man, and starting MCP.\n- Use MCP tools for Builder project data manipulation: pages, instances/components, props, text, styles, tokens, variables, resources, assets, breakpoints, redirects, and raw patches.\n- From a shell, call MCP tools with the shortcut form `webstudio <tool> \'<json>\'`, for example `webstudio insert-fragment \'<json>\' --dry-run`. The explicit equivalent is `webstudio mcp single-op-call <tool> \'<json>\'`. Use `--input-file` for large payloads.\n- Inside the Webstudio monorepo, call the local CLI as its own command: `node packages/cli/local.js ...`. Do not wrap the CLI call in `pwd && ...`, command substitution, `pnpm exec webstudio`, `pnpm --filter webstudio exec webstudio`, or a global `webstudio`.\n- For experiments, pass `--dry-run` to local-capable mutation calls. Read the computed transaction from `meta.session.transaction` and its base build version from `meta.session.version`. Copying a `.webstudio` folder is not an isolated project clone; `.webstudio/config.json` still points to the same remote project, so non-dry-run mutations can commit to that project.\n- For bounded multi-step shell work, run inline JSON with `webstudio mcp run \'[{"tool":"components.find","input":{"brief":"button"}}]\'`; this reuses one CLI session without raw JSON-RPC. For large batches, write `{ "calls": [{ "tool": "..." }] }` to a normal JSON file and run `webstudio mcp run .temp/mcp-calls.json`.\n- Use JSON strings for `brief` fields. Never pass boolean flags such as `{"brief":true}`.\n- Treat `webstudio mcp single-op-call` and `webstudio mcp run` stderr lines as progress checkpoints; stdout remains JSON on both success and failure. On failure, parse stdout for `{ "ok": false, "error": { "code": "...", "message": "..." } }` before deciding what to fix.\n- If a CLI/MCP tool crashes, hangs, gives a confusing error, needs an undocumented workaround, or forces source-code inspection for normal usage, ask the user to report it in Discord `#help` at https://wstd.us/community. Give them a complete copy-paste report with the goal, expected behavior, actual error, exact command/tool call, stdout JSON, stderr/lifecycle logs, environment, workaround, and secrets redacted.\n- Run one-shot `webstudio mcp single-op-call` commands sequentially against a linked `.webstudio` folder. If a command returns `PROJECT_SESSION_BUSY`, another CLI/MCP process is updating the local session; wait a moment and retry sequentially.\n- In delegated or non-streaming agent environments, do not batch many MCP calls silently and do not wrap many shortcut or `webstudio mcp single-op-call` commands in a shell loop. Treat each parent-visible checkpoint as the unit of work. If the parent asks for status within 30 seconds, run exactly one shortcut command such as `webstudio meta.index` or one explicit `webstudio mcp single-op-call` command, report that command/result, then wait for the parent to continue. Do not take a broad task such as creating a full design-system page as one execution unit. Call `workflow.next {"goal":"design-system-page"}`, report the returned phase/checkpoint, wait until the parent continues, call `checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}`, complete exactly that bounded phase, and return: discovery, page creation, one dry-run JSX section, one committed JSX section, one `components.coverage-insert-next` call, or one presentation pass. Phase commands do not include nextPhase in their own output. After the parent continues, acknowledge the previous checkpoint first, then call `workflow.next` with the next phase. For all-component design-system pages, checkpoint after workflow planning, discovery, page creation, call `components.coverage-insert-next` once before checkpointing again, then finish with `workflow.next {"goal":"design-system-page","phase":"presentation-pass"}`. Coverage 72/72 is necessary but not sufficient: the page must be organized into styled, real-world examples, not raw unstyled component dumps.\n- For design-system or “use every component” tasks, start with compact `webstudio components.coverage-plan`, checkpoint, then request component coverage details with `webstudio components.coverage-plan \'{"detail":"roots","offset":20}\'` or `{"detail":"parts"}` only when needed. Do not pass `detail` to `list-pages`; use `list-pages {}` or `get-page-by-path` for page lookup.\n- MCP tool shortcuts are only for MCP tools. If a shortcut is ambiguous with a real top-level command, the real top-level command wins; use `webstudio mcp single-op-call <tool> \'<json>\'` to force the MCP path.\n\n## LLM Implementation Process\n\nUse this process for user requests that change Webstudio content, layout, styles, assets, pages, redirects, resources, or publishing state:\n\n1. Discover capabilities with `webstudio man --json`, `webstudio schema api`, `webstudio schema mcp`, MCP `meta.index`, `meta.guide`, `meta.get_more_tools`, `components.list`, `components.summary`, `components.coverage-plan`, `components.search`, `components.get`, `templates.list`, and `templates.get`. From a shell, prefer shortcut calls such as `webstudio meta.index` and `webstudio components.search \'{"brief":"button"}\'` for these focused tool calls; use `webstudio mcp single-op-call` when you need the explicit MCP form. Read full resources such as `webstudio://project/tools` and `webstudio://project/components` only when needed. Do not write scripts to parse full MCP discovery JSON for normal lookup.\n2. Inspect current project state with semantic reads such as `get-project-settings`, `list-pages`, `get-page-by-path`, `list-instances`, `inspect-instance`, `get-styles`, `list-assets`, `list-breakpoints`, and `snapshot` only when needed. Before changing a project, read `get-project-settings` and follow any non-empty `meta.agentInstructions`. These are shared project instructions, not a place for secrets.\n3. Mutate the Webstudio project with semantic MCP write tools first. Prefer MCP `insert-fragment` for authored/styled sections, use `insert-component` only for one automatic component template, then `update-text`, `update-props`, `update-styles`, `upload-asset`, `create-page`, and page/project settings tools over raw patches.\n4. Use `apply-patch` only when no semantic tool covers the required change, and only after reading the latest snapshot/version.\n5. For visual/design work, regenerate or preview the generated app, capture a screenshot, inspect it with vision, and iterate before final response.\n6. Report what changed and what verification ran.\n\n## Visual Design Workflow\n\nFor requests involving visible HTML/CSS, layout, typography, colors, imagery, responsive behavior, or screenshots:\n\n1. Read editable Webstudio structure first: pages, instances, props, styles, breakpoints, assets, and relevant text.\n2. Do not use generated route/component files as the source of truth for editable content.\n3. Make edits through Webstudio semantic commands/MCP tools so the result stays editable in Builder and survives the next `webstudio build`.\n4. Keep generated project files current, start preview, and capture the changed page with `screenshot`.\n5. Use `screenshot.diff` when a baseline exists and inspect screenshot/diff artifacts with vision before finishing.\n6. If vision or screenshot tooling is unavailable, state that explicitly and explain what fallback verification was used.\n\n## Responsive Verification Workflow\n\nFor responsive page work, use Builder breakpoints as the source of truth:\n\n1. Read breakpoints with `list-breakpoints` before deciding responsive behavior.\n2. Apply responsive styles with existing Builder breakpoint ids; do not invent CSS media queries or breakpoint names when Webstudio breakpoint data exists.\n3. Pick screenshot viewport widths from the project breakpoints: include a desktop width, each defined max-width or min-width edge, and a narrow mobile width.\n4. Capture each viewport with `screenshot`, for example `{"path":"/","output":"home-375.png","viewport":{"width":375,"height":812}}` and `{"path":"/","output":"home-1440.png","viewport":{"width":1440,"height":900}}`.\n5. Inspect every viewport screenshot with vision before finishing, checking layout, overflow, hidden content, text wrapping, and breakpoint-specific style changes.\n6. If any viewport fails, update styles through semantic Webstudio tools and repeat screenshots for the affected breakpoints.\n\n## Generated Files Guardrails\n\n- Do not edit `app/__generated__`, generated route files, generated page files, generated CSS, or build output for normal Webstudio content/design requests.\n- Do not replace generated page components with handcrafted app code unless the user explicitly asks for code-only export customization.\n- Generated files are build artifacts and may be overwritten by `webstudio build`.\n- If a task truly requires generated app customization, keep it outside `app/__generated__` where possible and explain that it is not editable Webstudio content.\n\n## Values vs Bindings\n\nBefore authoring unfamiliar expressions, read `webstudio://project/expressions` with MCP `resources/read` or `webstudio mcp read-resource webstudio://project/expressions`. It documents the supported expression subset, method allowlist, scope, Collection context, and validation limits.\n\n- Use direct value tools for fixed content. For one visible text child, use `update-text` with plain `text`. For a bounded multi-instance literal replacement, use `replace-text` with `find`, `replace`, `pagePath` or `pageId`, and `limit`; it does not change expression children. Use `replace-prop-text` for bounded changes inside static string props, optionally limited to prop names or instance ids; it never changes dynamic bindings. For static props such as `aria-label`, `alt`, `id`, `class`, `href`, or button labels stored as props, use `update-props` with the prop\'s direct type/value.\n- Use `bind-props` only when the prop must stay dynamic: an expression, resource result, action, or existing scoped runtime context such as `system`. Do not use `bind-props` just to set a fixed string.\n- Direct prop string example: `{"updates":[{"instanceId":"button-id","name":"aria-label","type":"string","value":"Open menu"}]}`.\n- Expression binding example: `{"bindings":[{"instanceId":"link-id","name":"href","binding":{"type":"expression","value":"currentPost.url"}}]}`.\n- Page metadata fields such as `title`, `description`, `language`, `redirect`, and custom meta content accept plain fixed text. For computed values, pass JavaScript expression code such as `pageTitle ?? "Pricing | Acme"`.\n- Page `status` accepts a fixed HTTP status code as a number from 200 through 599, for example `302`. For a dynamic status, pass JavaScript expression code such as `system.status`.\n- Page metadata update example: use `update-page` with `{"pageId":"page-id","values":{"title":"Pricing | Acme","meta":{"description":"Plans for teams"}}}`.\n- Draft a page with `update-page` and `{"pageId":"page-id","values":{"isDraft":true}}`. It remains editable and previewable but is omitted from every publish target, including staging, and from sitemap output.\n- Stage a draft page for a future publish with `{"pageId":"page-id","values":{"isDraft":false}}`. This clears draft state but does not deploy the site. The home page and `/*` catch-all page cannot be drafts.\n- Resource `url` accepts plain fixed URLs and paths. For computed URLs, pass JavaScript expression code such as `"https://api.example.com/items?tag=" + filters.tag`. Resource header values, search parameter values, and text bodies accept expressions for dynamic values; for fixed text, use `{ "type": "literal", "value": "application/json" }`.\n- Resource update example: use `update-resource` with `{"resourceId":"resource-id","values":{"url":"https://api.example.com/items"}}`.\n- Assets is one system resource with one response shape and always executes a structured query. `create-assets-resource` without `query` uses the default URL and optional image-dimensions output. Provide query configuration to control filtering, sorting, pagination, selected fields, or file content.\n- For a Markdown-backed blog, read `get-asset-field-catalog`, validate a structured query with `validate-asset-query`, then call `create-assets-resource` or `update-assets-resource`. Set `values.query:null` to restore the default query.\n- Optimize every explicit Assets query for the deployed content-database size. Use `output.mode:"fields"` and select only fields that are actually rendered or otherwise required by the query. Keep `includeMetadata:false` unless the rendered value needs file metadata; diagnostics are returned separately. Do not use `output.mode:"all"` as a convenience default.\n- Use a metadata-only Assets resource with `content.mode:"none"` for listings. Combine filters with `where.all` (AND) and `where.any` (OR). Use a separate Assets resource for the detail route with a slug or alternate-ID filter whose value is `system.params.slug`, `limit:1`, and `content.mode:"markdown-body"`. Request `full` content only when the whole source file is rendered; otherwise prefer `markdown-body` or a bounded byte range.\n- Markdown returned with `content.mode:"markdown-body"` resolves conventional relative links and images such as `../images/hero.png` to matching Assets. Markdown Embed permits sanitized figures, audio, video, and iframes, but removes scripts, inline event handlers, and unsafe URLs.\n- Assets expose an ID-keyed map at `<dataSourceName>.data` and collection information at `<dataSourceName>.meta`. Bind a listing Collection to `posts.data` and a one-result detail Collection to `post.data`; each item value contains selected fields and its item key is the asset ID. Read frontmatter or JSON fields from `item.properties`, the derived excerpt from `item.excerpt`, and requested Markdown from `item.content.text`.\n- Use `preview-asset-query` with concrete values before binding expressions in the saved resource. Inspect `__diagnostics__.usedBytes`, `maxBytes`, `unboundedBytes`, and `truncated`. When usage approaches the limit, first remove unused output fields, then narrow candidate files with filters, and finally reduce or remove embedded content. Inspect saved mode and configuration with `list-assets-resources` or `get-assets-resource`; shared index maintenance is automatic.\n- Data variable values support `string`, `number`, `boolean`, and `json`. Use `json` for all arrays, objects, filters, and nested data.\n- Parameters are internal scoped runtime values from pages, collections, or components. They are not a public authoring surface: do not create, update, or delete parameter records. Public tools should preserve existing parameter records and may reference documented context values such as `system` in expressions where they are already in scope.\n- Use scoped resources for read data. A GET resource created with `scopeInstanceId`/`dataSourceName` defaults to `exposeAsDataSource:true`, becomes a scoped resource data variable, is generated into the page resource `data` map, and may be loaded while rendering the page. Read the loaded resource result from its wrapper, usually `.data`.\n- Use prop-bound resources for actions. A resource created without `scopeInstanceId` and bound to a component prop such as Form `action` with `bind-props` and `binding.type: "resource"` becomes an action resource in the page resource `action` map. Use this for POST, PUT, DELETE, webhooks, GraphQL submissions, and anything that should run only from an explicit form/action flow.\n- POST, PUT, and DELETE resources default to `exposeAsDataSource:false`, even with a scope. Set `exposeAsDataSource:true` only for an intentional render-time read such as a GraphQL POST query; provide `scopeInstanceId` and inspect the returned warning. Set it to `false` during `update-resource` to detach existing render-time exposure.\n- For dynamic resource query parameters prefer `searchParams`, for example `{"name":"tag","value":"filters.tag"}`. Use `{"type":"literal","value":"website"}` for fixed request text. Header values can be expressions such as `"\\"Bearer \\" + auth.token"`. Body can be an object expression, including GraphQL payloads such as `{ query: "...", variables: { slug: system.params.slug } }`.\n- Resource methods are `get`, `post`, `put`, and `delete`. Optional resource controls are `graphql` and `system`. Use `control:"graphql"` for GraphQL POST resources with query bodies. Use `control:"system"` for built-in local resource URLs such as `"/$resources/current-date"` and for resources reading the built-in `system` parameter. The built-in system fields are `system.origin`, `system.pathname`, `system.params`, and `system.search`; do not use `system.path`.\n- Whenever an array or object from a resource or data variable should render repeated UI, call `insert-collection` with the complete iterable and one repeated-item JSX root. The command creates the Collection, private item parameters, iterable binding, and descendant item bindings atomically. Use `collectionItem` and `collectionItemKey` expressions in the item JSX. Wrap multiple repeated siblings in one Element, and give repeated Radix items stable unique `value` bindings.\n- Expressions are single JavaScript expressions, not statements or functions. Functions, arrow functions, classes, `new`, `this`, `await`, imports, arbitrary calls, increment/decrement, and assignment outside actions are unsupported. Prefer optional chaining, nullish coalescing, ternaries, property/index access, operators, and the documented string/array methods.\n\n## Pick Read Command\n\n{{readFirst}}\n\n## Pick Write Command\n\n{{taskRecipeIndex}}\n\n## Raw Patch Only If Needed\n\n1. Use MCP tool: snapshot.\n2. Write BuildPatchTransaction[].\n3. Use MCP tool: apply-patch.\n\n## MCP Argument Examples\n\nMCP tools receive JSON argument objects, not CLI flags. Use these shapes:\n\n{{mcpArgumentExampleIndex}}\n\n## Rules\n\n- Never guess ids for existing records. Read them first.\n- Never use project ids from user input. Commands use the configured project.\n- Use --refresh before a local-capable command when cached data may be stale.\n- Pass --json only to commands whose help/schema documents it. Do not add --json to top-level commands such as sync unless supported.\n- On VERSION_CONFLICT, read MCP snapshot again, regenerate the patch, then retry.\n- Treat stdout JSON as the API contract and stderr as diagnostics.\n- For visual/design work, verify the rendered result with vision before finishing.\n- Do not edit generated files for normal Webstudio content/design requests.\n- Use direct values for static strings and bindings only for dynamic expressions/resources/actions.\n- Use plain fixed text where documented. Only encode a quoted JavaScript string literal when a field is explicitly documented as an expression-only value.\n- Confirm destructive commands with --confirm only when user requested deletion/unpublish/replacement.\n- Use webstudio schema api for machine-readable top-level command metadata and webstudio schema mcp for MCP tool schemas.\n\n## Known Gaps\n\n{{knownCliGapIndex}}\n',
+ '# Webstudio CLI Manual for LLMs\n\nUse this order. Stop only when a command returns ok:false.\n\nIf you are inside the Webstudio monorepo, the first command discovery should use\nthe local CLI exactly as `node packages/cli/local.js ...` from the repo root. Do\nnot use `packages/cli/bin.js` for local source-tree work; it is the packaged\nbuild entry and may use stale built output. Do not use `pnpm exec webstudio`,\n`pnpm --filter webstudio exec webstudio`, or a global `webstudio`: they can\nresolve an older binary.\n\nFor delegated design-system or “use every component” tasks, skip the generic warm-up sequence and start with exactly one MCP command: `webstudio workflow.next \'{"goal":"design-system-page"}\'`. Report that returned checkpoint to the parent/user and stop until continued.\n\n## Use MCP locally or optionally connect a client\n\nDo not install, register, or connect an MCP server merely because the user asks\nyou to edit a Webstudio project. If Webstudio MCP tools are already available,\nuse them. If you have shell access, use the local CLI shortcuts such as\n`webstudio meta.index` and `webstudio list-pages`; they expose the same project\noperations without changing client configuration or restarting the app.\n\nOnly when the user explicitly asks for persistent native MCP integration, run\nthe command for their client:\n\n- Claude Code: `webstudio connect claude`\n- Codex: `webstudio connect codex`\n- Cursor: `webstudio connect cursor`\n- VS Code or GitHub Copilot: `webstudio connect vscode`\n\nRun project operations from the linked project root. If the folder is not\nlinked, ask for an editable Builder share link and run\n`webstudio init --link <share-link> --json`. You can then use local CLI\nshortcuts immediately. Do not run `webstudio sync`, `webstudio connect`, or\nrestart the app unless the user specifically wants native MCP registration:\nMCP reads and edits the latest editable Builder build directly, including for\nprojects that have never been published. Treat the share link as a credential\nand do not include it in committed files, logs, screenshots, or issue reports.\n\nThe optional `connect` command verifies project access before changing client configuration. For\nClaude Code, Cursor, and VS Code it safely merges the `webstudio` server into\nthe client\'s project configuration. For Codex it runs both `codex mcp add` and\n`codex mcp get webstudio`; do not repeat those commands separately. Follow the\nreload, restart, or approval instruction printed by `connect`, then verify the\nloaded MCP connection by asking the client to use Webstudio MCP and list the\nproject pages. Use `--print` only to inspect the generated setup without\nchanging configuration or requiring project access.\n\n## Always\n\n1. webstudio permissions --json\n2. For bounded shell workflows, call MCP tools directly through the CLI shortcut, for example `webstudio meta.index` or `webstudio insert-fragment \'<json>\' --dry-run`. The explicit form `webstudio mcp single-op-call <tool> \'<json>\'` is equivalent and useful when you need to make the MCP boundary obvious. Use `webstudio mcp run \'[{"tool":"components.find","input":{"brief":"button"}}]\'` for multiple calls in one shared CLI session. Use a normal JSON file path for large batches. Use long-running `webstudio mcp` only when your environment is a real MCP client. Do not manually send raw JSON-RPC to `webstudio mcp` from a shell or PTY.\n3. Read MCP `meta.index`, for example `webstudio meta.index`.\n4. Use focused MCP calls with concrete JSON: `webstudio meta.guide \'{"brief":"Create a design system page using every component"}\'`, `webstudio meta.get_more_tools \'{"tools":["insert-fragment"]}\'`, `webstudio components.list \'{"source":"all"}\'`, `webstudio components.coverage-plan`, `webstudio components.search \'{"brief":"radix select"}\'`, `webstudio components.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'`, `webstudio templates.list`, and `webstudio templates.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'`.\n5. Read overview resources `webstudio://project/tools-overview` or `webstudio://project/components-overview` when useful. Read full resources `webstudio://project/tools` or `webstudio://project/components` only when focused tools are insufficient.\n6. Pick focused MCP read tool.\n7. Pick semantic MCP write tool.\n\nUse `webstudio schema mcp` for a compact MCP tool overview. Add `--verbose` only when exact input schemas for all tools are truly needed; otherwise prefer focused `meta.get_more_tools` and `components.*` calls.\n\nRun these commands from the linked project root. Use the MCP startup status line\'s absolute root for local files; write temporary scripts and artifacts under `<project root>/.temp`, not under a parent workspace.\n\nMonorepo quick path for a simple styled section:\n\n```sh\nnode packages/cli/local.js mcp single-op-call meta.index\nnode packages/cli/local.js mcp single-op-call meta.get_more_tools \'{"tools":["insert-fragment"]}\'\nnode packages/cli/local.js mcp single-op-call insert-fragment \'{"parentInstanceId":"parent-id","fragment":"<ws.element ws:tag=\\"section\\" ws:style={css`padding: 32px; display: grid; gap: 12px;`}><ws.element ws:tag="h2">Launch Kit</ws.element><ws.element ws:tag="p">A focused section created with Webstudio JSX.</ws.element><ws.element ws:tag="button">Get started</ws.element></ws.element>"}\' --dry-run\n```\n\nThe same local shortcut form is shorter and preferred for simple shell steps:\n\n```sh\nnode packages/cli/local.js meta.index\nnode packages/cli/local.js meta.get_more_tools \'{"tools":["insert-fragment"]}\'\nnode packages/cli/local.js insert-fragment \'{"parentInstanceId":"parent-id","fragment":"<ws.element ws:tag=\\"section\\" ws:style={css`padding: 32px; display: grid; gap: 12px;`}><ws.element ws:tag="h2">Launch Kit</ws.element><ws.element ws:tag="p">A focused section created with Webstudio JSX.</ws.element><ws.element ws:tag="button">Get started</ws.element></ws.element>"}\' --dry-run\n```\n\nFor this simple path, do not grep source files, dump full MCP resources, or write parser scripts first. Use `list-pages`, `get-page-by-path`, or `list-instances` only to get the target `parentInstanceId`.\n\nWhen authoring JSX for `insert-fragment`, use Webstudio component helpers and Webstudio style syntax. Use `ws:style={css\\`...\\`}`for Webstudio-native CSS, or use React-style object syntax such as`style={{ padding: 24 }}` when that is simpler. Both forms create editable Webstudio style data.\n\nWhen the task says another user will edit a page in Content mode, use a Content Block (`ws:block`) around every editable region. Content-mode users can edit text and supported props only in descendants of that block; content outside it is read-only. Put reusable insertable options in the block\'s `ws:block-template` child. Do not put intended editor content inside that template container: templates are protected source material, while an inserted template copy becomes an editable direct child of the Content Block. Verify this structure before handoff.\n\nDo not access host globals or dynamic code APIs in JSX fragments, including `process`, `globalThis`, `eval`, `Function`, or `constructor`. JSX fragments are declarative project data; use the built-in Webstudio helpers instead.\n\nUse Webstudio prop names in JSX: `class`, `for`, `aria-label`, and other HTML/Webstudio names. Do not use React-only aliases such as `className` or `htmlFor`; the runtime rejects them with the Webstudio prop name to use.\n\nUse Webstudio actions for event/action props. Do not pass JavaScript functions such as `onClick={() => ...}`; the runtime rejects them because functions cannot be persisted as Webstudio project data.\n\n```tsx\n<ws.element\n ws:tag="button"\n onClick={new ActionValue(["event"], expression`console.log(event)`)}\n>\n Open\n</ws.element>\n```\n\nPlain JSX prop values must be JSON-compatible: `null`, strings, booleans, finite numbers, arrays, and plain objects. Do not pass `undefined`, `Symbol`, `BigInt`, `NaN`, `Infinity`, `Date`, `Map`, `Set`, class instances, or circular objects; omit the prop, use plain data, or use `expression`/`ActionValue` when the value is dynamic.\n\nIf a component has a registered template with required parts, JSX must include those parts explicitly under the same parent structure as the template, for example `<radix.Switch><radix.SwitchThumb /></radix.Switch>`. Use `insert-component` when you want Webstudio to apply one component template automatically.\n\n## Animation Components\n\nBefore creating animation examples, inspect the exact components with focused discovery:\n\n```sh\nwebstudio components.get \'{"component":"@webstudio-is/sdk-components-animation:AnimateChildren"}\'\nwebstudio components.get \'{"component":"@webstudio-is/sdk-components-animation:AnimateText"}\'\nwebstudio components.get \'{"component":"@webstudio-is/sdk-components-animation:StaggerAnimation"}\'\nwebstudio components.get \'{"component":"@webstudio-is/sdk-components-animation:VideoAnimation"}\'\n```\n\nUse Animation Group (`AnimateChildren`) as the controller. Put normal instances directly inside it, or put Text Animation, Stagger Animation, or Video Animation directly inside it. Text, Stagger, and Video are helper components with `contentModel.category: "none"` and should not be used as standalone section roots.\n\nDefine timing and CSS changes on the Animation Group `action` prop. Use `type:"view"` for viewport entry/exit progress and `type:"scroll"` for scroll-progress timelines. For in animations, keep the canvas styles as the final state and use `fill:"backwards"` with keyframes that describe the starting state. For out animations, use `fill:"forwards"` with keyframes that describe the ending state.\n\nText Animation settings: `slidingWindow` defaults to `5`, `easing` defaults to `linear`, and `splitBy` defaults to `char`. Use `splitBy:"space"` for word-by-word animation. The parent Animation Group keyframes provide the actual opacity, translate, scale, or other styles.\n\nStagger Animation settings: `slidingWindow` defaults to `1` and `easing` defaults to `linear`. It applies parent Animation Group progress across its direct children. Use `slidingWindow:0` for instant sequential steps, `1` for one child at a time, and values above `1` for overlapping waves.\n\nVideo Animation settings: `timeline` is a boolean. Prefer `insert-component` for Video Animation so the Video child template is inserted, then configure the Video child asset/source. Use short, seek-friendly videos for smooth scroll-linked playback.\n\nUse JSX fragments for authored animation structures when you need styled, editable examples. Put the final visual state in `ws:style` and put the starting or ending animated state in the Animation Group `action` keyframes. Include an explicit `offset` on every keyframe: use `offset: 0` for starting-state keyframes with `fill:"backwards"` and `offset: 1` for ending-state keyframes with `fill:"forwards"`.\n\n```tsx\n<animation.AnimateChildren\n action={{\n type: "view",\n axis: "block",\n animations: [\n {\n name: "Fade up on entry",\n timing: {\n fill: "backwards",\n rangeStart: ["entry", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["entry", { type: "unit", value: 100, unit: "%" }],\n },\n keyframes: [\n {\n offset: 0,\n styles: {\n opacity: { type: "unit", value: 0, unit: "number" },\n translate: {\n type: "tuple",\n value: [\n { type: "unit", value: 0, unit: "number" },\n { type: "unit", value: 24, unit: "px" },\n ],\n },\n },\n },\n ],\n },\n ],\n }}\n>\n <ws.element\n ws:tag="section"\n ws:style={css`\n display: grid;\n gap: 16px;\n padding: 48px;\n border-radius: 24px;\n background: #111827;\n color: white;\n `}\n >\n <ws.element ws:tag="h2">Launch metrics</ws.element>\n <ws.element ws:tag="p">\n A polished card that fades up as it enters the viewport.\n </ws.element>\n </ws.element>\n</animation.AnimateChildren>\n```\n\nFor Text Animation, keep `animation.AnimateText` as the direct child of Animation Group and place the text-containing element inside it:\n\n```tsx\n<animation.AnimateChildren\n action={{\n type: "view",\n animations: [\n {\n name: "Parallax In",\n timing: {\n fill: "backwards",\n rangeStart: ["cover", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["cover", { type: "unit", value: 70, unit: "%" }],\n },\n keyframes: [\n {\n offset: 0,\n styles: {\n translate: {\n type: "tuple",\n value: [\n { type: "unit", value: 0, unit: "number" },\n { type: "unit", value: 100, unit: "px" },\n ],\n },\n },\n },\n ],\n },\n {\n name: "Opacity In",\n timing: {\n fill: "backwards",\n rangeStart: ["cover", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["cover", { type: "unit", value: 70, unit: "%" }],\n },\n keyframes: [\n {\n offset: 0,\n styles: {\n opacity: { type: "unit", value: 0, unit: "number" },\n },\n },\n ],\n },\n {\n name: "Scale In",\n timing: {\n fill: "backwards",\n rangeStart: ["cover", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["cover", { type: "unit", value: 70, unit: "%" }],\n },\n keyframes: [\n {\n offset: 0,\n styles: {\n scale: {\n type: "tuple",\n value: [\n { type: "unit", value: 5, unit: "number" },\n { type: "unit", value: 5, unit: "number" },\n ],\n },\n },\n },\n ],\n },\n {\n name: "Parallax Out",\n timing: {\n fill: "forwards",\n rangeStart: ["cover", { type: "unit", value: 50, unit: "%" }],\n rangeEnd: ["cover", { type: "unit", value: 100, unit: "%" }],\n },\n keyframes: [\n {\n offset: 1,\n styles: {\n translate: {\n type: "tuple",\n value: [\n { type: "unit", value: 0, unit: "number" },\n { type: "unit", value: -100, unit: "px" },\n ],\n },\n scale: {\n type: "tuple",\n value: [\n { type: "unit", value: 5, unit: "number" },\n { type: "unit", value: 5, unit: "number" },\n ],\n },\n opacity: { type: "unit", value: 0, unit: "number" },\n },\n },\n ],\n },\n ],\n insetStart: { type: "unit", value: 5, unit: "%" },\n insetEnd: { type: "unit", value: 5, unit: "%" },\n isPinned: true,\n }}\n>\n <animation.AnimateText\n splitBy="space"\n slidingWindow={5}\n easing="easeOutQuart"\n >\n <ws.element ws:tag="h2">Animate words with controlled rhythm</ws.element>\n </animation.AnimateText>\n</animation.AnimateChildren>\n```\n\nFor Stagger Animation, put the repeated cards or rows directly inside `animation.StaggerAnimation`:\n\n```tsx\n<animation.AnimateChildren\n action={{\n type: "view",\n animations: [\n {\n timing: {\n fill: "backwards",\n rangeStart: ["contain", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["contain", { type: "unit", value: 30, unit: "%" }],\n },\n keyframes: [\n {\n offset: 0,\n styles: {\n opacity: { type: "unit", value: 0, unit: "number" },\n },\n },\n ],\n },\n ],\n }}\n>\n <animation.StaggerAnimation>\n <ws.element\n ws:tag="article"\n ws:style={css`\n padding: 20px;\n border: 1px solid #d1d5db;\n border-radius: 16px;\n `}\n >\n Plan\n </ws.element>\n <ws.element\n ws:tag="article"\n ws:style={css`\n padding: 20px;\n border: 1px solid #d1d5db;\n border-radius: 16px;\n `}\n >\n Build\n </ws.element>\n <ws.element\n ws:tag="article"\n ws:style={css`\n padding: 20px;\n border: 1px solid #d1d5db;\n border-radius: 16px;\n `}\n >\n Launch\n </ws.element>\n </animation.StaggerAnimation>\n</animation.AnimateChildren>\n```\n\nFor Video Animation, use the registered template via `insert-component` when possible. If you author JSX, include the Video child explicitly:\n\n```tsx\n<animation.AnimateChildren\n action={{\n type: "view",\n animations: [\n {\n name: "Video progress",\n timing: {\n fill: "both",\n rangeStart: ["cover", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["cover", { type: "unit", value: 100, unit: "%" }],\n },\n keyframes: [{ offset: 0, styles: {} }],\n },\n ],\n }}\n>\n <animation.VideoAnimation timeline={true}>\n <$.Video\n preload="auto"\n autoPlay={true}\n muted={true}\n playsInline={true}\n crossOrigin="anonymous"\n />\n </animation.VideoAnimation>\n</animation.AnimateChildren>\n```\n\n## Command Surface Boundary\n\n- Use top-level `webstudio ...` shell commands for setup, sync/import/build/preview/screenshot, permissions, publish/domains, schema, registry inspection, man, and starting MCP.\n- Use MCP tools for Builder project data manipulation: pages, instances/components, props, text, styles, tokens, variables, resources, assets, breakpoints, redirects, and raw patches.\n- From a shell, call MCP tools with the shortcut form `webstudio <tool> \'<json>\'`, for example `webstudio insert-fragment \'<json>\' --dry-run`. The explicit equivalent is `webstudio mcp single-op-call <tool> \'<json>\'`. Use `--input-file` for large payloads.\n- Inside the Webstudio monorepo, call the local CLI as its own command: `node packages/cli/local.js ...`. Do not wrap the CLI call in `pwd && ...`, command substitution, `pnpm exec webstudio`, `pnpm --filter webstudio exec webstudio`, or a global `webstudio`.\n- For experiments, pass `--dry-run` to local-capable mutation calls. Read the computed transaction from `meta.session.transaction` and its base build version from `meta.session.version`. Copying a `.webstudio` folder is not an isolated project clone; `.webstudio/config.json` still points to the same remote project, so non-dry-run mutations can commit to that project.\n- For bounded multi-step shell work, run inline JSON with `webstudio mcp run \'[{"tool":"components.find","input":{"brief":"button"}}]\'`; this reuses one CLI session without raw JSON-RPC. For large batches, write `{ "calls": [{ "tool": "..." }] }` to a normal JSON file and run `webstudio mcp run .temp/mcp-calls.json`.\n- Use JSON strings for `brief` fields. Never pass boolean flags such as `{"brief":true}`.\n- Treat `webstudio mcp single-op-call` and `webstudio mcp run` stderr lines as progress checkpoints; stdout remains JSON on both success and failure. On failure, parse stdout for `{ "ok": false, "error": { "code": "...", "message": "..." } }` before deciding what to fix.\n- If a CLI/MCP tool crashes, hangs, gives a confusing error, needs an undocumented workaround, or forces source-code inspection for normal usage, ask the user to report it in Discord `#help` at https://wstd.us/community. Give them a complete copy-paste report with the goal, expected behavior, actual error, exact command/tool call, stdout JSON, stderr/lifecycle logs, environment, workaround, and secrets redacted.\n- Run one-shot `webstudio mcp single-op-call` commands sequentially against a linked `.webstudio` folder. If a command returns `PROJECT_SESSION_BUSY`, another CLI/MCP process is updating the local session; wait a moment and retry sequentially.\n- In delegated or non-streaming agent environments, do not batch many MCP calls silently and do not wrap many shortcut or `webstudio mcp single-op-call` commands in a shell loop. Treat each parent-visible checkpoint as the unit of work. If the parent asks for status within 30 seconds, run exactly one shortcut command such as `webstudio meta.index` or one explicit `webstudio mcp single-op-call` command, report that command/result, then wait for the parent to continue. Do not take a broad task such as creating a full design-system page as one execution unit. Call `workflow.next {"goal":"design-system-page"}`, report the returned phase/checkpoint, wait until the parent continues, call `checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}`, complete exactly that bounded phase, and return: discovery, page creation, one dry-run JSX section, one committed JSX section, one `components.coverage-insert-next` call, or one presentation pass. Phase commands do not include nextPhase in their own output. After the parent continues, acknowledge the previous checkpoint first, then call `workflow.next` with the next phase. For all-component design-system pages, checkpoint after workflow planning, discovery, page creation, call `components.coverage-insert-next` once before checkpointing again, then finish with `workflow.next {"goal":"design-system-page","phase":"presentation-pass"}`. Coverage 72/72 is necessary but not sufficient: the page must be organized into styled, real-world examples, not raw unstyled component dumps.\n- For design-system or “use every component” tasks, start with compact `webstudio components.coverage-plan`, checkpoint, then request component coverage details with `webstudio components.coverage-plan \'{"detail":"roots","offset":20}\'` or `{"detail":"parts"}` only when needed. Do not pass `detail` to `list-pages`; use `list-pages {}` or `get-page-by-path` for page lookup.\n- MCP tool shortcuts are only for MCP tools. If a shortcut is ambiguous with a real top-level command, the real top-level command wins; use `webstudio mcp single-op-call <tool> \'<json>\'` to force the MCP path.\n\n## LLM Implementation Process\n\nUse this process for user requests that change Webstudio content, layout, styles, assets, pages, redirects, resources, or publishing state:\n\n1. Discover capabilities with `webstudio man --json`, `webstudio schema api`, `webstudio schema mcp`, MCP `meta.index`, `meta.guide`, `meta.get_more_tools`, `components.list`, `components.summary`, `components.coverage-plan`, `components.search`, `components.get`, `templates.list`, and `templates.get`. From a shell, prefer shortcut calls such as `webstudio meta.index` and `webstudio components.search \'{"brief":"button"}\'` for these focused tool calls; use `webstudio mcp single-op-call` when you need the explicit MCP form. Read full resources such as `webstudio://project/tools` and `webstudio://project/components` only when needed. Do not write scripts to parse full MCP discovery JSON for normal lookup.\n2. Inspect current project state with semantic reads such as `get-project-settings`, `list-pages`, `get-page-by-path`, `list-instances`, `inspect-instance`, `get-styles`, `list-assets`, `list-breakpoints`, and `snapshot` only when needed. Before changing a project, read `get-project-settings` and follow any non-empty `meta.agentInstructions`. These are shared project instructions, not a place for secrets.\n3. Mutate the Webstudio project with semantic MCP write tools first. Prefer MCP `insert-fragment` for authored/styled sections, use `insert-component` only for one automatic component template, then `update-text`, `update-props`, `update-styles`, `upload-asset`, `create-page`, and page/project settings tools over raw patches.\n4. Use `apply-patch` only when no semantic tool covers the required change, and only after reading the latest snapshot/version.\n5. For visual/design work, regenerate or preview the generated app, capture a screenshot, inspect it with vision, and iterate before final response.\n6. Report what changed and what verification ran.\n\n## Visual Design Workflow\n\nFor requests involving visible HTML/CSS, layout, typography, colors, imagery, responsive behavior, or screenshots:\n\n1. Read editable Webstudio structure first: pages, instances, props, styles, breakpoints, assets, and relevant text.\n2. Do not use generated route/component files as the source of truth for editable content.\n3. Make edits through Webstudio semantic commands/MCP tools so the result stays editable in Builder and survives the next `webstudio build`.\n4. Keep generated project files current, start preview, and capture the changed page with `screenshot`.\n5. Use `screenshot.diff` when a baseline exists and inspect screenshot/diff artifacts with vision before finishing.\n6. If vision or screenshot tooling is unavailable, state that explicitly and explain what fallback verification was used.\n\n## Responsive Verification Workflow\n\nFor responsive page work, use Builder breakpoints as the source of truth:\n\n1. Read breakpoints with `list-breakpoints` before deciding responsive behavior.\n2. Apply responsive styles with existing Builder breakpoint ids; do not invent CSS media queries or breakpoint names when Webstudio breakpoint data exists.\n3. Pick screenshot viewport widths from the project breakpoints: include a desktop width, each defined max-width or min-width edge, and a narrow mobile width.\n4. Capture each viewport with `screenshot`, for example `{"path":"/","output":"home-375.png","viewport":{"width":375,"height":812}}` and `{"path":"/","output":"home-1440.png","viewport":{"width":1440,"height":900}}`.\n5. Inspect every viewport screenshot with vision before finishing, checking layout, overflow, hidden content, text wrapping, and breakpoint-specific style changes.\n6. If any viewport fails, update styles through semantic Webstudio tools and repeat screenshots for the affected breakpoints.\n\n## Generated Files Guardrails\n\n- Do not edit `app/__generated__`, generated route files, generated page files, generated CSS, or build output for normal Webstudio content/design requests.\n- Do not replace generated page components with handcrafted app code unless the user explicitly asks for code-only export customization.\n- Generated files are build artifacts and may be overwritten by `webstudio build`.\n- If a task truly requires generated app customization, keep it outside `app/__generated__` where possible and explain that it is not editable Webstudio content.\n\n## Values vs Bindings\n\nBefore authoring unfamiliar expressions, read `webstudio://project/expressions` with MCP `resources/read` or `webstudio mcp read-resource webstudio://project/expressions`. It documents the supported expression subset, method allowlist, scope, Collection context, and validation limits.\n\n- Use direct value tools for fixed content. For one visible text child, use `update-text` with plain `text`. For a bounded multi-instance literal replacement, use `replace-text` with `find`, `replace`, `pagePath` or `pageId`, and `limit`; it does not change expression children. Use `replace-prop-text` for bounded changes inside static string props, optionally limited to prop names or instance ids; it never changes dynamic bindings. For static props such as `aria-label`, `alt`, `id`, `class`, `href`, or button labels stored as props, use `update-props` with the prop\'s direct type/value.\n- Use `bind-props` only when the prop must stay dynamic: an expression, resource result, action, or existing scoped runtime context such as `system`. Do not use `bind-props` just to set a fixed string.\n- Direct prop string example: `{"updates":[{"instanceId":"button-id","name":"aria-label","type":"string","value":"Open menu"}]}`.\n- Expression binding example: `{"bindings":[{"instanceId":"link-id","name":"href","binding":{"type":"expression","value":"currentPost.url"}}]}`.\n- Page metadata fields such as `title`, `description`, `language`, `redirect`, and custom meta content accept plain fixed text. For computed values, pass JavaScript expression code such as `pageTitle ?? "Pricing | Acme"`.\n- Page `status` accepts a fixed HTTP status code as a number from 200 through 599, for example `302`. For a dynamic status, pass JavaScript expression code such as `system.status`.\n- Page metadata update example: use `update-page` with `{"pageId":"page-id","values":{"title":"Pricing | Acme","meta":{"description":"Plans for teams"}}}`.\n- Draft a page with `update-page` and `{"pageId":"page-id","values":{"isDraft":true}}`. It remains editable and previewable but is omitted from every publish target, including staging, and from sitemap output.\n- Stage a draft page for a future publish with `{"pageId":"page-id","values":{"isDraft":false}}`. This clears draft state but does not deploy the site. The home page and `/*` catch-all page cannot be drafts.\n- Resource `url` accepts plain fixed URLs and paths. For computed URLs, pass JavaScript expression code such as `"https://api.example.com/items?tag=" + filters.tag`. Resource header values, search parameter values, and text bodies accept expressions for dynamic values; for fixed text, use `{ "type": "literal", "value": "application/json" }`.\n- Resource update example: use `update-resource` with `{"resourceId":"resource-id","values":{"url":"https://api.example.com/items"}}`.\n- Assets is one system resource with one response shape and always executes a structured query. `create-assets-resource` without `query` uses the default URL and optional image-dimensions output. Provide query configuration to control filtering, sorting, pagination, selected fields, or file content.\n- For a Markdown-backed blog, create exactly two Builder page definitions: a fixed `/blog` overview and one `/blog/:slug` detail page. Both pages load content through Assets resources. Never create one Builder page per post or duplicate Markdown content into static page structures. Read `get-asset-field-catalog`, validate each structured query with `validate-asset-query`, then call `create-assets-resource` or `update-assets-resource`. Set `values.query:null` to restore the default query.\n- Optimize every explicit Assets query for the deployed content-database size. Use `output.mode:"fields"` and select only fields that are actually rendered or otherwise required by the query. Keep `includeMetadata:false` unless the rendered value needs file metadata; diagnostics are returned separately. Do not use `output.mode:"all"` as a convenience default.\n- Use a metadata-only Assets resource with `content.mode:"none"` for the `/blog` listing. Combine filters with `where.all` (AND) and `where.any` (OR). Give both blog queries static Markdown and folder/path constraints, including `extension = md`, so dynamic route compilation cannot pull images or unrelated files into the database. Use a separate Assets resource for `/blog/:slug` with those same static constraints plus a slug or alternate-ID filter whose value is `system.params.slug`, `limit:1`, and `content.mode:"markdown-body"`. Request `full` content only when the whole source file is rendered; otherwise prefer `markdown-body` or a bounded byte range.\n- Markdown returned with `content.mode:"markdown-body"` resolves conventional relative links and images such as `../images/hero.png` to matching Assets. Markdown Embed permits sanitized figures, audio, video, and iframes, but removes scripts, inline event handlers, and unsafe URLs.\n- Assets expose an ID-keyed map at `<dataSourceName>.data` and collection information at `<dataSourceName>.meta`. Bind a listing Collection to `posts.data` and a one-result detail Collection to `post.data`; each item value contains selected fields and its item key is the asset ID. Read frontmatter or JSON fields from `item.properties`, the derived excerpt from `item.excerpt`, and requested Markdown from `item.content.text`.\n- Use `preview-asset-query` with concrete values before binding expressions in the saved resource. Inspect `__diagnostics__.query` for the temporary query-only footprint and `__diagnostics__.database` for the merged database built from all reachable Assets queries. Only `database.usedBytes` counts toward `database.maxBytes`; query sizes are not separate allowances and must not be summed. Compare `usedBytes`, `unboundedBytes`, and `truncated` within both scopes. When merged usage approaches the limit, first remove unused output fields, then narrow candidate files with filters, and finally reduce or remove embedded content. Inspect saved mode and configuration with `list-assets-resources` or `get-assets-resource`; shared index maintenance is automatic.\n- Data variable values support `string`, `number`, `boolean`, and `json`. Use `json` for all arrays, objects, filters, and nested data.\n- Parameters are internal scoped runtime values from pages, collections, or components. They are not a public authoring surface: do not create, update, or delete parameter records. Public tools should preserve existing parameter records and may reference documented context values such as `system` in expressions where they are already in scope.\n- Use scoped resources for read data. A GET resource created with `scopeInstanceId`/`dataSourceName` defaults to `exposeAsDataSource:true`, becomes a scoped resource data variable, is generated into the page resource `data` map, and may be loaded while rendering the page. Read the loaded resource result from its wrapper, usually `.data`.\n- Use prop-bound resources for actions. A resource created without `scopeInstanceId` and bound to a component prop such as Form `action` with `bind-props` and `binding.type: "resource"` becomes an action resource in the page resource `action` map. Use this for POST, PUT, DELETE, webhooks, GraphQL submissions, and anything that should run only from an explicit form/action flow.\n- POST, PUT, and DELETE resources default to `exposeAsDataSource:false`, even with a scope. Set `exposeAsDataSource:true` only for an intentional render-time read such as a GraphQL POST query; provide `scopeInstanceId` and inspect the returned warning. Set it to `false` during `update-resource` to detach existing render-time exposure.\n- For dynamic resource query parameters prefer `searchParams`, for example `{"name":"tag","value":"filters.tag"}`. Use `{"type":"literal","value":"website"}` for fixed request text. Header values can be expressions such as `"\\"Bearer \\" + auth.token"`. Body can be an object expression, including GraphQL payloads such as `{ query: "...", variables: { slug: system.params.slug } }`.\n- Resource methods are `get`, `post`, `put`, and `delete`. Optional resource controls are `graphql` and `system`. Use `control:"graphql"` for GraphQL POST resources with query bodies. Use `control:"system"` for built-in local resource URLs such as `"/$resources/current-date"` and for resources reading the built-in `system` parameter. The built-in system fields are `system.origin`, `system.pathname`, `system.params`, and `system.search`; do not use `system.path`.\n- Whenever an array or object from a resource or data variable should render repeated UI, call `insert-collection` with the complete iterable and one repeated-item JSX root. The command creates the Collection, private item parameters, iterable binding, and descendant item bindings atomically. Use `collectionItem` and `collectionItemKey` expressions in the item JSX. Wrap multiple repeated siblings in one Element, and give repeated Radix items stable unique `value` bindings.\n- Expressions are single JavaScript expressions, not statements or functions. Functions, arrow functions, classes, `new`, `this`, `await`, imports, arbitrary calls, increment/decrement, and assignment outside actions are unsupported. Prefer optional chaining, nullish coalescing, ternaries, property/index access, operators, and the documented string/array methods.\n\n## Pick Read Command\n\n{{readFirst}}\n\n## Pick Write Command\n\n{{taskRecipeIndex}}\n\n## Raw Patch Only If Needed\n\n1. Use MCP tool: snapshot.\n2. Write BuildPatchTransaction[].\n3. Use MCP tool: apply-patch.\n\n## MCP Argument Examples\n\nMCP tools receive JSON argument objects, not CLI flags. Use these shapes:\n\n{{mcpArgumentExampleIndex}}\n\n## Rules\n\n- Never guess ids for existing records. Read them first.\n- Never use project ids from user input. Commands use the configured project.\n- Use --refresh before a local-capable command when cached data may be stale.\n- Pass --json only to commands whose help/schema documents it. Do not add --json to top-level commands such as sync unless supported.\n- On VERSION_CONFLICT, read MCP snapshot again, regenerate the patch, then retry.\n- Treat stdout JSON as the API contract and stderr as diagnostics.\n- For visual/design work, verify the rendered result with vision before finishing.\n- Do not edit generated files for normal Webstudio content/design requests.\n- Use direct values for static strings and bindings only for dynamic expressions/resources/actions.\n- Use plain fixed text where documented. Only encode a quoted JavaScript string literal when a field is explicitly documented as an expression-only value.\n- Confirm destructive commands with --confirm only when user requested deletion/unpublish/replacement.\n- Use webstudio schema api for machine-readable top-level command metadata and webstudio schema mcp for MCP tool schemas.\n\n## Known Gaps\n\n{{knownCliGapIndex}}\n',
"manual-mcp":
'# Webstudio MCP Manual\n\n`webstudio mcp` starts a stdio MCP server for real MCP clients. Shell users can call MCP tools with the shortcut form `webstudio <tool> \'<json>\'`, for example `webstudio meta.index` or `webstudio insert-fragment \'<json>\' --dry-run`. `webstudio mcp single-op-call` is the explicit equivalent and prints the structured JSON result. `webstudio mcp run` runs multiple MCP tool calls from inline JSON or a normal JSON file in one shared CLI session. Do not manually type or pipe raw JSON-RPC frames into `webstudio mcp` from an interactive shell or PTY.\n\n## Startup\n\nIf you are already working with a shell-capable agent, it can use the local CLI\ndirectly. Native MCP client registration is optional. Give the editable Builder\nshare link only when the trusted agent asks for it. Treat the share link as a\ncredential: do not include it in committed files, screenshots, logs, or issue\nreports.\n\n1. Configure a project with `webstudio init --link <api-share-link> --json`.\n2. Check capabilities with `webstudio permissions --json`.\n3. Use shortcut calls such as `webstudio meta.index` and `webstudio insert-fragment \'<json>\' --dry-run` for individual MCP tool calls. Use the explicit equivalent `webstudio mcp single-op-call <tool> \'<json>\'` when you need to force the MCP path, or `webstudio mcp run \'[{"tool":"components.find","input":{"brief":"button"}}]\'` for bounded multi-call workflows. Use `webstudio mcp run .temp/mcp-calls.json` for large batches.\n4. Start discovery with `meta.index`, then call focused tools with concrete JSON, for example `webstudio mcp single-op-call meta.guide \'{"brief":"Create a design system page using every component"}\'`.\n\nDo not run `webstudio sync`, install an MCP server, change client configuration,\nor restart the app for this local CLI workflow.\n\nWhen the user explicitly wants persistent native MCP integration, run\n`webstudio connect claude`, `webstudio connect codex`, `webstudio connect\ncursor`, or `webstudio connect vscode`. This optional command changes client\nconfiguration, so follow its client-specific reload or restart instruction.\nUse `--print` to inspect the generated setup without changing configuration or\nrequiring project access. For Codex, `connect` registers and verifies the server\nthrough the Codex CLI. Before changing client configuration, `connect` verifies\nthat the saved project endpoint is reachable and its credential is accepted.\n\nStart MCP from the linked Webstudio project root. The lifecycle status line prints that absolute root; create local scripts, screenshots, and temporary artifacts under that root, for example `<project root>/.temp/script.mjs`. If the shell starts in a parent workspace, `cd` into the project root first or use absolute paths.\n\nWhen developing inside the Webstudio monorepo, start the local CLI exactly as `node packages/cli/local.js mcp` from the repo root. Do not use `pnpm exec webstudio`, `pnpm --filter webstudio exec webstudio`, or a global `webstudio`: they can resolve an older binary.\n\nWhile the server is running, stdout is reserved for MCP JSON-RPC messages. Do not print human text from the server process. The server advertises MCP `logging` capability and emits sparse `notifications/message` logs for ready state and tool lifecycle checkpoints such as `tool preview.start started`, `tool preview.start still running after 10000ms`, and `tool preview.start succeeded in 1234ms`; stderr also mirrors these sparse lifecycle fallback lines prefixed with `[webstudio mcp]`.\n\n## One-Shot Tool Calls\n\nUse the shortcut `webstudio <tool> \'<json>\'` when you are operating from a shell and need one MCP tool result. The explicit form `webstudio mcp single-op-call <tool> \'<json>\'` is equivalent and avoids writing temporary Node.js stdio client scripts.\n\nExamples:\n\n```sh\nwebstudio mcp single-op-call meta.index\nwebstudio mcp single-op-call meta.guide \'{"brief":"Create a design system page using every component"}\'\nwebstudio mcp single-op-call meta.get_more_tools \'{"tools":["insert-fragment"]}\'\nwebstudio mcp single-op-call components.list \'{"source":"all"}\'\nwebstudio mcp single-op-call components.coverage-plan\nwebstudio mcp single-op-call components.search \'{"brief":"radix select"}\'\nwebstudio mcp single-op-call components.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'\nwebstudio mcp single-op-call templates.list\nwebstudio mcp single-op-call templates.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'\nwebstudio mcp single-op-call insert-fragment --input-file .temp/insert-fragment.json\n```\n\nShortcut equivalents:\n\n```sh\nwebstudio meta.index\nwebstudio meta.guide \'{"brief":"Create a design system page using every component"}\'\nwebstudio meta.get_more_tools \'{"tools":["insert-fragment"]}\'\nwebstudio components.list \'{"source":"all"}\'\nwebstudio components.coverage-plan\nwebstudio components.search \'{"brief":"radix select"}\'\nwebstudio components.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'\nwebstudio templates.list\nwebstudio templates.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'\nwebstudio insert-fragment --input-file .temp/insert-fragment.json\n```\n\nRules:\n\n- Inside the Webstudio monorepo, replace `webstudio` in the examples above with `node packages/cli/local.js`, for example `node packages/cli/local.js meta.index`.\n- For a simple authored/styled section, run `meta.index`, then `meta.get_more_tools \'{"tools":["insert-fragment"]}\'`, then `insert-fragment`. Do not grep source files, dump full MCP resources, or write parser scripts first.\n- In `insert-fragment` JSX, use `ws:style={css\\`...\\`}`for Webstudio-native CSS, or use React-style object syntax such as`style={{ padding: 24 }}` when that is simpler. Both forms create editable Webstudio style data.\n- Prefer JSX for authored/styled content. Common `insert-fragment` inputs:\n\n```jsonl\n{"parentInstanceId":"root-id","fragment":"<ws.element ws:tag=\\"section\\" ws:style={css`padding: 32px; display: grid; gap: 16px;`}><ws.element ws:tag="h2">Northstar Product OS</ws.element><ws.element ws:tag="p">Reusable patterns for teams.</ws.element></ws.element>"}\n{"parentInstanceId":"root-id","fragment":"<ws.element ws:tag=\\"section\\" style={{ padding: 32, borderRadius: 16 }}><ws.element ws:tag="h2">Operations Console</ws.element><ws.element ws:tag="p">React-style object styles become editable Webstudio styles.</ws.element></ws.element>"}\n{"parentInstanceId":"root-id","fragment":"<ws.element ws:tag=\\"section\\" ws:tokens={[token(\\"accent\\", css`color: #0f766e;`)]}><ws.element ws:tag="button" onClick={new ActionValue([\\"event\\"], expression`console.log(event)`)}>Track launch</ws.element></ws.element>"}\n{"parentInstanceId":"root-id","fragment":"<ws.element ws:tag=\\"section\\"><radix.Switch><radix.SwitchThumb /></radix.Switch></ws.element>"}\n```\n\n- Do not access host globals or dynamic code APIs in JSX fragments, including `process`, `globalThis`, `eval`, `Function`, or `constructor`.\n- Use Webstudio prop names such as `class` and `for`; do not use React aliases `className` or `htmlFor`.\n- Use Webstudio actions for event/action props, for example `onClick={new ActionValue(["event"], expression\\`console.log(event)\\`)}`. Do not pass JavaScript functions such as `onClick={() => ...}`.\n- Plain prop values must be JSON-compatible: `null`, strings, booleans, finite numbers, arrays, and plain objects. Do not pass `undefined`, `Symbol`, `BigInt`, `NaN`, `Infinity`, `Date`, `Map`, `Set`, class instances, or circular objects; omit the prop, use plain data, or use `expression`/`ActionValue` when the value is dynamic.\n- Template-backed components used in JSX must include required child/part components explicitly under the same parent structure as the template, for example `<radix.Switch><radix.SwitchThumb /></radix.Switch>`. Use `insert-component` when you want one automatic registered component template.\n- The positional input is JSON and defaults to `{}`.\n- Use `--input-file` for large mutation payloads.\n- Use `--dry-run` with local-capable mutation tools when you need a patch plan without committing. The computed transaction is returned in `meta.session.transaction`, and `meta.session.version` is its base build version. Copying a `.webstudio` folder is not an isolated project clone; `.webstudio/config.json` still points to the same remote project, so non-dry-run mutations can commit to that project.\n- The command prints JSON to stdout for both success and failure. Success uses the same `structuredContent` shape MCP tools return: `{ "ok": true, "data": ..., "meta": ... }`. Failure prints `{ "ok": false, "error": { "code": "...", "message": "..." }, "meta": ... }` and exits nonzero.\n- The command writes sparse progress to stderr, including start, success/failure, elapsed time, and committed status when the tool returns session metadata.\n- Invalid argument types fail loudly with path-specific messages, for example `meta.guide input.brief must be a string when provided`.\n- Run one-shot shortcut or `mcp single-op-call` commands sequentially against the same linked `.webstudio` folder. If you receive `PROJECT_SESSION_BUSY`, another CLI/MCP process is updating the local session; wait a moment and retry sequentially.\n- To work with another previously linked project without changing the directory\'s default link, start MCP or a shell call with `--project <projectId>`, for example `webstudio mcp --project <projectId>` or `webstudio mcp single-op-call list-pages --project <projectId>`. Selected projects use isolated local session and checkpoint files.\n- If you are a delegated agent and your parent cannot see live stderr/stdout, do not run a long sequence of shortcut or `mcp single-op-call` commands silently and do not wrap many calls in a shell loop. Treat each parent-visible checkpoint as the unit of work. If the parent asks for status within 30 seconds, run exactly one `webstudio <tool>` or `webstudio mcp single-op-call` command, report that command/result, then wait before the next MCP command. For all-component design-system pages, checkpoint after discovery, checkpoint after page creation, call `components.coverage-insert-next` once before checkpointing again, then finish with the `presentation-pass` workflow phase. Coverage alone is not completion; organize examples into styled sections/cards.\n\n## Reporting CLI/MCP Issues\n\nIf a CLI/MCP tool gives a confusing error, crashes, hangs, produces invalid output, requires an undocumented workaround, or makes you inspect source code to understand normal usage, ask the user to report it in the Webstudio Discord `#help` channel: https://wstd.us/community.\n\nGive the user a complete copy-paste report. Include only non-secret values: never include auth tokens, private URLs, cookies, API keys, passwords, or proprietary project data. Redact them as `<redacted>`.\n\nCopy-paste template:\n\n````md\nWebstudio CLI/MCP issue report\n\nWhat I was trying to do:\n<short user goal, for example "Create a resource from an external API and render it in a collection">\n\nWhat I expected:\n<what should have happened>\n\nWhat happened instead:\n<exact error, confusing behavior, hang, missing docs, or workaround required>\n\nCommand/tool used:\n\n```sh\n<exact command or MCP tool call, with tokens/secrets redacted>\n```\n\nStructured output / error:\n\n```json\n<stdout JSON or MCP structuredContent, if available, with secrets redacted>\n```\n\nStderr / lifecycle logs:\n\n```txt\n<stderr lines, timings, checkpoint messages, or stack trace, with secrets redacted>\n```\n\nEnvironment:\n\n- CLI command path: <webstudio / node packages/cli/local.js / other>\n- Webstudio CLI version: <from command output if known>\n- OS: <macOS / Windows / Linux / unknown>\n- Node version: <node -v if known>\n- Project/session state: <linked project, local .webstudio session, preview, MCP server, or unknown>\n\nWorkaround tried:\n<what the agent/user tried next, and whether it worked>\n\nWhy this should be improved:\n<one sentence: better error message, docs, schema, tool behavior, etc.>\n````\n\n## Shared-Session Shell Runs\n\nUse `webstudio mcp run \'[{"tool":"components.find","input":{"brief":"button"}}]\'` when you are operating from a shell and need several MCP tool calls to share one CLI session without hand-writing JSON-RPC. For large batches, pass a normal JSON file path such as `.temp/mcp-calls.json`. Do not use shell process substitution like `<(...)`; use inline JSON or a real file.\n\nUse `mcp run` for long-lived tools such as `preview.start`. A one-shot `mcp single-op-call preview.start` cannot keep ownership of a preview server for a later screenshot or stop call. Put `preview.start`, `screenshot`, and `preview.stop` in one shared `mcp run` process, or use a real long-running MCP client.\n\nInput shape:\n\n```json\n{\n "calls": [\n { "tool": "meta.index" },\n { "tool": "components.find", "input": { "brief": "radix select" } }\n ]\n}\n```\n\nRules:\n\n- The command prints JSON to stdout for both success and failure. It stops at the first failed call and prints partial results in `{ "ok": false, "error": ..., "data": { "completedCalls": ..., "results": [...] }, "meta": ... }`, then exits nonzero.\n- If a call returns `checkpoint.required`, read-only discovery and inspection remain available, but mutations and state-changing session tools return `CHECKPOINT_REQUIRED`. Stop and report the checkpoint to the parent/user. Only after the parent/user continues, call `checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}` before continuing mutations.\n- For `mcp single-op-call`, checkpoint requirements persist across later one-shot CLI processes until you call `checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}`.\n- Use this instead of manually sending JSON-RPC frames to `webstudio mcp` from a shell.\n\n### Cross-project batches\n\nAdd `projects` to the same `mcp run` manifest to run focused reads, audits, or dry runs across independently linked project roots:\n\n```json\n{\n "concurrency": 2,\n "calls": [\n { "tool": "status" },\n { "tool": "audit", "input": {} },\n {\n "tool": "update-project-settings",\n "input": { "meta": { "siteName": "Reviewed" } },\n "dryRun": true\n }\n ],\n "projects": [\n { "id": "site-a", "root": "../site-a" },\n { "id": "site-b", "root": "../site-b" }\n ]\n}\n```\n\nProject roots and an optional `progressFile` are resolved relative to the manifest file. Each project may provide its own `calls` instead of using the top-level calls. Each root must already be linked with its own `.webstudio/config.json`; the runner creates an independently authenticated ProjectSession and uses root-scoped session, audit, preview-data, and checkpoint paths without changing the process working directory.\n\nConcurrency defaults to 2, is capped at 16, and can be set in the manifest or overridden with `--concurrency`. A failure is reported for that project while other projects continue. Progress is saved after every successful call; rerunning with the default `--resume` skips completed projects and starts failed projects after their last confirmed successful call. Reads and dry runs may be retried. A committed mutation interrupted after dispatch is marked `AMBIGUOUS_MUTATION_RESULT` and is never replayed automatically; inspect that project before deciding how to continue. Use `--no-resume` only to intentionally start the complete manifest over.\n\nCommitted mutation tools are rejected in a projects batch unless the command includes `--approve-mutations`. Review the complete manifest before granting approval. `--dry-run` applies to every call and does not require mutation approval. The final stdout object is compact: project counts, one status/error record per project, elapsed time, and the progress-file path rather than every tool result.\n\n## Discovery\n\nUse MCP itself after startup, or call the same tools with `webstudio mcp single-op-call`:\n\n- `tools/list`: machine-readable available tools\n- `resources/list`: available overview and full JSON resources\n- `meta.index`: concise capability catalog\n- `meta.guide`: workflow for a user goal; call with a string brief such as `{"brief":"Create a pricing page"}`\n- `meta.get_more_tools`: detailed params, examples, namespaces, and local/server behavior; prefer exact names such as `{"tools":["insert-fragment"]}` when you know them\n- `components.list`: compact registry metadata for visible components and templates; use a focused get tool for complete details\n- `components.summary`: component counts by default; use `{"detail":"components","limit":20}` for paginated entries\n- `components.coverage-plan`: compact paged plan for design-system coverage tasks that need every component; default returns counts plus the first root page, use `{"detail":"roots"}`, `{"detail":"parts"}`, or `{"detail":"full"}` for more\n- `components.coverage-status`: page-specific covered/missing component report with `missingRoots` and `missingParts`\n- `components.search`: focused component/template search by id, namespace, label, category, or content model\n- `components.find`: compatibility alias for focused component search\n- `components.get`: full metadata for one component id\n- `templates.list`: compact metadata for template-backed insertions only\n- `templates.get`: full registry item and payload metadata for one template\n\nComponent and template registry items use a shadcn-compatible top-level shape plus Webstudio-specific superset metadata in `meta`. Use `meta.runtime` for component ids, props, states, content model, and source identity; `meta.authoring` for composition and accessibility guidance; and `meta.builder` for template insertion details and expected project-data namespaces. These items are for Builder/MCP discovery and are not a published shadcn install registry yet.\n\nPrefer the focused `components.*` tools over dumping `webstudio://project/components`. Do not write local scripts to parse full MCP discovery JSON for common component lookup.\nFor “use every component” or design-system pages, start with compact `components.coverage-plan`, checkpoint, then page through roots/parts instead of dumping the full catalog.\n\n## Consumer Capabilities\n\nMCP lets agents work on one configured Webstudio project at a time. In consumer\nterms, agents can:\n\n- Check which project they are connected to.\n- Check what the share link is allowed to do.\n- Inspect project metadata and the latest editable build.\n- Read selected project data for audits and repair.\n- Apply precise project changes against a known version.\n- List, inspect, create, update, delete, duplicate, copy, and reorder pages.\n- Set the home page.\n- Preserve old page paths for redirects or history.\n- Read and update page titles, descriptions, metadata, auth settings, and SEO fields.\n- List, create, update, duplicate, move, and delete page folders.\n- List, create, update, delete, duplicate, reorder, and reuse page templates.\n- Create pages from reusable templates.\n- Read and update project site settings.\n- Read and update marketplace product metadata.\n- List, create, update, delete, and replace redirects.\n- List, create, update, and delete responsive breakpoints.\n- List and inspect page elements.\n- Insert registered components.\n- Insert styled JSX fragments.\n- Move, reparent, clone, duplicate, wrap, unwrap, convert, rename, retag, and delete elements.\n- Fill grid cells.\n- List and update text children.\n- Update plain text and expression text.\n- Update structured rich text.\n- Add, update, delete, and bind element props.\n- Bind props to expressions, resources, actions, and runtime system values.\n- Read, add, update, delete, and replace local styles.\n- Update selected style-source styles.\n- List, create, update, attach, detach, extract, duplicate, rename, lock, unlock, reorder, clear, and delete design tokens and style sources.\n- List, define, rename, delete, and rewrite CSS variables.\n- List, create, update, and delete static data variables.\n- Create string, number, boolean, and JSON variables. Arrays use JSON.\n- Delete unused data variables.\n- List, create, update, upsert, bind, and delete resources.\n- Create HTTP resources.\n- Create GraphQL resources.\n- Create system resources.\n- Use built-in system resources for sitemap, current date, and assets.\n- List and inspect complete asset metadata; upload, download, update, move, duplicate, find usage for, replace, and delete assets.\n- List, create, rename, move, recursively duplicate, and recursively delete nested asset folders.\n- Publish to staging or production.\n- Publish to selected domains.\n- List publish builds.\n- Check publish job status.\n- Unpublish staging or production deployments.\n- List, create, update, delete, and verify custom domains.\n- Start and stop preview.\n- Capture screenshots of generated pages.\n- Compare screenshots against baselines.\n- Install OCR support for richer visual checks.\n\nUseful resources:\n\n- `webstudio://project/status`: compact current ProjectSession status\n- `webstudio://project/tools-overview`: small operation overview by capability area\n- `webstudio://project/components-overview`: small component overview with ids, labels, namespaces, and categories\n- `webstudio://project/tools`: full operation catalog; read only when focused metadata is insufficient\n- `webstudio://project/components`: full component catalog with props, states, and content model composition constraints; read only when `components.summary`, `components.find`, and `components.get` are insufficient\n- `webstudio://project/guide`: concise discovery guide\n- `webstudio://project/expressions`: expression syntax, scope, supported methods, bindings, Collection iteration context, and verification\n- `webstudio://project/accessibility-review`: evidence-based LLM accessibility-review workflow using project checks, preview, and screenshots\n\n## MCP SDK Client Imports\n\nWhen writing a local Node.js MCP client script, use the official MCP SDK package and these exact ESM imports:\n\nInside the Webstudio monorepo this package is available at the repo root. In another project, install it first with `pnpm add -D @modelcontextprotocol/sdk`.\n\n```js\nimport { Client } from "@modelcontextprotocol/sdk/client/index.js";\nimport { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";\nimport { LoggingMessageNotificationSchema } from "@modelcontextprotocol/sdk/types.js";\n```\n\nMinimal stdio client for the local Webstudio CLI:\n\n```js\nconst client = new Client({ name: "webstudio-agent", version: "1.0.0" });\n\nclient.setNotificationHandler(\n LoggingMessageNotificationSchema,\n (notification) => {\n console.error(`[mcp] ${notification.params.data}`);\n }\n);\n\nconst transport = new StdioClientTransport({\n command: "node",\n args: ["packages/cli/local.js", "mcp"],\n cwd: process.cwd(),\n stderr: "inherit",\n});\n\nawait client.connect(transport);\n\nconst index = await client.callTool({\n name: "meta.index",\n arguments: {},\n});\nconsole.log(JSON.stringify(index.structuredContent, null, 2));\n\nawait client.close();\n```\n\nUse `node packages/cli/local.js mcp` from the Webstudio monorepo root for local development, or `webstudio mcp` from a linked project where the CLI is installed. Keep stdout for JSON-RPC/structured results and surface MCP logging notifications or stderr lifecycle lines as progress.\n\n## Core Rules\n\n- stdout is reserved for MCP JSON-RPC while the server is running.\n- Operate on the configured project only.\n- Read ids before writing.\n- Prefer semantic tools over `apply-patch`.\n- Use `status` and `refresh` when cached namespaces may be stale. Pass `status {"verbose":true}` only when debugging full namespace arrays, freshness, compatibility, or diagnostic details.\n- A mutation is durable only when `meta.session.committed` is true.\n- For visual/design work, verify the rendered result with vision before finishing.\n\n## Vision Verification Loop\n\nVision-capable AI can use MCP to see what it is building:\n\n{{mcpVisionVerificationLoopMarkdown}}\n\nGenerated app setup:\n\n{{mcpGeneratedAppDependencyNotes}}\n\n## MCP Argument Examples\n\nMCP tools receive JSON argument objects:\n\n{{mcpArgumentExampleIndex}}\n\n## Screenshot Verification\n\n{{screenshotVerificationSummary}}\n',
"mcp-startup-epilogue":
@@ -84,12 +84,12 @@ export const cliDocSections = {
'Resource url accepts plain fixed URLs and paths. For computed URLs, pass JavaScript expression code such as "https://api.example.com/items?tag=" + filters.tag. Resource header values, search parameter values, and text bodies accept expressions for dynamic values; for fixed text, use { "type": "literal", "value": "application/json" }.',
'Resource update example: use update-resource with {"resourceId":"resource-id","values":{"url":"https://api.example.com/items"}}.',
"Assets is one system resource with one response shape and always executes a structured query. create-assets-resource without query uses the default URL and optional image-dimensions output. Provide query configuration to control filtering, sorting, pagination, selected fields, or file content.",
- "For a Markdown-backed blog, read get-asset-field-catalog, validate a structured query with validate-asset-query, then call create-assets-resource or update-assets-resource. Set values.query:null to restore the default query.",
+ "For a Markdown-backed blog, create exactly two Builder page definitions: a fixed /blog overview and one /blog/:slug detail page. Both pages load content through Assets resources. Never create one Builder page per post or duplicate Markdown content into static page structures. Read get-asset-field-catalog, validate each structured query with validate-asset-query, then call create-assets-resource or update-assets-resource. Set values.query:null to restore the default query.",
'Optimize every explicit Assets query for the deployed content-database size. Use output.mode:"fields" and select only fields that are actually rendered or otherwise required by the query. Keep includeMetadata:false unless the rendered value needs file metadata; diagnostics are returned separately. Do not use output.mode:"all" as a convenience default.',
- 'Use a metadata-only Assets resource with content.mode:"none" for listings. Combine filters with where.all (AND) and where.any (OR). Use a separate Assets resource for the detail route with a slug or alternate-ID filter whose value is system.params.slug, limit:1, and content.mode:"markdown-body". Request full content only when the whole source file is rendered; otherwise prefer markdown-body or a bounded byte range.',
+ 'Use a metadata-only Assets resource with content.mode:"none" for the /blog listing. Combine filters with where.all (AND) and where.any (OR). Give both blog queries static Markdown and folder/path constraints, including extension = md, so dynamic route compilation cannot pull images or unrelated files into the database. Use a separate Assets resource for /blog/:slug with those same static constraints plus a slug or alternate-ID filter whose value is system.params.slug, limit:1, and content.mode:"markdown-body". Request full content only when the whole source file is rendered; otherwise prefer markdown-body or a bounded byte range.',
'Markdown returned with content.mode:"markdown-body" resolves conventional relative links and images such as ../images/hero.png to matching Assets. Markdown Embed permits sanitized figures, audio, video, and iframes, but removes scripts, inline event handlers, and unsafe URLs.',
"Assets expose an ID-keyed map at <dataSourceName>.data and collection information at <dataSourceName>.meta. Bind a listing Collection to posts.data and a one-result detail Collection to post.data; each item value contains selected fields and its item key is the asset ID. Read frontmatter or JSON fields from item.properties, the derived excerpt from item.excerpt, and requested Markdown from item.content.text.",
- "Use preview-asset-query with concrete values before binding expressions in the saved resource. Inspect __diagnostics__.usedBytes, maxBytes, unboundedBytes, and truncated. When usage approaches the limit, first remove unused output fields, then narrow candidate files with filters, and finally reduce or remove embedded content. Inspect saved mode and configuration with list-assets-resources or get-assets-resource; shared index maintenance is automatic.",
+ "Use preview-asset-query with concrete values before binding expressions in the saved resource. Inspect __diagnostics__.query for the temporary query-only footprint and __diagnostics__.database for the merged database built from all reachable Assets queries. Only database.usedBytes counts toward database.maxBytes; query sizes are not separate allowances and must not be summed. Compare usedBytes, unboundedBytes, and truncated within both scopes. When merged usage approaches the limit, first remove unused output fields, then narrow candidate files with filters, and finally reduce or remove embedded content. Inspect saved mode and configuration with list-assets-resources or get-assets-resource; shared index maintenance is automatic.",
"Data variable values support string, number, boolean, and json. Use json for all arrays, objects, filters, and nested data.",
"Parameters are internal scoped runtime values from pages, collections, or components. They are not a public authoring surface: do not create, update, or delete parameter records. Public tools should preserve existing parameter records and may reference documented context values such as system in expressions where they are already in scope.",
"Use scoped resources for read data. A GET resource created with scopeInstanceId/dataSourceName defaults to exposeAsDataSource:true, becomes a scoped resource data variable, is generated into the page resource data map, and may be loaded while rendering the page. Read the loaded resource result from its wrapper, usually .data.",
diff --git a/packages/cli/src/docs/api-use-cases.md b/packages/cli/src/docs/api-use-cases.md
index 2f698bddcd..511c13abd3 100644
--- a/packages/cli/src/docs/api-use-cases.md
+++ b/packages/cli/src/docs/api-use-cases.md
@@ -234,6 +234,20 @@ Commands:
- MCP tool: update-marketplace-product {"category":"pageTemplates","name":"Acme Template","thumbnailAssetId":"asset-id","author":"Acme Studio","email":"[email protected]","website":"https://example.com","issues":"","description":"Reusable template project for Acme landing pages."}
+## Submit marketplace product
+
+Commands:
+
+- MCP tool: upload-asset {"asset":{"name":"marketplace-thumbnail.png","type":"image","format":"png","meta":{"width":1200,"height":630}},"assetsDir":".webstudio/assets"}
+- MCP tool: update-marketplace-product {"category":"pageTemplates","name":"Acme Template","thumbnailAssetId":"<uploadedAssetId>","author":"Acme Studio","email":"[email protected]","website":"https://example.com","issues":"","description":"Reusable template project for Acme landing pages."}
+- MCP tool: publish {"target":"production"}
+- MCP tool: submit-marketplace-product {"acknowledgePublicSubmission":true}
+
+Notes:
+
+- Wait for the production publish to complete before submitting the product for review.
+- Submission requires complete, valid marketplace metadata.
+
## List redirects
Commands:
@@ -722,7 +736,7 @@ Commands:
- MCP tool: validate-asset-query {"query":{"where":{"all":[{"field":["extension"],"operator":"eq","value":"md"},{"field":["properties","draft"],"operator":"ne","value":true}]},"limit":20}}
- MCP tool: create-assets-resource {"name":"All assets","scopeInstanceId":"<instanceId>","dataSourceName":"assets"}
- MCP tool: create-assets-resource {"name":"Published posts","scopeInstanceId":"<instanceId>","dataSourceName":"posts","query":{"where":{"all":[{"field":["extension"],"operator":"eq","value":{"type":"literal","value":"md"}},{"field":["properties","draft"],"operator":"ne","value":{"type":"literal","value":true}}]},"sort":[{"field":["properties","publishedAt"],"direction":"desc"}],"limit":{"type":"literal","value":20},"output":{"mode":"fields","includeMetadata":false,"fields":[["properties","title"],["properties","slug"],["properties","publishedAt"],["excerpt"]]},"content":{"mode":"none"}}}
-- MCP tool: create-assets-resource {"name":"Post by slug or ID","scopeInstanceId":"<instanceId>","dataSourceName":"post","query":{"where":{"any":[{"field":["properties","slug"],"operator":"eq","value":"system.params.slug"},{"field":["id"],"operator":"eq","value":"system.params.slug"}]},"limit":{"type":"literal","value":1},"output":{"mode":"fields","includeMetadata":false,"fields":[["properties","title"],["properties","publishedAt"]]},"content":{"mode":"markdown-body","maxBytes":1048576}}}
+- MCP tool: create-assets-resource {"name":"Post by slug or ID","scopeInstanceId":"<instanceId>","dataSourceName":"post","query":{"where":{"all":[{"field":["extension"],"operator":"eq","value":{"type":"literal","value":"md"}},{"any":[{"field":["properties","slug"],"operator":"eq","value":"system.params.slug"},{"field":["id"],"operator":"eq","value":"system.params.slug"}]}]},"limit":{"type":"literal","value":1},"output":{"mode":"fields","includeMetadata":false,"fields":[["properties","title"],["properties","publishedAt"]]},"content":{"mode":"markdown-body","maxBytes":1048576}}}
- MCP tool: list-assets-resources {}
- MCP tool: get-assets-resource {"resourceId":"<resourceId>"}
- MCP tool: update-assets-resource {"resourceId":"<resourceId>","values":{"query":null}}
@@ -736,7 +750,7 @@ Notes:
- Use `content.mode:"none"` for listings. Request `markdown-body`, `full`, or a bounded `range` only after filtering to the intended files, normally with `limit:1` for a slug detail route.
- In Markdown, reference sibling Assets with conventional relative URLs such as `../images/hero.png`. When `markdown-body` is requested, the content engine resolves matching files against the Markdown file's folder and emits the correct Builder or published Asset URL. Keep external URLs absolute.
- Markdown Embed renders sanitized authored HTML for figures, captions, audio, video, and iframes. Scripts, inline event handlers, `srcdoc`, and unsafe URL protocols are removed. Executable component composition remains separate future MDX work.
-- Preview each query with concrete values before saving it. Inspect `__diagnostics__.usedBytes`, `maxBytes`, `unboundedBytes`, and `truncated`; when usage approaches the limit, remove unused output fields, narrow candidate files, and reduce embedded content in that order.
+- Preview each query with concrete values before saving it. Inspect `__diagnostics__.query` for the temporary query-only footprint and `__diagnostics__.database` for the merged database built from all reachable Assets queries. Only `database.usedBytes` counts toward `database.maxBytes`; query sizes must not be summed and are not separate allowances. Compare `usedBytes`, `unboundedBytes`, and `truncated` within both scopes. When merged usage approaches the limit, remove unused output fields, narrow candidate files, and reduce embedded content in that order.
- Read Assets from the ID-keyed map at `<dataSourceName>.data`, with collection information such as `totalCount` and `hasMore` at `<dataSourceName>.meta`. Bind a listing Collection to `posts.data` and a one-result detail Collection to `post.data`. On each value, selected file fields such as `id`, `name`, and `extension` are top-level; Markdown frontmatter and JSON fields are under `properties`; the derived `excerpt` is top-level; and requested Markdown is at `content.text`.
- Assets has one response shape and always executes a structured query. Omit `query` to use the default query, which selects URL and optional image dimensions. Provide query configuration to control filtering, sorting, pagination, selected fields, or file content. Set `values.query:null` to restore the default query.
- `create-assets-resource` and `update-assets-resource` are the semantic authoring path. Do not construct the internal query URL, headers, or body expression manually.
@@ -975,6 +989,7 @@ Commands:
- MCP tool: get-marketplace-product {}
- MCP tool: update-marketplace-product {"category":"pageTemplates","name":"Acme Template","thumbnailAssetId":"asset-id","author":"Acme Studio","email":"[email protected]","website":"https://example.com","issues":"","description":"Reusable template project for Acme landing pages."}
+- MCP tool: submit-marketplace-product {"acknowledgePublicSubmission":true}
Patch namespaces:
diff --git a/packages/cli/src/docs/manual-llm.md b/packages/cli/src/docs/manual-llm.md
index a06009a269..93d0dfdff2 100644
--- a/packages/cli/src/docs/manual-llm.md
+++ b/packages/cli/src/docs/manual-llm.md
@@ -460,12 +460,12 @@ Before authoring unfamiliar expressions, read `webstudio://project/expressions`
- Resource `url` accepts plain fixed URLs and paths. For computed URLs, pass JavaScript expression code such as `"https://api.example.com/items?tag=" + filters.tag`. Resource header values, search parameter values, and text bodies accept expressions for dynamic values; for fixed text, use `{ "type": "literal", "value": "application/json" }`.
- Resource update example: use `update-resource` with `{"resourceId":"resource-id","values":{"url":"https://api.example.com/items"}}`.
- Assets is one system resource with one response shape and always executes a structured query. `create-assets-resource` without `query` uses the default URL and optional image-dimensions output. Provide query configuration to control filtering, sorting, pagination, selected fields, or file content.
-- For a Markdown-backed blog, read `get-asset-field-catalog`, validate a structured query with `validate-asset-query`, then call `create-assets-resource` or `update-assets-resource`. Set `values.query:null` to restore the default query.
+- For a Markdown-backed blog, create exactly two Builder page definitions: a fixed `/blog` overview and one `/blog/:slug` detail page. Both pages load content through Assets resources. Never create one Builder page per post or duplicate Markdown content into static page structures. Read `get-asset-field-catalog`, validate each structured query with `validate-asset-query`, then call `create-assets-resource` or `update-assets-resource`. Set `values.query:null` to restore the default query.
- Optimize every explicit Assets query for the deployed content-database size. Use `output.mode:"fields"` and select only fields that are actually rendered or otherwise required by the query. Keep `includeMetadata:false` unless the rendered value needs file metadata; diagnostics are returned separately. Do not use `output.mode:"all"` as a convenience default.
-- Use a metadata-only Assets resource with `content.mode:"none"` for listings. Combine filters with `where.all` (AND) and `where.any` (OR). Use a separate Assets resource for the detail route with a slug or alternate-ID filter whose value is `system.params.slug`, `limit:1`, and `content.mode:"markdown-body"`. Request `full` content only when the whole source file is rendered; otherwise prefer `markdown-body` or a bounded byte range.
+- Use a metadata-only Assets resource with `content.mode:"none"` for the `/blog` listing. Combine filters with `where.all` (AND) and `where.any` (OR). Give both blog queries static Markdown and folder/path constraints, including `extension = md`, so dynamic route compilation cannot pull images or unrelated files into the database. Use a separate Assets resource for `/blog/:slug` with those same static constraints plus a slug or alternate-ID filter whose value is `system.params.slug`, `limit:1`, and `content.mode:"markdown-body"`. Request `full` content only when the whole source file is rendered; otherwise prefer `markdown-body` or a bounded byte range.
- Markdown returned with `content.mode:"markdown-body"` resolves conventional relative links and images such as `../images/hero.png` to matching Assets. Markdown Embed permits sanitized figures, audio, video, and iframes, but removes scripts, inline event handlers, and unsafe URLs.
- Assets expose an ID-keyed map at `<dataSourceName>.data` and collection information at `<dataSourceName>.meta`. Bind a listing Collection to `posts.data` and a one-result detail Collection to `post.data`; each item value contains selected fields and its item key is the asset ID. Read frontmatter or JSON fields from `item.properties`, the derived excerpt from `item.excerpt`, and requested Markdown from `item.content.text`.
-- Use `preview-asset-query` with concrete values before binding expressions in the saved resource. Inspect `__diagnostics__.usedBytes`, `maxBytes`, `unboundedBytes`, and `truncated`. When usage approaches the limit, first remove unused output fields, then narrow candidate files with filters, and finally reduce or remove embedded content. Inspect saved mode and configuration with `list-assets-resources` or `get-assets-resource`; shared index maintenance is automatic.
+- Use `preview-asset-query` with concrete values before binding expressions in the saved resource. Inspect `__diagnostics__.query` for the temporary query-only footprint and `__diagnostics__.database` for the merged database built from all reachable Assets queries. Only `database.usedBytes` counts toward `database.maxBytes`; query sizes are not separate allowances and must not be summed. Compare `usedBytes`, `unboundedBytes`, and `truncated` within both scopes. When merged usage approaches the limit, first remove unused output fields, then narrow candidate files with filters, and finally reduce or remove embedded content. Inspect saved mode and configuration with `list-assets-resources` or `get-assets-resource`; shared index maintenance is automatic.
- Data variable values support `string`, `number`, `boolean`, and `json`. Use `json` for all arrays, objects, filters, and nested data.
- Parameters are internal scoped runtime values from pages, collections, or components. They are not a public authoring surface: do not create, update, or delete parameter records. Public tools should preserve existing parameter records and may reference documented context values such as `system` in expressions where they are already in scope.
- Use scoped resources for read data. A GET resource created with `scopeInstanceId`/`dataSourceName` defaults to `exposeAsDataSource:true`, becomes a scoped resource data variable, is generated into the page resource `data` map, and may be loaded while rendering the page. Read the loaded resource result from its wrapper, usually `.data`.
diff --git a/packages/cli/src/framework-vike-ssg.ts b/packages/cli/src/framework-vike-ssg.ts
index 610d29c957..74637d3f10 100644
--- a/packages/cli/src/framework-vike-ssg.ts
+++ b/packages/cli/src/framework-vike-ssg.ts
@@ -59,6 +59,9 @@ export const createFramework = async (
a: `${baseComponentImportSource}:Link`,
},
html: ({ pagePath, prerenderPaths = [] }) => {
+ if (pagePath === "/*") {
+ return [];
+ }
const dynamic = isPathnamePattern(pagePath);
if (dynamic && prerenderPaths.length === 0) {
throw new Error(
diff --git a/packages/cli/src/prebuild.test.ts b/packages/cli/src/prebuild.test.ts
index d4b9350057..d6533685a1 100644
--- a/packages/cli/src/prebuild.test.ts
+++ b/packages/cli/src/prebuild.test.ts
@@ -1049,6 +1049,41 @@ describe("prebuild", () => {
await expectGeneratedRedirectFallback("app/routes/$.tsx");
});
+ test("ignores the catch-all fallback when generating an SSG site", async () => {
+ await writeSiteData(
+ createSiteData({
+ pages: [
+ {
+ id: "home",
+ name: "Home",
+ title: "Home",
+ path: "",
+ rootInstanceId: "root",
+ meta: {},
+ },
+ {
+ id: "not-found",
+ name: "Not found",
+ title: "Not found",
+ path: "/*",
+ rootInstanceId: "root",
+ meta: {},
+ },
+ ],
+ })
+ );
+
+ await expect(
+ prebuild({ assets: false, template: ["ssg"] })
+ ).resolves.toBeUndefined();
+ await expect(readFile("pages/index/+Page.tsx", "utf8")).resolves.toContain(
+ "Page"
+ );
+ await expect(readFile("pages/*/+Page.tsx", "utf8")).rejects.toThrow(
+ "ENOENT"
+ );
+ });
+
test("generates one dynamic SSR blog route with an embedded content database", async () => {
const source = "# Published post\n";
const index = await createTestAssetIndex(
diff --git a/packages/content-engine/src/asset-index.test.ts b/packages/content-engine/src/asset-index.test.ts
index 96634293ae..3d99db5c90 100644
--- a/packages/content-engine/src/asset-index.test.ts
+++ b/packages/content-engine/src/asset-index.test.ts
@@ -2,7 +2,11 @@ import { describe, expect, test } from "vitest";
import { contentEngineLimits, parseContentDatabaseMaxBytes } from "./limits";
import { createCanonicalAssetFileEntry } from "./canonical";
import { createContentDatabase } from "./content-database";
-import { assetQueryResult, type AssetResourceOutputSelection } from "./schema";
+import {
+ assetQuery,
+ assetQueryResult,
+ type AssetResourceOutputSelection,
+} from "./schema";
import {
createContentCompilationPlan,
createLiteralContentCompilationQuery,
@@ -92,7 +96,15 @@ describe("shared asset index", () => {
fields: [["id"]],
});
- expect(idOnly.artifact.documents).toEqual([{ _id: "alpha" }]);
+ expect(idOnly.artifact.documents).toEqual([]);
+ expect(Object.values(idOnly.artifact.queries ?? {})).toEqual([
+ {
+ fields: [["id"]],
+ rows: [["alpha"]],
+ totalCount: 1,
+ hasMore: false,
+ },
+ ]);
expect(idOnly.diagnostics.boundedBytes).toBeLessThan(
metadata.diagnostics.boundedBytes
);
@@ -109,6 +121,304 @@ describe("shared asset index", () => {
).resolves.toMatchObject({ items: [{ id: "alpha" }] });
});
+ test("materializes a static overview query without storing candidate documents", async () => {
+ const posts = [
+ {
+ id: "newest",
+ slug: "newest",
+ title: "Newest",
+ excerpt: "Newest excerpt",
+ category: "Updates",
+ publishedAt: "2026-07-05",
+ readTime: "3 min read",
+ },
+ {
+ id: "first",
+ slug: "first",
+ title: "First",
+ excerpt: "First excerpt",
+ category: "Guides",
+ publishedAt: "2026-07-04",
+ readTime: "4 min read",
+ },
+ {
+ id: "second",
+ slug: "second",
+ title: "Second",
+ excerpt: "Second excerpt",
+ category: "Strategy",
+ publishedAt: "2026-07-03",
+ readTime: "5 min read",
+ },
+ {
+ id: "third",
+ slug: "third",
+ title: "Third",
+ excerpt: "Third excerpt",
+ category: "Updates",
+ publishedAt: "2026-07-02",
+ readTime: "6 min read",
+ },
+ {
+ id: "fourth",
+ slug: "fourth",
+ title: "Fourth",
+ excerpt: "Fourth excerpt",
+ category: "Guides",
+ publishedAt: "2026-07-01",
+ readTime: "7 min read",
+ },
+ ].map(({ id, ...properties }) =>
+ createCanonicalAssetFileEntry({
+ projectId: "project",
+ document: {
+ ...entry({ id }).document,
+ properties,
+ },
+ })
+ );
+ const query = assetQuery.parse({
+ where: {
+ all: [{ field: ["extension"], operator: "eq", value: "md" }],
+ },
+ sort: [{ field: ["properties", "publishedAt"], direction: "desc" }],
+ limit: 4,
+ offset: 1,
+ output: {
+ mode: "fields",
+ includeMetadata: false,
+ fields: [
+ ["properties", "slug"],
+ ["properties", "title"],
+ ["properties", "excerpt"],
+ ["properties", "category"],
+ ["properties", "publishedAt"],
+ ["properties", "readTime"],
+ ],
+ },
+ content: { mode: "none" },
+ });
+ const staticPlan = createContentCompilationPlan([
+ createLiteralContentCompilationQuery({ id: "posts", query }),
+ ]);
+ const runtimePlan = createContentCompilationPlan([
+ {
+ ...createLiteralContentCompilationQuery({ id: "posts", query }),
+ limit: { type: "dynamic" },
+ },
+ ]);
+ const materialized = await compileContentArtifact({
+ projectId: "project",
+ entries: posts,
+ plan: staticPlan,
+ });
+ const runtime = await compileContentArtifact({
+ projectId: "project",
+ entries: posts,
+ plan: runtimePlan,
+ });
+ const bounded = await compileContentArtifact({
+ projectId: "project",
+ entries: posts,
+ plan: staticPlan,
+ maxBytes: materialized.diagnostics.boundedBytes - 200,
+ });
+
+ expect(materialized.artifact.documents).toEqual([]);
+ expect(materialized.artifact.fieldCatalog.fields).toEqual({});
+ expect(materialized.artifact.database).toMatchObject({
+ sourceDocumentCount: 5,
+ includedDocumentCount: 5,
+ });
+ expect(Object.values(materialized.artifact.queries ?? {})).toEqual([
+ {
+ fields: [
+ ["id"],
+ ["properties", "slug"],
+ ["properties", "title"],
+ ["properties", "excerpt"],
+ ["properties", "category"],
+ ["properties", "publishedAt"],
+ ["properties", "readTime"],
+ ],
+ rows: [
+ [
+ "first",
+ "first",
+ "First",
+ "First excerpt",
+ "Guides",
+ "2026-07-04",
+ "4 min read",
+ ],
+ [
+ "second",
+ "second",
+ "Second",
+ "Second excerpt",
+ "Strategy",
+ "2026-07-03",
+ "5 min read",
+ ],
+ [
+ "third",
+ "third",
+ "Third",
+ "Third excerpt",
+ "Updates",
+ "2026-07-02",
+ "6 min read",
+ ],
+ [
+ "fourth",
+ "fourth",
+ "Fourth",
+ "Fourth excerpt",
+ "Guides",
+ "2026-07-01",
+ "7 min read",
+ ],
+ ],
+ totalCount: 5,
+ hasMore: false,
+ },
+ ]);
+ expect(materialized.diagnostics.boundedBytes).toBeLessThan(
+ runtime.diagnostics.boundedBytes * 0.7
+ );
+ expect(bounded.diagnostics.boundedBytes).toBeLessThanOrEqual(
+ materialized.diagnostics.boundedBytes - 200
+ );
+ expect(bounded.diagnostics.omittedDocumentCount).toBeGreaterThan(0);
+ expect(
+ createContentDatabase({ artifact: bounded.artifact }).getStats().truncated
+ ).toBe(true);
+ const result = await createContentDatabase({
+ artifact: materialized.artifact,
+ }).query({ query });
+ expect(result.items.map(({ id }) => id)).toEqual([
+ "first",
+ "second",
+ "third",
+ "fourth",
+ ]);
+ expect(result.items[0]).toMatchObject({
+ id: "first",
+ properties: {
+ slug: "first",
+ title: "First",
+ excerpt: "First excerpt",
+ },
+ });
+ expect(result).toMatchObject({
+ totalCount: 5,
+ hasMore: false,
+ });
+ expect(
+ createContentDatabase({
+ artifact: materialized.artifact,
+ }).getStats()
+ ).toMatchObject({
+ includedDocumentCount: 5,
+ omittedDocumentCount: 0,
+ omissionReason: undefined,
+ truncated: false,
+ });
+ await expect(verifyContentArtifact(materialized.artifact)).resolves.toEqual(
+ materialized.artifact
+ );
+ });
+
+ test("stores overview-only fields outside dynamic detail documents", async () => {
+ const sourceEntries = ["alpha", "beta"].map((id) =>
+ createCanonicalAssetFileEntry({
+ projectId: "project",
+ document: {
+ ...entry({ id }).document,
+ properties: {
+ slug: id,
+ title: `${id} title`,
+ excerpt: `${id} overview excerpt`,
+ },
+ },
+ })
+ );
+ const overview = createLiteralContentCompilationQuery({
+ id: "overview",
+ query: {
+ where: {
+ all: [{ field: ["extension"], operator: "eq", value: "md" }],
+ },
+ sort: [],
+ limit: 20,
+ offset: 0,
+ output: {
+ mode: "fields",
+ includeMetadata: false,
+ fields: [
+ ["properties", "slug"],
+ ["properties", "title"],
+ ["properties", "excerpt"],
+ ],
+ },
+ content: { mode: "none" },
+ },
+ });
+ const detail = {
+ ...createLiteralContentCompilationQuery({
+ id: "detail",
+ query: {
+ where: {
+ all: [
+ {
+ field: ["properties", "slug"],
+ operator: "eq",
+ value: "alpha",
+ },
+ ],
+ },
+ sort: [],
+ limit: 1,
+ offset: 0,
+ output: {
+ mode: "fields",
+ includeMetadata: false,
+ fields: [["properties", "title"]],
+ },
+ content: { mode: "none" },
+ },
+ }),
+ where: {
+ field: ["properties", "slug"] as [string, string],
+ operator: "eq" as const,
+ value: { type: "dynamic" as const },
+ },
+ };
+ const { artifact } = await compileContentArtifact({
+ projectId: "project",
+ entries: sourceEntries,
+ plan: createContentCompilationPlan([overview, detail]),
+ });
+
+ expect(artifact.documents).toEqual([
+ {
+ _id: "alpha",
+ properties: { slug: "alpha", title: "alpha title" },
+ },
+ {
+ _id: "beta",
+ properties: { slug: "beta", title: "beta title" },
+ },
+ ]);
+ expect(artifact.fieldCatalog.fields).not.toHaveProperty(
+ "properties.excerpt"
+ );
+ expect(Object.values(artifact.queries ?? {})[0]?.rows).toEqual([
+ ["alpha", "alpha", "alpha title", "alpha overview excerpt"],
+ ["beta", "beta", "beta title", "beta overview excerpt"],
+ ]);
+ });
+
test("creates one deterministic complete index and field catalog", async () => {
const index = await createAssetIndex({
projectId: "project",
@@ -262,6 +572,7 @@ describe("shared asset index", () => {
maxBytes: 5_000,
includedDocumentCount: 2,
omittedDocumentCount: 1,
+ omissionReason: "size",
truncated: true,
});
expect(contentEngineLimits.databaseBytes).toBe(500 * 1024);
@@ -354,6 +665,12 @@ describe("shared asset index", () => {
expect(diagnostics.unboundedBytes).toBeGreaterThan(
diagnostics.boundedBytes
);
+ expect(createContentDatabase({ artifact }).getStats()).toMatchObject({
+ includedDocumentCount: 1,
+ omittedDocumentCount: 1,
+ omissionReason: "unavailable",
+ truncated: true,
+ });
});
test("bounds a thousand oversized documents without rebuilding per document", async () => {
diff --git a/packages/content-engine/src/asset-index.ts b/packages/content-engine/src/asset-index.ts
index 3624ba1f11..b6c3858e60 100644
--- a/packages/content-engine/src/asset-index.ts
+++ b/packages/content-engine/src/asset-index.ts
@@ -16,12 +16,18 @@ import { contentEngineLimits } from "./limits";
import {
getContentDocumentCandidateQueryIds,
compareContentEntryPriority,
+ createContentCompilationPlan,
+ isContentDocumentCandidate,
isContentCompilationFieldRequired,
projectContentDatabaseDocument,
type ContentCompilationPlan,
} from "./compilation-plan";
import { getUtf8ByteLength } from "./byte-stream";
import type { MarkdownAssetReferences } from "./markdown-references";
+import {
+ canMaterializeContentCompilationQuery,
+ materializeContentCompilationQueries,
+} from "./materialized-query";
export type ContentCompilerDiagnostics = {
maxBytes: number;
@@ -142,11 +148,56 @@ const buildAssetIndex = async ({
plan?: ContentCompilationPlan;
finalize?: boolean;
}) => {
- const documents = entries
- .map(({ document }) => projectContentDatabaseDocument({ document, plan }))
+ const sourceDocuments = entries.map(({ document }) => document);
+ const sourceCatalog = await createAssetFieldCatalog(entries);
+ const assetRevision = sourceCatalog.canonicalRevision;
+ const completeSourceFieldCatalog = toBuilderAssetFieldCatalog(sourceCatalog);
+ const materialized =
+ plan === undefined
+ ? {
+ values: {},
+ materializedQueries: new Set<
+ ContentCompilationPlan["queries"][number]
+ >(),
+ }
+ : await materializeContentCompilationQueries({
+ queries: plan.queries,
+ catalog: completeSourceFieldCatalog,
+ documents: sourceDocuments,
+ });
+ const runtimeQueries =
+ plan?.queries.filter(
+ (query) => materialized.materializedQueries.has(query) === false
+ ) ?? [];
+ const runtimePlan =
+ plan === undefined
+ ? undefined
+ : (createContentCompilationPlan(runtimeQueries) ?? {
+ standardFields: [],
+ structuredPropertyPaths: [],
+ excerpt: false,
+ metadataError: false,
+ queries: [],
+ });
+ const runtimeEntries =
+ runtimePlan === undefined
+ ? entries
+ : runtimePlan.queries.length === 0
+ ? []
+ : entries.filter(({ document }) =>
+ isContentDocumentCandidate({
+ document,
+ plan: runtimePlan,
+ available: "all",
+ })
+ );
+ const documents = runtimeEntries
+ .map(({ document }) =>
+ projectContentDatabaseDocument({ document, plan: runtimePlan })
+ )
.sort((left, right) => compareStrings(left._id, right._id));
const contents = Object.fromEntries(
- entries
+ runtimeEntries
.filter(
(entry): entry is ContentCompilerInput & { content: string } =>
entry.content !== undefined
@@ -157,16 +208,21 @@ const buildAssetIndex = async ({
.map((entry) => [entry.document.contentRef, entry.content])
);
const includedContentRefs = new Set(
- entries.map(({ document }) => document.contentRef)
+ runtimeEntries.map(({ document }) => document.contentRef)
);
const includedAssetReferences = Object.fromEntries(
Object.entries(assetReferences ?? {}).filter(([contentRef]) =>
includedContentRefs.has(contentRef)
)
);
- const catalog = await createAssetFieldCatalog(entries);
- const assetRevision = catalog.canonicalRevision;
- const completeFieldCatalog = toBuilderAssetFieldCatalog(catalog);
+ const runtimeCatalog =
+ runtimeEntries === entries
+ ? sourceCatalog
+ : await createAssetFieldCatalog(runtimeEntries);
+ const completeFieldCatalog = {
+ ...toBuilderAssetFieldCatalog(runtimeCatalog),
+ canonicalRevision: assetRevision,
+ };
const fieldCatalog = {
...completeFieldCatalog,
fields: Object.fromEntries(
@@ -174,7 +230,10 @@ const buildAssetIndex = async ({
const queryPath = field.queryPath;
return (
queryPath !== undefined &&
- isContentCompilationFieldRequired({ plan, field: queryPath })
+ isContentCompilationFieldRequired({
+ plan: runtimePlan,
+ field: queryPath,
+ })
);
})
),
@@ -189,7 +248,17 @@ const buildAssetIndex = async ({
? {}
: { assetReferences: includedAssetReferences }),
fieldCatalog,
- database: { maxBytes, unboundedBytes, sourceDocumentCount },
+ ...(Object.keys(materialized.values).length === 0
+ ? {}
+ : { queries: materialized.values }),
+ database: {
+ maxBytes,
+ unboundedBytes,
+ sourceDocumentCount,
+ ...(runtimeEntries.length === entries.length
+ ? {}
+ : { includedDocumentCount: entries.length }),
+ },
integrity: {
algorithm: "sha256",
checksum: `sha256:${"0".repeat(64)}`,
@@ -228,6 +297,8 @@ export const compileContentArtifact = async ({
}
validateEntries({ projectId, entries });
const sourceDocumentCount = entries.length;
+ const hasMaterializableQueries =
+ plan?.queries.some(canMaterializeContentCompilationQuery) === true;
const unavailable = entries.filter(
(entry) => entry.contentRequired === true && entry.content === undefined
);
@@ -294,7 +365,10 @@ export const compileContentArtifact = async ({
selectedContentRefs,
plan,
});
- if (minimumAdditionalBytes <= maxBytes - selectedBytes) {
+ if (
+ hasMaterializableQueries ||
+ minimumAdditionalBytes <= maxBytes - selectedBytes
+ ) {
const trial = await buildAssetIndex({
entries: [...selected, ...candidates],
sourceDocumentCount,
diff --git a/packages/content-engine/src/content-database.ts b/packages/content-engine/src/content-database.ts
index cdb6425152..870effd3ec 100644
--- a/packages/content-engine/src/content-database.ts
+++ b/packages/content-engine/src/content-database.ts
@@ -13,6 +13,7 @@ import {
} from "./structured-query";
import { encodeUtf8, getUtf8ByteLength } from "./byte-stream";
import type { AssetResourceContentReader } from "./hydration";
+import { getMaterializedAssetQueryResult } from "./materialized-query";
export type ContentDatabase = {
query(
@@ -31,20 +32,29 @@ export const createContentDatabase = ({
artifact: ContentArtifactV1;
readContent?: AssetResourceContentReader;
}): ContentDatabase => {
- const includedDocumentCount = artifact.documents.length;
+ const includedDocumentCount =
+ artifact.database?.includedDocumentCount ?? artifact.documents.length;
const sourceDocumentCount =
artifact.database?.sourceDocumentCount ?? includedDocumentCount;
const omittedDocumentCount = sourceDocumentCount - includedDocumentCount;
const usedBytes = getUtf8ByteLength(serializeContentArtifact(artifact));
+ const maxBytes = artifact.database?.maxBytes ?? Number.MAX_SAFE_INTEGER;
+ const unboundedBytes = artifact.database?.unboundedBytes ?? usedBytes;
const stats: ContentDatabaseStats = {
format: artifact.format,
version: artifact.version,
revision: artifact.integrity.checksum,
usedBytes,
- maxBytes: artifact.database?.maxBytes ?? Number.MAX_SAFE_INTEGER,
- unboundedBytes: artifact.database?.unboundedBytes ?? usedBytes,
+ maxBytes,
+ unboundedBytes,
includedDocumentCount,
omittedDocumentCount,
+ omissionReason:
+ omittedDocumentCount === 0
+ ? undefined
+ : unboundedBytes > maxBytes
+ ? "size"
+ : "unavailable",
truncated: omittedDocumentCount > 0,
};
return {
@@ -55,6 +65,13 @@ export const createContentDatabase = ({
) {
throw new AssetIndexRevisionError();
}
+ const materialized = await getMaterializedAssetQueryResult({
+ queries: artifact.queries,
+ query: request.query,
+ });
+ if (materialized !== undefined) {
+ return materialized;
+ }
const readEmbeddedContent: AssetResourceContentReader = async (
contentRef,
range
diff --git a/packages/content-engine/src/materialized-query.ts b/packages/content-engine/src/materialized-query.ts
new file mode 100644
index 0000000000..2cbf630397
--- /dev/null
+++ b/packages/content-engine/src/materialized-query.ts
@@ -0,0 +1,261 @@
+import {
+ getQueryConditions,
+ mapQueryWhere,
+} from "@webstudio-is/query-builder/runtime";
+import { serializeJsonDeterministically, sha256 } from "./canonical-json";
+import type { ContentCompilationQuery } from "./compilation-plan";
+import {
+ assetQuery,
+ assetQueryResult,
+ isAssetQueryRuntimeField,
+ materializedAssetQuery,
+ type AssetQuery,
+ type AssetQueryFieldPath,
+ type AssetQueryInput,
+ type AssetQueryItem,
+ type AssetQueryResult,
+ type BuilderAssetFieldCatalog,
+ type ContentDatabaseDocument,
+ type MaterializedAssetQuery,
+} from "./schema";
+import {
+ AssetQueryExecutionError,
+ executeAssetQuery,
+} from "./structured-query";
+
+const hasOverlappingFields = (fields: readonly AssetQueryFieldPath[]) =>
+ fields.some((field, index) =>
+ fields.some(
+ (candidate, candidateIndex) =>
+ index !== candidateIndex &&
+ candidate.length < field.length &&
+ candidate.every((segment, position) => segment === field[position])
+ )
+ );
+
+const getMaterializedFields = (
+ query: ContentCompilationQuery
+): AssetQueryFieldPath[] | undefined => {
+ if (
+ query.content.mode !== "none" ||
+ query.output.mode !== "fields" ||
+ query.output.includeMetadata
+ ) {
+ return;
+ }
+ const fields = [
+ ["id"] as AssetQueryFieldPath,
+ ...query.output.fields.filter(
+ (field) => field.length !== 1 || field[0] !== "id"
+ ),
+ ];
+ if (
+ fields.some((field) => isAssetQueryRuntimeField(field[0])) ||
+ hasOverlappingFields(fields)
+ ) {
+ return;
+ }
+ return fields;
+};
+
+const toLiteralAssetQuery = (
+ query: ContentCompilationQuery
+): AssetQuery | undefined => {
+ if (
+ query.limit.type !== "literal" ||
+ query.offset.type !== "literal" ||
+ getQueryConditions(query.where).some(
+ ({ field, value }) =>
+ value.type !== "literal" || isAssetQueryRuntimeField(field[0])
+ ) ||
+ query.sort.some(({ field }) => isAssetQueryRuntimeField(field[0]))
+ ) {
+ return;
+ }
+ return assetQuery.parse({
+ where: mapQueryWhere(query.where, (condition) => ({
+ field: condition.field,
+ operator: condition.operator,
+ value:
+ condition.value.type === "literal" ? condition.value.value : undefined,
+ })),
+ sort: query.sort,
+ limit: query.limit.value,
+ offset: query.offset.value,
+ output: query.output,
+ content: query.content,
+ });
+};
+
+export const canMaterializeContentCompilationQuery = (
+ query: ContentCompilationQuery
+) =>
+ getMaterializedFields(query) !== undefined &&
+ toLiteralAssetQuery(query) !== undefined;
+
+export const getAssetQueryHash = async (query: AssetQuery) =>
+ await sha256(serializeJsonDeterministically(assetQuery.parse(query)));
+
+const getItemFieldValue = (
+ item: AssetQueryItem,
+ field: AssetQueryFieldPath
+) => {
+ let value: unknown = item;
+ for (const segment of field) {
+ if (
+ typeof value !== "object" ||
+ value === null ||
+ Object.hasOwn(value, segment) === false
+ ) {
+ return;
+ }
+ value = (value as Readonly<Record<string, unknown>>)[segment];
+ }
+ return value;
+};
+
+const materializeQuery = async ({
+ query,
+ catalog,
+ documents,
+}: {
+ query: ContentCompilationQuery;
+ catalog: BuilderAssetFieldCatalog;
+ documents: readonly ContentDatabaseDocument[];
+}): Promise<
+ | {
+ hash: string;
+ value: MaterializedAssetQuery;
+ }
+ | undefined
+> => {
+ if (canMaterializeContentCompilationQuery(query) === false) {
+ return;
+ }
+ const fields = getMaterializedFields(query);
+ const literalQuery = toLiteralAssetQuery(query);
+ if (fields === undefined || literalQuery === undefined) {
+ return;
+ }
+ let result: AssetQueryResult;
+ try {
+ result = await executeAssetQuery({
+ query: literalQuery,
+ catalog,
+ documents,
+ });
+ } catch (error) {
+ if (error instanceof AssetQueryExecutionError) {
+ return;
+ }
+ throw error;
+ }
+ const rows = result.items.map((item) =>
+ fields.map((field) => getItemFieldValue(item, field))
+ );
+ if (rows.some((row) => row.some((value) => value === undefined))) {
+ return;
+ }
+ return {
+ hash: await getAssetQueryHash(literalQuery),
+ value: materializedAssetQuery.parse({
+ fields,
+ rows,
+ totalCount: result.totalCount,
+ hasMore: result.hasMore,
+ }),
+ };
+};
+
+export const materializeContentCompilationQueries = async ({
+ queries,
+ catalog,
+ documents,
+}: {
+ queries: readonly ContentCompilationQuery[];
+ catalog: BuilderAssetFieldCatalog;
+ documents: readonly ContentDatabaseDocument[];
+}) => {
+ const values: Record<string, MaterializedAssetQuery> = {};
+ const materializedQueries = new Set<ContentCompilationQuery>();
+ for (const query of queries) {
+ const materialized = await materializeQuery({
+ query,
+ catalog,
+ documents,
+ });
+ if (materialized === undefined) {
+ continue;
+ }
+ values[materialized.hash] = materialized.value;
+ materializedQueries.add(query);
+ }
+ return { values, materializedQueries };
+};
+
+const setItemFieldValue = ({
+ item,
+ field,
+ value,
+}: {
+ item: Record<string, unknown>;
+ field: AssetQueryFieldPath;
+ value: unknown;
+}) => {
+ let target = item;
+ for (const [index, segment] of field.entries()) {
+ if (index === field.length - 1) {
+ Object.defineProperty(target, segment, {
+ value,
+ enumerable: true,
+ configurable: true,
+ writable: true,
+ });
+ return;
+ }
+ const current = Object.hasOwn(target, segment)
+ ? target[segment]
+ : undefined;
+ if (typeof current === "object" && current !== null) {
+ target = current as Record<string, unknown>;
+ continue;
+ }
+ const nested: Record<string, unknown> = {};
+ Object.defineProperty(target, segment, {
+ value: nested,
+ enumerable: true,
+ configurable: true,
+ writable: true,
+ });
+ target = nested;
+ }
+};
+
+const hydrateMaterializedQuery = (
+ query: MaterializedAssetQuery
+): AssetQueryResult =>
+ assetQueryResult.parse({
+ items: query.rows.map((row) => {
+ const item: Record<string, unknown> = {};
+ for (const [index, field] of query.fields.entries()) {
+ setItemFieldValue({ item, field, value: row[index] });
+ }
+ return item;
+ }),
+ totalCount: query.totalCount,
+ hasMore: query.hasMore,
+ });
+
+export const getMaterializedAssetQueryResult = async ({
+ queries,
+ query,
+}: {
+ queries: Readonly<Record<string, MaterializedAssetQuery>> | undefined;
+ query: AssetQueryInput;
+}): Promise<AssetQueryResult | undefined> => {
+ if (queries === undefined) {
+ return;
+ }
+ const value = queries[await getAssetQueryHash(assetQuery.parse(query))];
+ return value === undefined ? undefined : hydrateMaterializedQuery(value);
+};
diff --git a/packages/content-engine/src/published-runtime.test.ts b/packages/content-engine/src/published-runtime.test.ts
index d1ec87308d..31c7b70f21 100644
--- a/packages/content-engine/src/published-runtime.test.ts
+++ b/packages/content-engine/src/published-runtime.test.ts
@@ -1,7 +1,11 @@
import { afterEach, describe, expect, test, vi } from "vitest";
-import type { AssetFileDocument } from "./schema";
+import { assetQuery, type AssetFileDocument } from "./schema";
import { createAssetIndex } from "./asset-index";
import { createCanonicalAssetFileEntry } from "./canonical";
+import {
+ createContentCompilationPlan,
+ createLiteralContentCompilationQuery,
+} from "./compilation-plan";
import {
createGeneratedAssetResourceRuntime,
createPublishedAssetResourceFetch,
@@ -133,6 +137,66 @@ describe("published asset resource runtime", () => {
expect(networkFetch).not.toHaveBeenCalled();
});
+ test("serves a materialized static query without candidate documents", async () => {
+ const query = assetQuery.parse({
+ where: {
+ all: [
+ {
+ field: ["properties", "slug"],
+ operator: "eq",
+ value: "post",
+ },
+ ],
+ },
+ sort: [],
+ limit: 1,
+ offset: 0,
+ output: {
+ mode: "fields",
+ includeMetadata: false,
+ fields: [
+ ["properties", "slug"],
+ ["properties", "title"],
+ ],
+ },
+ content: { mode: "none" },
+ });
+ const index = await createAssetIndex({
+ projectId: "project-1",
+ entries: [
+ createCanonicalAssetFileEntry({
+ projectId: "project-1",
+ document,
+ }),
+ ],
+ plan: createContentCompilationPlan([
+ createLiteralContentCompilationQuery({ id: "posts", query }),
+ ]),
+ });
+ const runtimeFetch = createPublishedAssetResourceFetch({
+ baseUrl: "https://site.example",
+ deploymentId: "build-materialized",
+ artifact: index,
+ runtimeAssets: {},
+ });
+
+ expect(index.documents).toEqual([]);
+ const response = await runtimeFetch("/$resources/assets", {
+ method: "POST",
+ body: JSON.stringify({ query }),
+ });
+ await expect(response?.json()).resolves.toEqual({
+ items: [
+ {
+ id: "post-1",
+ properties: { slug: "post", title: "Post" },
+ },
+ ],
+ totalCount: 1,
+ hasMore: false,
+ });
+ });
+
test("reuses one initialized runtime across deployment origins", async () => {
const { index } = await createRuntime();
const createGeneratedFetch = createGeneratedAssetResourceRuntime({
diff --git a/packages/content-engine/src/schema.ts b/packages/content-engine/src/schema.ts
index 972fc97d75..e06b76d4a5 100644
--- a/packages/content-engine/src/schema.ts
+++ b/packages/content-engine/src/schema.ts
@@ -144,6 +144,32 @@ export type BuilderAssetFieldCatalog = Infer<typeof builderAssetFieldCatalog>;
const sha256Revision = string().regex(/^sha256:[a-f0-9]{64}$/);
+export const materializedAssetQuery = strictObject({
+ fields: array(
+ array(string().min(1)).min(1).max(contentEngineLimits.fieldPathDepth)
+ )
+ .min(1)
+ .max(contentEngineLimits.outputFieldCount + 1),
+ rows: array(array(json())).max(contentEngineLimits.resultCount),
+ totalCount: number()
+ .int()
+ .nonnegative()
+ .max(contentEngineLimits.candidateDocuments),
+ hasMore: boolean(),
+}).superRefine(({ fields, rows }, context) => {
+ for (const [index, row] of rows.entries()) {
+ if (row.length !== fields.length) {
+ context.addIssue({
+ code: "custom",
+ path: ["rows", index],
+ message: "Materialized query rows must match the field count",
+ });
+ }
+ }
+});
+
+export type MaterializedAssetQuery = Infer<typeof materializedAssetQuery>;
+
/** One compiled runtime database shared by all reachable Assets queries. */
export const contentArtifactV1 = strictObject({
format: literal("webstudio-content-database"),
@@ -165,10 +191,12 @@ export const contentArtifactV1 = strictObject({
)
).optional(),
fieldCatalog: builderAssetFieldCatalog,
+ queries: record(sha256Revision, materializedAssetQuery).optional(),
database: strictObject({
maxBytes: number().int().positive(),
unboundedBytes: number().int().nonnegative(),
sourceDocumentCount: number().int().nonnegative(),
+ includedDocumentCount: number().int().nonnegative().optional(),
}).optional(),
integrity: strictObject({
algorithm: literal("sha256"),
@@ -202,6 +230,17 @@ export const contentArtifactV1 = strictObject({
message: "Source document count cannot be smaller than the database",
});
}
+ if (
+ index.database?.includedDocumentCount !== undefined &&
+ (index.database.includedDocumentCount < index.documents.length ||
+ index.database.includedDocumentCount > index.database.sourceDocumentCount)
+ ) {
+ context.addIssue({
+ code: "custom",
+ path: ["database", "includedDocumentCount"],
+ message: "Included document count must match the database bounds",
+ });
+ }
let previousId: string | undefined;
for (const [position, document] of index.documents.entries()) {
if (previousId !== undefined && document._id <= previousId) {
@@ -562,21 +601,27 @@ export const contentDatabaseStats = strictObject({
unboundedBytes: number().int().nonnegative(),
includedDocumentCount: number().int().nonnegative(),
omittedDocumentCount: number().int().nonnegative(),
+ omissionReason: zEnum(["size", "unavailable"]).optional(),
truncated: boolean(),
});
export type ContentDatabaseStats = Infer<typeof contentDatabaseStats>;
-export const assetQueryPreviewDiagnostics = contentDatabaseStats
- .pick({
- usedBytes: true,
- maxBytes: true,
- unboundedBytes: true,
- includedDocumentCount: true,
- omittedDocumentCount: true,
- truncated: true,
- })
- .extend({ scope: literal("query-preview") });
+const contentDatabaseCapacityStats = contentDatabaseStats.pick({
+ usedBytes: true,
+ maxBytes: true,
+ unboundedBytes: true,
+ includedDocumentCount: true,
+ omittedDocumentCount: true,
+ omissionReason: true,
+ truncated: true,
+});
+
+export const assetQueryPreviewDiagnostics = strictObject({
+ scope: literal("query-preview"),
+ query: contentDatabaseCapacityStats,
+ database: contentDatabaseCapacityStats,
+});
export type AssetQueryPreviewDiagnostics = Infer<
typeof assetQueryPreviewDiagnostics
diff --git a/packages/http-client/src/index.ts b/packages/http-client/src/index.ts
index 1cab6a9835..9760dc7569 100644
--- a/packages/http-client/src/index.ts
+++ b/packages/http-client/src/index.ts
@@ -1191,6 +1191,11 @@ export const getMarketplaceProduct = projectQueryInput<AuthProjectParams>(
"get-marketplace-product"
);
+export const submitMarketplaceProduct = projectMutationInput<
+ AuthProjectParams & { acknowledgePublicSubmission: true },
+ { marketplaceApprovalStatus: "PENDING" }
+>("submit-marketplace-product");
+
export const setRedirects = runtimeProjectMutation("set-redirects");
export const copyPage = runtimeProjectMutation("copy-page");
diff --git a/packages/project-build/src/content-database.ts b/packages/project-build/src/content-database.ts
new file mode 100644
index 0000000000..c90460316f
--- /dev/null
+++ b/packages/project-build/src/content-database.ts
@@ -0,0 +1,78 @@
+import {
+ assetQuery,
+ createContentDatabase,
+ createContentCompilationPlan,
+ createLiteralContentCompilationQuery,
+ hasDynamicContentCompilationValues,
+ type AssetQueryInput,
+ type ContentArtifactV1,
+} from "@webstudio-is/content-engine";
+import {
+ createReachableAssetContentCompilationPlan,
+ type DataSource,
+ type Prop,
+ type Resource,
+} from "@webstudio-is/sdk";
+import type { Build, CompactBuild } from "./types";
+
+type ContentDatabaseBuild =
+ | Pick<Build, "props" | "dataSources" | "resources">
+ | Pick<CompactBuild, "props" | "dataSources" | "resources">;
+
+const getBuildValues = <Item>(
+ values: readonly Item[] | readonly (readonly [string, Item])[]
+) =>
+ values.map((value) =>
+ Array.isArray(value) ? (value[1] as Item) : (value as Item)
+ );
+
+export const createBuildContentCompilationPlan = (
+ build: ContentDatabaseBuild
+) =>
+ createReachableAssetContentCompilationPlan({
+ props: getBuildValues<Prop>(build.props),
+ dataSources: getBuildValues<DataSource>(build.dataSources),
+ resources: getBuildValues<Resource>(build.resources),
+ });
+
+export const createAssetQueryPreviewCompilationPlan = ({
+ build,
+ query,
+}: {
+ build: ContentDatabaseBuild;
+ query: AssetQueryInput;
+}) => {
+ const savedPlan = createBuildContentCompilationPlan(build);
+ return createContentCompilationPlan([
+ ...(savedPlan?.queries ?? []),
+ createLiteralContentCompilationQuery({
+ id: "__query-preview__",
+ query: assetQuery.parse(query),
+ }),
+ ]);
+};
+
+export const getContentDatabasePublishDiagnostics = ({
+ build,
+ artifact,
+}: {
+ build: ContentDatabaseBuild;
+ artifact: ContentArtifactV1 | undefined;
+}) => {
+ if (artifact === undefined) {
+ return;
+ }
+ const plan = createBuildContentCompilationPlan(build);
+ if (plan === undefined) {
+ return;
+ }
+ return {
+ stats: createContentDatabase({ artifact }).getStats(),
+ queries: plan.queries.map((query) => ({
+ id: query.id,
+ kind: hasDynamicContentCompilationValues({ ...plan, queries: [query] })
+ ? ("dynamic" as const)
+ : ("static" as const),
+ })),
+ };
+};
diff --git a/packages/project-build/src/contracts/__generated__/runtime-operation-contracts.ts b/packages/project-build/src/contracts/__generated__/runtime-operation-contracts.ts
index 8deed86941..43cc8c23d7 100644
--- a/packages/project-build/src/contracts/__generated__/runtime-operation-contracts.ts
+++ b/packages/project-build/src/contracts/__generated__/runtime-operation-contracts.ts
@@ -628,7 +628,7 @@ export const runtimeOperationContractData = [
path: {
type: "string",
description:
- 'Plain page path. For a new non-home page, start with "/", for example "/pricing". The home page path is the empty string ""; do not use an empty path when creating a new page.',
+ 'Plain page path. For a new non-home page, start with "/", for example "/pricing". Use colon-prefixed dynamic segments such as "/blog/:slug" when one page definition must render many concrete routes; do not create a separate page for every route value. The home page path is the empty string ""; do not use an empty path when creating a new page.',
},
title: {
description:
@@ -802,7 +802,7 @@ export const runtimeOperationContractData = [
},
],
description:
- 'Plain page path. For a new non-home page, start with "/", for example "/pricing". The home page path is the empty string ""; do not use an empty path when creating a new page.',
+ 'Plain page path. For a new non-home page, start with "/", for example "/pricing". Use colon-prefixed dynamic segments such as "/blog/:slug" when one page definition must render many concrete routes; do not create a separate page for every route value. The home page path is the empty string ""; do not use an empty path when creating a new page.',
},
title: {
description:
@@ -1402,85 +1402,92 @@ export const runtimeOperationContractData = [
type: "object",
properties: {
marketplaceProduct: {
- type: "object",
- properties: {
- category: {
- anyOf: [
- {
- type: "string",
- const: "sectionTemplates",
+ anyOf: [
+ {
+ type: "object",
+ properties: {
+ category: {
+ anyOf: [
+ {
+ type: "string",
+ const: "sectionTemplates",
+ },
+ {
+ type: "string",
+ const: "pageTemplates",
+ },
+ {
+ type: "string",
+ const: "integrationTemplates",
+ },
+ ],
},
- {
+ name: {
type: "string",
- const: "pageTemplates",
+ minLength: 2,
+ maxLength: 200,
},
- {
+ thumbnailAssetId: {
type: "string",
- const: "integrationTemplates",
},
- ],
- },
- name: {
- type: "string",
- minLength: 2,
- maxLength: 200,
- },
- thumbnailAssetId: {
- type: "string",
- },
- author: {
- type: "string",
- minLength: 2,
- maxLength: 200,
- },
- email: {
- type: "string",
- maxLength: 200,
- format: "email",
- pattern:
- "^(?!\\.)(?!.*\\.\\.)([A-Za-z0-9_'+\\-\\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\\-]*\\.)+[A-Za-z]{2,}$",
- },
- website: {
- anyOf: [
- {
+ author: {
type: "string",
+ minLength: 2,
maxLength: 200,
- format: "uri",
},
- {
- type: "string",
- const: "",
- },
- ],
- },
- issues: {
- anyOf: [
- {
+ email: {
type: "string",
maxLength: 200,
- format: "uri",
+ format: "email",
+ pattern:
+ "^(?!\\.)(?!.*\\.\\.)([A-Za-z0-9_'+\\-\\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\\-]*\\.)+[A-Za-z]{2,}$",
},
- {
+ website: {
+ anyOf: [
+ {
+ type: "string",
+ maxLength: 200,
+ format: "uri",
+ },
+ {
+ type: "string",
+ const: "",
+ },
+ ],
+ },
+ issues: {
+ anyOf: [
+ {
+ type: "string",
+ maxLength: 200,
+ format: "uri",
+ },
+ {
+ type: "string",
+ const: "",
+ },
+ ],
+ },
+ description: {
type: "string",
- const: "",
+ minLength: 10,
+ maxLength: 1000,
},
+ },
+ required: [
+ "category",
+ "name",
+ "thumbnailAssetId",
+ "author",
+ "email",
+ "description",
],
+ additionalProperties: {},
},
- description: {
- type: "string",
- minLength: 10,
- maxLength: 1000,
+ {
+ type: "null",
},
- },
- required: [
- "category",
- "name",
- "thumbnailAssetId",
- "author",
- "email",
- "description",
],
- additionalProperties: {},
},
},
required: ["marketplaceProduct"],
@@ -1586,7 +1593,7 @@ export const runtimeOperationContractData = [
required: ["updated"],
additionalProperties: {},
},
- readNamespaces: ["marketplaceProduct"],
+ readNamespaces: [],
writeNamespaces: ["marketplaceProduct"],
invalidatesNamespaces: ["marketplaceProduct"],
retryOnConflict: true,
diff --git a/packages/project-build/src/index.ts b/packages/project-build/src/index.ts
index 09d7804f7f..d5790fa7a8 100644
--- a/packages/project-build/src/index.ts
+++ b/packages/project-build/src/index.ts
@@ -2,3 +2,4 @@ export * from "./types";
export * from "./shared/pages-utils";
export * from "./shared/marketplace";
export * from "./shared/project-settings";
+export * from "./content-database";
diff --git a/packages/project-build/src/mcp.test.ts b/packages/project-build/src/mcp.test.ts
index 65b0a90463..abfe08868e 100644
--- a/packages/project-build/src/mcp.test.ts
+++ b/packages/project-build/src/mcp.test.ts
@@ -4409,6 +4409,13 @@ describe("project session mcp adapter", () => {
name: "meta.guide",
input: { brief: "Render an array of blog posts as repeated cards" },
});
+ const markdownBlogGuide = await adapter.callTool({
+ name: "meta.guide",
+ input: {
+ brief:
+ "Create a Markdown-based blog with overview and post pages from Assets",
+ },
+ });
const expressionGuide = await adapter.callTool({
name: "meta.guide",
input: { brief: "Bind a dynamic expression to a prop" },
@@ -4502,6 +4509,25 @@ describe("project session mcp adapter", () => {
]),
})
);
+ expect(markdownBlogGuide.structuredContent.data).toEqual(
+ expect.objectContaining({
+ workflow: expect.arrayContaining([
+ expect.stringContaining("exactly two Builder pages"),
+ expect.stringContaining('fixed path "/blog"'),
+ expect.stringContaining('dynamic path "/blog/:slug"'),
+ expect.stringContaining("Do not create one page per post"),
+ expect.stringContaining('content.mode:"none"'),
+ expect.stringContaining('field:["extension"]'),
+ expect.stringContaining("system.params.slug"),
+ expect.stringContaining("both pages load their content from Assets"),
+ ]),
+ tools: expect.arrayContaining([
+ expect.objectContaining({ name: "list-pages" }),
+ expect.objectContaining({ name: "list-assets" }),
+ expect.objectContaining({ name: "insert-collection" }),
+ ]),
+ })
+ );
expect(expressionGuide.structuredContent.data).toEqual(
expect.objectContaining({
workflow: expect.arrayContaining([
diff --git a/packages/project-build/src/mcp.ts b/packages/project-build/src/mcp.ts
index 6de3094a6e..a4bd7616da 100644
--- a/packages/project-build/src/mcp.ts
+++ b/packages/project-build/src/mcp.ts
@@ -5483,6 +5483,30 @@ const getMetaIndex = (
};
const metaGoalGuides = [
+ {
+ pattern:
+ /markdown(?:-|\s)*(?:based|backed)?\s*blog|blog.*markdown|assets?(?:-|\s)*backed\s*blog/i,
+ tools: [
+ "list-pages",
+ "list-assets",
+ "get-asset-field-catalog",
+ "validate-asset-query",
+ "preview-asset-query",
+ "create-page",
+ "create-assets-resource",
+ "insert-fragment-verified",
+ "insert-collection",
+ "verify-page-responsive",
+ ],
+ workflow: [
+ 'Ensure the blog has exactly two Builder pages: an overview at the fixed path "/blog" and one detail page at the dynamic path "/blog/:slug". Both pages load their content from Assets resources. Do not create one page per post or copy Markdown content into page-specific static structures.',
+ 'For both queries, add static Markdown and blog-folder constraints before any dynamic condition. Include a filter shaped like field:["extension"], operator:"eq", value:"md", plus the narrowest folder or path filter supported by the asset field catalog. This prevents images and unrelated files from consuming the published content-database budget.',
+ 'Create the overview Assets resource under the /blog page root. Request only the fields rendered by the listing, use content.mode:"none", and bind one Collection to the complete posts.data map. The overview route is fixed, but its listing remains data-driven through Assets.',
+ 'Create the detail Assets resource under the /blog/:slug page root with the same static Markdown/folder constraints, a slug or alternate-ID condition whose value is system.params.slug, limit:1, and content.mode:"markdown-body". Bind the selected item metadata and item.content.text; do not materialize a separate Builder page for each query result.',
+ "Validate both queries and preview the detail query with one concrete slug before saving dynamic expressions. Query-preview diagnostics report this query separately from the merged published database; use the merged database measurement when checking the deployment limit.",
+ "Verify that exactly the two intended page definitions exist and that both pages load their content from Assets. Preview /blog and one concrete detail route, including empty/not-found behavior, before finishing.",
+ ],
+ },
{
pattern: /json\s*-?\s*ld|structured\s+data/i,
tools: [
diff --git a/packages/project-build/src/project-session.test.ts b/packages/project-build/src/project-session.test.ts
index 5abcfc6790..4b6bc3ca6e 100644
--- a/packages/project-build/src/project-session.test.ts
+++ b/packages/project-build/src/project-session.test.ts
@@ -433,6 +433,52 @@ describe("project session", () => {
]);
});
+ test("creates marketplace metadata from an unconfigured session", async () => {
+ const remote = createSnapshot();
+ remote.state.marketplaceProduct = undefined;
+ const transport = createMutableTransport(remote);
+ const session = createSession({ storage: createStorage(), transport });
+ const marketplaceProduct = {
+ category: "pageTemplates" as const,
+ name: "Acme Template",
+ thumbnailAssetId: "asset-id",
+ author: "Acme Studio",
+ email: "[email protected]",
+ website: "https://example.com",
+ issues: "",
+ description: "Reusable template project for Acme landing pages.",
+ };
+
+ const update = await session.mutate(
+ "projectSettings.updateMarketplaceProduct",
+ marketplaceProduct
+ );
+ expect(update.state.committed).toBe(true);
+
+ await session.refresh(["marketplaceProduct"]);
+ const product = await session.read(
+ "projectSettings.getMarketplaceProduct",
+ {}
+ );
+ expect(product.result).toEqual({ marketplaceProduct });
+ });
+
+ test("loads configured marketplace metadata in a cold session", async () => {
+ const remote = createSnapshot();
+ const transport = createTransport(remote);
+ const session = createSession({ storage: createStorage(), transport });
+
+ const product = await session.read(
+ "projectSettings.getMarketplaceProduct",
+ {}
+ );
+
+ expect(product.result).toEqual({
+ marketplaceProduct: remote.state.marketplaceProduct,
+ });
+ expect(transport.loadedNamespaces).toEqual([["marketplaceProduct"]]);
+ });
+
test("duplicates a page from a cold session with assets hydrated", async () => {
const remote = createSnapshot({
state: createBuilderStateFromSnapshot({
diff --git a/packages/project-build/src/runtime/output-schemas.ts b/packages/project-build/src/runtime/output-schemas.ts
index 4cf46f9f53..3e09883ec3 100644
--- a/packages/project-build/src/runtime/output-schemas.ts
+++ b/packages/project-build/src/runtime/output-schemas.ts
@@ -357,7 +357,7 @@ export const runtimeOutputSchemas = {
}),
"projectSettings.update": looseObject({ updated: z.boolean() }),
"projectSettings.getMarketplaceProduct": looseObject({
- marketplaceProduct: looseObject(marketplaceProduct.shape),
+ marketplaceProduct: looseObject(marketplaceProduct.shape).nullable(),
}),
"projectSettings.updateMarketplaceProduct": looseObject({
updated: z.boolean(),
diff --git a/packages/project-build/src/runtime/pages.ts b/packages/project-build/src/runtime/pages.ts
index 29cd6ddc20..103f075637 100644
--- a/packages/project-build/src/runtime/pages.ts
+++ b/packages/project-build/src/runtime/pages.ts
@@ -952,7 +952,7 @@ const pageStatusExpressionInput = z
.describe(pageStatusFieldHint);
export const pagePathFieldHint =
- 'Plain page path. For a new non-home page, start with "/", for example "/pricing". The home page path is the empty string ""; do not use an empty path when creating a new page.';
+ 'Plain page path. For a new non-home page, start with "/", for example "/pricing". Use colon-prefixed dynamic segments such as "/blog/:slug" when one page definition must render many concrete routes; do not create a separate page for every route value. The home page path is the empty string ""; do not use an empty path when creating a new page.';
export const pageDraftFieldHint =
"Set true to mark the page as draft. Draft pages remain editable and previewable in Builder but are omitted from every publish target, including staging, and from sitemap output. Set false to stage the page for a future publish; this does not deploy the site. The home page and /* catch-all page cannot be drafts.";
diff --git a/packages/project-build/src/runtime/project-settings.test.ts b/packages/project-build/src/runtime/project-settings.test.ts
index 574e6e516b..60c3284126 100644
--- a/packages/project-build/src/runtime/project-settings.test.ts
+++ b/packages/project-build/src/runtime/project-settings.test.ts
@@ -410,12 +410,46 @@ describe("project settings runtime", () => {
});
});
+ test("creates marketplace product when it is not configured", () => {
+ const state = createState();
+ state.marketplaceProduct = undefined;
+ const nextMarketplaceProduct = {
+ category: "sectionTemplates" as const,
+ name: "New Marketplace Product",
+ thumbnailAssetId: "new-asset-id",
+ author: "Webstudio",
+ email: "[email protected]",
+ website: "",
+ issues: "",
+ description: "A reusable section template for marketplace testing.",
+ };
+
+ expect(updateMarketplaceProduct(state, nextMarketplaceProduct)).toEqual(
+ expect.objectContaining({
+ payload: [
+ {
+ namespace: "marketplaceProduct",
+ patches: [
+ { op: "replace", path: [], value: nextMarketplaceProduct },
+ ],
+ },
+ ],
+ })
+ );
+ });
+
test("gets marketplace product", () => {
const state = createState();
expect(getMarketplaceProduct(state)).toEqual({
marketplaceProduct: state.marketplaceProduct,
});
});
+
+ test("reports an unconfigured marketplace product", () => {
+ expect(getMarketplaceProduct({ marketplaceProduct: undefined })).toEqual({
+ marketplaceProduct: null,
+ });
+ });
});
describe("redirect runtime", () => {
diff --git a/packages/project-build/src/runtime/project-settings.ts b/packages/project-build/src/runtime/project-settings.ts
index 1673755317..5dcba7531b 100644
--- a/packages/project-build/src/runtime/project-settings.ts
+++ b/packages/project-build/src/runtime/project-settings.ts
@@ -241,15 +241,9 @@ export const updateProjectSettings = (
};
export const updateMarketplaceProduct = (
- state: Pick<BuilderState, "marketplaceProduct">,
+ _state: Pick<BuilderState, "marketplaceProduct">,
input: MarketplaceProduct
) => {
- if (state.marketplaceProduct === undefined) {
- return throwBuilderRuntimeError(
- "BAD_REQUEST",
- "Marketplace product namespace is missing"
- );
- }
return createRuntimeMutation({
payload: compactBuilderPatchPayload([
{
@@ -265,13 +259,7 @@ export const updateMarketplaceProduct = (
export const getMarketplaceProduct = (
state: Pick<BuilderState, "marketplaceProduct">
) => {
- if (state.marketplaceProduct === undefined) {
- return throwBuilderRuntimeError(
- "BAD_REQUEST",
- "Marketplace product namespace is missing"
- );
- }
- return { marketplaceProduct: state.marketplaceProduct };
+ return { marketplaceProduct: state.marketplaceProduct ?? null };
};
const paginateProjectSettingItems = <Item>(
diff --git a/packages/project-build/src/runtime/registry.ts b/packages/project-build/src/runtime/registry.ts
index d6cb2452bb..95fa6fc61f 100644
--- a/packages/project-build/src/runtime/registry.ts
+++ b/packages/project-build/src/runtime/registry.ts
@@ -530,7 +530,7 @@ export const builderRuntimeOperations = [
"projectSettings.updateMarketplaceProduct",
api("update-marketplace-product", "updateMarketplaceProduct"),
mutationContract({
- readNamespaces: ["marketplaceProduct"],
+ readNamespaces: [],
writeNamespaces: ["marketplaceProduct"],
retryOnConflict: true,
}),
diff --git a/packages/protocol/src/builder-api/__generated__/server-only-router-operation-metadata.ts b/packages/protocol/src/builder-api/__generated__/server-only-router-operation-metadata.ts
index 1dc9088ab3..a729569301 100644
--- a/packages/protocol/src/builder-api/__generated__/server-only-router-operation-metadata.ts
+++ b/packages/protocol/src/builder-api/__generated__/server-only-router-operation-metadata.ts
@@ -50,6 +50,26 @@ export const serverOnlyRouterOperationMetadata = {
additionalProperties: true,
},
},
+ "projects.submitMarketplaceProduct": {
+ id: "projects.submitMarketplaceProduct",
+ command: "submit-marketplace-product",
+ method: "mutation",
+ path: "api.projects.submitMarketplaceProduct",
+ client: "submitMarketplaceProduct",
+ permit: "edit",
+ inputSchema: {
+ type: "object",
+ properties: {
+ acknowledgePublicSubmission: {
+ type: "boolean",
+ const: true,
+ description:
+ "Acknowledge that submission starts public marketplace review",
+ },
+ },
+ required: ["acknowledgePublicSubmission"],
+ },
+ },
"build.get": {
id: "build.get",
command: "snapshot",
diff --git a/packages/protocol/src/builder-api/operation-docs.ts b/packages/protocol/src/builder-api/operation-docs.ts
index c122eb7611..e47541e2f3 100644
--- a/packages/protocol/src/builder-api/operation-docs.ts
+++ b/packages/protocol/src/builder-api/operation-docs.ts
@@ -103,6 +103,13 @@ const curatedPublicApiOperationDocumentation = [
"webstudio update-marketplace-product --input marketplace-product.json --json",
],
},
+ {
+ command: "submit-marketplace-product",
+ description:
+ "Submit the configured marketplace product for review after updating its metadata and publishing the project",
+ requiredOptions: ["confirm", "json"],
+ examples: ["webstudio submit-marketplace-product --confirm --json"],
+ },
{
command: "list-redirects",
description: "List project redirects",
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 9953c92a29..7e90eceda4 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -240,7 +240,7 @@ importers:
specifier: workspace:*
version: link:../../packages/authorization-token
'@webstudio-is/content-engine':
- specifier: workspace:0.0.0-webstudio-version
+ specifier: workspace:*
version: link:../../packages/content-engine
'@webstudio-is/css-data':
specifier: workspace:*