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.

feat: Add storage-backed document graph resolution (#5966)

Oleg Isonen56a22fde8ac2
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
deleted file mode 100644
index 39d3b7cb27..0000000000
--- a/apps/builder/app/builder/features/publish/content-database-publish-warning.test.ts
+++ /dev/null
@@ -1,9 +0,0 @@
-import { describe, expect, test } from "vitest";
-import { shouldShowContentDatabasePublishWarningToast } from "./content-database-publish-warning";
-
-describe("content database publish warning", () => {
- 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.tsx b/apps/builder/app/builder/features/publish/content-database-publish-warning.tsx
index fd2b28fa03..7e0fa95796 100644
--- a/apps/builder/app/builder/features/publish/content-database-publish-warning.tsx
+++ b/apps/builder/app/builder/features/publish/content-database-publish-warning.tsx
@@ -1,12 +1,7 @@
-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;
+import { showPublishWarning } from "./publish-warning";
export const showContentDatabasePublishWarning = async ({
projectId,
@@ -27,12 +22,5 @@ export const showContentDatabasePublishWarning = async ({
return;
}
const message = <ContentDatabasePublishWarning diagnostics={diagnostics} />;
- if (
- shouldShowContentDatabasePublishWarningToast(
- $publishDialog.get() !== "none"
- )
- ) {
- toast.warn(message);
- }
- setWarning(message);
+ showPublishWarning({ message, setWarning });
};
diff --git a/apps/builder/app/builder/features/publish/publish-warning.test.tsx b/apps/builder/app/builder/features/publish/publish-warning.test.tsx
new file mode 100644
index 0000000000..955ca0917b
--- /dev/null
+++ b/apps/builder/app/builder/features/publish/publish-warning.test.tsx
@@ -0,0 +1,37 @@
+import { afterEach, describe, expect, test, vi } from "vitest";
+import { toast } from "@webstudio-is/design-system";
+import { $publishDialog } from "../../shared/nano-states";
+import { showPublishWarning } from "./publish-warning";
+
+describe("publish warning", () => {
+ afterEach(() => {
+ $publishDialog.set("none");
+ vi.restoreAllMocks();
+ });
+
+ test.each(["publish", "export"] as const)(
+ "shows the warning inline without a duplicate toast while the %s popover is open",
+ (publishDialog) => {
+ const toastWarn = vi.spyOn(toast, "warn").mockImplementation(() => "");
+ const setWarning = vi.fn();
+ const message = <span>Invalid HTML</span>;
+ $publishDialog.set(publishDialog);
+
+ showPublishWarning({ message, setWarning });
+
+ expect(setWarning).toHaveBeenCalledWith(message);
+ expect(toastWarn).not.toHaveBeenCalled();
+ }
+ );
+
+ test("shows a toast when the publish popover is closed", () => {
+ const toastWarn = vi.spyOn(toast, "warn").mockImplementation(() => "");
+ const setWarning = vi.fn();
+ const message = <span>Invalid HTML</span>;
+
+ showPublishWarning({ message, setWarning });
+
+ expect(setWarning).toHaveBeenCalledWith(message);
+ expect(toastWarn).toHaveBeenCalledWith(message);
+ });
+});
diff --git a/apps/builder/app/builder/features/publish/publish-warning.tsx b/apps/builder/app/builder/features/publish/publish-warning.tsx
new file mode 100644
index 0000000000..ef979d3c02
--- /dev/null
+++ b/apps/builder/app/builder/features/publish/publish-warning.tsx
@@ -0,0 +1,15 @@
+import { toast } from "@webstudio-is/design-system";
+import { $publishDialog } from "../../shared/nano-states";
+
+export const showPublishWarning = ({
+ message,
+ setWarning,
+}: {
+ message: JSX.Element;
+ setWarning: (warning: JSX.Element) => void;
+}) => {
+ if ($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 41ad925100..472fec89cc 100644
--- a/apps/builder/app/builder/features/publish/publish.tsx
+++ b/apps/builder/app/builder/features/publish/publish.tsx
@@ -103,6 +103,7 @@ import {
type PrePublishAuditFinding,
} from "@webstudio-is/project-build/runtime";
import { showContentDatabasePublishWarning } from "./content-database-publish-warning";
+import { showPublishWarning } from "./publish-warning";
const PrePublishAuditMessage = ({
finding,
@@ -638,8 +639,10 @@ const Publish = ({
return;
}
if (auditWarning !== undefined) {
- toast.warn(auditWarning);
- setPublishWarning(auditWarning);
+ showPublishWarning({
+ message: auditWarning,
+ setWarning: setPublishWarning,
+ });
}
// Custom domain checkboxes are disabled on free plan so they are never
@@ -810,8 +813,10 @@ const PublishStatic = ({
return;
}
if (auditWarning !== undefined) {
- toast.warn(auditWarning);
- setPublishWarning(auditWarning);
+ showPublishWarning({
+ message: auditWarning,
+ setWarning: setPublishWarning,
+ });
}
startTransition(async () => {
diff --git a/apps/builder/app/builder/features/settings-panel/content-database-diagnostics-view.test.tsx b/apps/builder/app/builder/features/settings-panel/content-database-diagnostics-view.test.tsx
new file mode 100644
index 0000000000..4144784d08
--- /dev/null
+++ b/apps/builder/app/builder/features/settings-panel/content-database-diagnostics-view.test.tsx
@@ -0,0 +1,97 @@
+/**
+ * @vitest-environment jsdom
+ */
+import { act } from "react-dom/test-utils";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, expect, test } from "vitest";
+import { TooltipProvider } from "@webstudio-is/design-system";
+import type { ContentArtifactV1 } from "@webstudio-is/content-engine";
+import { ContentDatabaseDiagnostics } from "./content-database-diagnostics";
+
+(
+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
+).IS_REACT_ACT_ENVIRONMENT = true;
+
+let root: Root | undefined;
+
+const revision = `sha256:${"a".repeat(64)}`;
+const artifact: ContentArtifactV1 = {
+ format: "webstudio-content-database",
+ version: 1,
+ assetRevision: revision,
+ documents: [
+ {
+ _id: "post",
+ properties: { body: { $ref: "./post.md#body" } },
+ },
+ ],
+ fieldCatalog: {
+ format: "webstudio-builder-asset-field-catalog",
+ version: 1,
+ canonicalRevision: revision,
+ documentCount: 1,
+ fields: {},
+ },
+ integrity: { algorithm: "sha256", checksum: revision },
+};
+
+afterEach(() => {
+ act(() => root?.unmount());
+ root = undefined;
+ document.body.innerHTML = "";
+});
+
+test("shows the unresolved query result in a read-only JSON editor", () => {
+ const container = document.createElement("div");
+ document.body.appendChild(container);
+ root = createRoot(container);
+ act(() => {
+ root?.render(
+ <TooltipProvider>
+ <ContentDatabaseDiagnostics
+ value={{
+ scope: "query-preview",
+ unresolved: {
+ items: [
+ {
+ id: "post",
+ properties: { body: { $ref: "./post.md#body" } },
+ },
+ ],
+ totalCount: 1,
+ hasMore: false,
+ },
+ artifacts: {
+ query: artifact,
+ database: artifact,
+ },
+ query: {
+ usedBytes: 1_000,
+ maxBytes: 500_000,
+ unboundedBytes: 1_000,
+ includedDocumentCount: 1,
+ omittedDocumentCount: 0,
+ truncated: false,
+ },
+ database: {
+ usedBytes: 2_000,
+ maxBytes: 500_000,
+ unboundedBytes: 2_000,
+ includedDocumentCount: 1,
+ omittedDocumentCount: 0,
+ truncated: false,
+ },
+ }}
+ />
+ </TooltipProvider>
+ );
+ });
+
+ const editor = container.querySelector(".cm-content");
+ expect(editor).not.toBeNull();
+ expect(editor?.getAttribute("aria-readonly")).toBe("true");
+ expect(container.textContent).toContain("Unresolved query result");
+ expect(container.textContent).toContain('"$ref": "./post.md#body"');
+ expect(container.textContent).toContain("Query database");
+ expect(container.textContent).toContain("Published database");
+});
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 a2075c6a72..1aac5b7806 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,58 +1,67 @@
import { describe, expect, test } from "vitest";
-import {
- getContentDatabaseDiagnosticRows,
- isDatabaseSizeNearLimit,
-} from "./content-database-diagnostics";
+import type { AssetQueryPreviewDiagnostics } from "@webstudio-is/content-engine";
+import { getContentDatabaseDiagnosticRows } from "./content-database-diagnostics";
+
+const createDiagnostics = ({
+ queryTruncated,
+ databaseTruncated,
+}: {
+ queryTruncated: boolean;
+ databaseTruncated: boolean;
+}): AssetQueryPreviewDiagnostics => ({
+ scope: "query-preview",
+ query: {
+ usedBytes: 20_000,
+ maxBytes: 500_000,
+ unboundedBytes: 20_000,
+ includedDocumentCount: 5,
+ omittedDocumentCount: 0,
+ truncated: queryTruncated,
+ },
+ database: {
+ usedBytes: 35_000,
+ maxBytes: 500_000,
+ unboundedBytes: 600_000,
+ includedDocumentCount: 5,
+ omittedDocumentCount: 1,
+ truncated: databaseTruncated,
+ },
+});
describe("content database diagnostics", () => {
- test("warns when the database reaches 90% of its limit", () => {
- expect(isDatabaseSizeNearLimit({ usedBytes: 899, maxBytes: 1_000 })).toBe(
- false
- );
- expect(isDatabaseSizeNearLimit({ usedBytes: 900, maxBytes: 1_000 })).toBe(
- true
- );
- expect(isDatabaseSizeNearLimit({ usedBytes: 1_000, maxBytes: 1_000 })).toBe(
- true
- );
+ test("highlights only sizes that exceed the limit", () => {
+ expect(
+ getContentDatabaseDiagnosticRows(
+ createDiagnostics({
+ queryTruncated: false,
+ databaseTruncated: true,
+ })
+ )
+ ).toEqual([
+ {
+ label: "Query size",
+ value: "20 kB",
+ valueColor: undefined,
+ description: expect.stringContaining("before the database limit"),
+ },
+ {
+ label: "Database size",
+ value: "600 kB",
+ valueColor: "destructive",
+ description: expect.stringContaining("before the database limit"),
+ },
+ ]);
});
- 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,
- },
+ test("uses the corresponding truncation state for each size", () => {
+ const [queryRow, databaseRow] = getContentDatabaseDiagnosticRows(
+ createDiagnostics({
+ queryTruncated: true,
+ databaseTruncated: false,
})
- ).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",
- }),
- ])
);
+
+ expect(queryRow.valueColor).toBe("destructive");
+ expect(databaseRow.valueColor).toBeUndefined();
});
});
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 1261e56667..3f0eb496b1 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
@@ -1,42 +1,49 @@
import type { AssetQueryPreviewDiagnostics } from "@webstudio-is/content-engine";
-import { PanelBanner, Text } from "@webstudio-is/design-system";
+import { Grid, PanelBanner, Text } from "@webstudio-is/design-system";
import prettyBytes from "pretty-bytes";
+import { CodeEditor } from "~/shared/code-editor";
import {
RequestDiagnosticsContent,
RequestDiagnosticsRow,
RequestDiagnosticsTable,
} from "./request-inspector";
-const databaseSizeWarningRatio = 0.9;
+const runtimeContentNote =
+ "Referenced documents fetched from storage at runtime are not included.";
-export const isDatabaseSizeNearLimit = ({
- usedBytes,
- maxBytes,
-}: Pick<AssetQueryPreviewDiagnostics["database"], "usedBytes" | "maxBytes">) =>
- usedBytes >= maxBytes * databaseSizeWarningRatio;
+const ReadonlyJsonEditor = ({
+ title,
+ value,
+}: {
+ title: string;
+ value: unknown;
+}) => (
+ <Grid gap={1}>
+ <Text variant="titles">{title}</Text>
+ <CodeEditor
+ lang="json"
+ readOnly
+ value={JSON.stringify(value, undefined, 2)}
+ onChange={() => {}}
+ onChangeComplete={() => {}}
+ />
+ </Grid>
+);
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",
+ label: "Query size",
value: prettyBytes(value.query.unboundedBytes),
+ valueColor: value.query.truncated ? ("destructive" as const) : undefined,
+ description: `Temporary query-only footprint before the database limit is applied. It is not added to the published database size. ${runtimeContentNote}`,
},
{
- 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",
+ label: "Database size",
value: prettyBytes(value.database.unboundedBytes),
+ valueColor: value.database.truncated ? ("destructive" as const) : undefined,
+ description: `Merged footprint of all reachable Assets queries before the database limit is applied. ${runtimeContentNote}`,
},
];
@@ -49,7 +56,6 @@ export const ContentDatabaseDiagnostics = ({
value.database.includedDocumentCount + value.database.omittedDocumentCount;
const candidateFilesLabel = `${totalDocumentCount} candidate ${totalDocumentCount === 1 ? "file" : "files"}`;
const omittedFilesLabel = `${value.database.omittedDocumentCount} ${value.database.omittedDocumentCount === 1 ? "file" : "files"}`;
- const isNearLimit = isDatabaseSizeNearLimit(value.database);
const rows = getContentDatabaseDiagnosticRows(value);
return (
<RequestDiagnosticsContent>
@@ -69,15 +75,7 @@ export const ContentDatabaseDiagnostics = ({
value={value.database.truncated ? "Truncated" : "Complete"}
/>
{rows.map((row) => (
- <RequestDiagnosticsRow
- key={row.label}
- {...row}
- valueColor={
- row.label === "Published database" && isNearLimit
- ? "destructive"
- : undefined
- }
- />
+ <RequestDiagnosticsRow key={row.label} {...row} />
))}
<RequestDiagnosticsRow
label="Database limit"
@@ -92,6 +90,32 @@ export const ContentDatabaseDiagnostics = ({
value={value.database.omittedDocumentCount}
/>
</RequestDiagnosticsTable>
+ {value.artifacts !== undefined && (
+ <>
+ <ReadonlyJsonEditor
+ title={
+ value.query.truncated
+ ? "Included query database"
+ : "Query database"
+ }
+ value={value.artifacts.query}
+ />
+ <ReadonlyJsonEditor
+ title={
+ value.database.truncated
+ ? "Included published database"
+ : "Published database"
+ }
+ value={value.artifacts.database}
+ />
+ </>
+ )}
+ {value.unresolved !== undefined && (
+ <ReadonlyJsonEditor
+ title="Unresolved query result"
+ value={value.unresolved}
+ />
+ )}
</RequestDiagnosticsContent>
);
};
diff --git a/apps/builder/app/builder/features/settings-panel/request-inspector.test.tsx b/apps/builder/app/builder/features/settings-panel/request-inspector.test.tsx
index 0c6c54c223..603a628aa3 100644
--- a/apps/builder/app/builder/features/settings-panel/request-inspector.test.tsx
+++ b/apps/builder/app/builder/features/settings-panel/request-inspector.test.tsx
@@ -18,14 +18,17 @@ afterEach(() => {
document.body.innerHTML = "";
});
-const renderInspector = (query: boolean) => {
+const renderInspector = (
+ query: boolean,
+ queryContainerRef: (element: HTMLDivElement | null) => void = () => {}
+) => {
const container = document.createElement("div");
document.body.appendChild(container);
root = createRoot(container);
act(() => {
root?.render(
<RequestInspector
- queryContainerRef={query ? () => {} : undefined}
+ queryContainerRef={query ? queryContainerRef : undefined}
preview={<div>Preview content</div>}
diagnostics={<div>Diagnostics content</div>}
/>
@@ -35,7 +38,10 @@ const renderInspector = (query: boolean) => {
};
test("places an available query editor in the first selected tab", () => {
- const container = renderInspector(true);
+ const queryContainer: { current: HTMLDivElement | null } = { current: null };
+ const container = renderInspector(true, (element) => {
+ queryContainer.current = element;
+ });
const tabs = Array.from(container.querySelectorAll('[role="tab"]'));
expect(tabs.map(({ textContent }) => textContent)).toEqual([
@@ -44,6 +50,9 @@ test("places an available query editor in the first selected tab", () => {
"Diagnostics",
]);
expect(tabs[0].getAttribute("data-state")).toBe("active");
+ expect(queryContainer.current?.style.minHeight).toBe("0");
+ expect(queryContainer.current?.style.minWidth).toBe("0");
+ expect(queryContainer.current?.style.overflow).toBe("hidden");
});
test("keeps preview first when no query editor is available", () => {
diff --git a/apps/builder/app/builder/features/settings-panel/request-inspector.tsx b/apps/builder/app/builder/features/settings-panel/request-inspector.tsx
index aebda5b22a..a8a3e25f91 100644
--- a/apps/builder/app/builder/features/settings-panel/request-inspector.tsx
+++ b/apps/builder/app/builder/features/settings-panel/request-inspector.tsx
@@ -111,7 +111,16 @@ export const RequestInspector = ({
value="query"
css={{ flex: 1, position: "relative", overflow: "hidden" }}
>
- <div ref={queryContainerRef} style={{ height: "100%" }} />
+ <div
+ ref={queryContainerRef}
+ style={{
+ height: "100%",
+ minHeight: 0,
+ minWidth: 0,
+ overflow: "hidden",
+ position: "relative",
+ }}
+ />
</PanelTabsContent>
)}
<PanelTabsContent
diff --git a/apps/builder/app/builder/shared/expression-editor.tsx b/apps/builder/app/builder/shared/expression-editor.tsx
index d5bae17a2d..024f4bc5ac 100644
--- a/apps/builder/app/builder/shared/expression-editor.tsx
+++ b/apps/builder/app/builder/shared/expression-editor.tsx
@@ -529,6 +529,8 @@ const wrapperStyle = css({
full: {
...getCodeEditorCssVars({ minHeight: "100%", maxHeight: "100%" }),
height: "100%",
+ minHeight: 0,
+ overflow: "hidden",
"& > div, & .cm-editor, & .cm-scroller": { height: "100%" },
},
},
@@ -560,6 +562,7 @@ const linterTooltipTheme = EditorView.theme({
const fullSizeEditorTheme = EditorView.theme({
".cm-scroller": {
+ minHeight: 0,
overflow: "auto",
},
});
diff --git a/apps/builder/app/builder/shared/query-builder.test.tsx b/apps/builder/app/builder/shared/query-builder.test.tsx
index 468c4062d1..734b1e2f4a 100644
--- a/apps/builder/app/builder/shared/query-builder.test.tsx
+++ b/apps/builder/app/builder/shared/query-builder.test.tsx
@@ -143,7 +143,7 @@ test("shows an evaluated value for a bound number input", () => {
expect(input?.disabled).toBe(true);
});
-test("allows the full-size query source to scroll in both directions", () => {
+test("renders the query source inside a constrained full-size editor", () => {
const sourceContainer = document.createElement("div");
document.body.appendChild(sourceContainer);
const capabilities = {
@@ -166,7 +166,18 @@ test("allows the full-size query source to scroll in both directions", () => {
sourceContainer,
});
- const scroller = sourceContainer.querySelector(".cm-scroller");
- expect(scroller).not.toBeNull();
- expect(getComputedStyle(scroller as Element).overflow).toBe("auto");
+ const sourceLayout = sourceContainer.firstElementChild;
+ const editorContent = sourceContainer.querySelector(
+ '[data-chromeless="true"]'
+ );
+ const editorLayout = sourceLayout?.firstElementChild;
+ expect(sourceLayout).not.toBeNull();
+ expect(editorLayout).not.toBeNull();
+ expect(editorContent).not.toBeNull();
+ expect(editorLayout?.firstElementChild).toBe(editorContent);
+ const scrollerStyle = getComputedStyle(
+ sourceContainer.querySelector(".cm-scroller") as Element
+ );
+ expect(scrollerStyle.minHeight).toBe("0");
+ expect(scrollerStyle.overflow).toBe("auto");
});
diff --git a/apps/builder/app/builder/shared/query-builder.tsx b/apps/builder/app/builder/shared/query-builder.tsx
index 44a6cbfd55..ad76190116 100644
--- a/apps/builder/app/builder/shared/query-builder.tsx
+++ b/apps/builder/app/builder/shared/query-builder.tsx
@@ -164,9 +164,12 @@ export const BindableQueryBuilder = <
? null
: createPortal(
<Grid
+ align="stretch"
css={{
height: "100%",
- minHeight: 0,
+ overflow: "hidden",
+ boxSizing: "content-box",
+ position: "relative",
gridTemplateRows: "minmax(0, 1fr) auto",
}}
>
diff --git a/apps/builder/app/services/asset-query-preview.server.test.ts b/apps/builder/app/services/asset-query-preview.server.test.ts
index 1a12b2e7a7..6445c670c3 100644
--- a/apps/builder/app/services/asset-query-preview.server.test.ts
+++ b/apps/builder/app/services/asset-query-preview.server.test.ts
@@ -48,4 +48,28 @@ describe("project asset query preview", () => {
}),
});
});
+
+ test("includes unresolved diagnostics only when requested", async () => {
+ const context = {} as never;
+ const build = { props: [], dataSources: [], resources: [] } as never;
+ const previewAssetResourceQuery = vi.fn().mockResolvedValue({});
+
+ await previewProjectAssetQuery(
+ {
+ projectId: "project-1",
+ request: { query: { limit: 1 } },
+ context,
+ includeUnresolvedDiagnostics: true,
+ },
+ {
+ createAssetClient: vi.fn(() => ({}) as never),
+ loadDevBuildByProjectId: vi.fn().mockResolvedValue(build),
+ previewAssetResourceQuery,
+ }
+ );
+
+ expect(previewAssetResourceQuery).toHaveBeenCalledWith(
+ expect.objectContaining({ includeUnresolvedDiagnostics: true })
+ );
+ });
});
diff --git a/apps/builder/app/services/asset-query-preview.server.ts b/apps/builder/app/services/asset-query-preview.server.ts
index eb978d7a69..4a411507ea 100644
--- a/apps/builder/app/services/asset-query-preview.server.ts
+++ b/apps/builder/app/services/asset-query-preview.server.ts
@@ -17,10 +17,12 @@ export const previewProjectAssetQuery = async (
projectId,
request,
context,
+ includeUnresolvedDiagnostics,
}: {
projectId: string;
request: AssetQueryRequestInput;
context: AppContext;
+ includeUnresolvedDiagnostics?: boolean;
},
dependencies = defaultDependencies
) => {
@@ -35,5 +37,8 @@ export const previewProjectAssetQuery = async (
build,
query: request.query,
}),
+ ...(includeUnresolvedDiagnostics === true
+ ? { includeUnresolvedDiagnostics: true }
+ : {}),
});
};
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 8142e39655..0a1482b6ea 100644
--- a/apps/builder/app/shared/$resources/assets-query.server.test.ts
+++ b/apps/builder/app/shared/$resources/assets-query.server.test.ts
@@ -91,6 +91,7 @@ describe("configured Assets system resource", () => {
}),
},
context: expect.anything(),
+ includeUnresolvedDiagnostics: true,
});
});
diff --git a/apps/builder/app/shared/$resources/assets-query.server.ts b/apps/builder/app/shared/$resources/assets-query.server.ts
index d1c144b1ac..dcc6b916fe 100644
--- a/apps/builder/app/shared/$resources/assets-query.server.ts
+++ b/apps/builder/app/shared/$resources/assets-query.server.ts
@@ -67,6 +67,7 @@ export const executeAssetQuery = async (
projectId,
request: parsed,
context,
+ includeUnresolvedDiagnostics: true,
});
return json(result, { headers: privateNoStoreResponseHeaders });
} catch (error) {
diff --git a/fixtures/react-router-cloudflare/.webstudio/data.json b/fixtures/react-router-cloudflare/.webstudio/data.json
index b3a725eb3a..018b75f45a 100644
--- a/fixtures/react-router-cloudflare/.webstudio/data.json
+++ b/fixtures/react-router-cloudflare/.webstudio/data.json
@@ -1,5 +1,5 @@
{
- "bundleVersion": "bundle-1kghc5n",
+ "bundleVersion": "bundle-7ljlhp",
"build": {
"id": "f565d527-32e7-4731-bc71-aca9e9574587",
"projectId": "d845c167-ea07-4875-b08d-83e97c09dcce",
diff --git a/fixtures/react-router-cloudflare/app/__generated__/$resources.assets.ts b/fixtures/react-router-cloudflare/app/__generated__/$resources.assets.ts
index 2a5c535b6a..b8478a593d 100644
--- a/fixtures/react-router-cloudflare/app/__generated__/$resources.assets.ts
+++ b/fixtures/react-router-cloudflare/app/__generated__/$resources.assets.ts
@@ -3,12 +3,14 @@
"1d8bf4398f643f5333d415091507d778aaed62f28883642636cbed0be156a0ee": {
"url": "/assets/iconly_svg_converted-converted_zMaMiAAutUl8XrITgz7d1.svg",
"width": 14,
- "height": 16
+ "height": 16,
+ "contentRef": "iconly_svg_converted-converted_zMaMiAAutUl8XrITgz7d1.svg"
},
"d0974db9300c1a3b0fb8b291dd9fabd45ad136478908394280af2f7087e3aecd": {
"url": "/assets/147-1478573_cat-icon-png-black-cat-png-icon.png_ZJ6-qJjk1RlFzuYwyCXdp.jpeg",
"width": 820,
- "height": 985
+ "height": 985,
+ "contentRef": "147-1478573_cat-icon-png-black-cat-png-icon.png_ZJ6-qJjk1RlFzuYwyCXdp.jpeg"
}
};
\ No newline at end of file
diff --git a/fixtures/react-router-docker/.webstudio/data.json b/fixtures/react-router-docker/.webstudio/data.json
index b3a725eb3a..018b75f45a 100644
--- a/fixtures/react-router-docker/.webstudio/data.json
+++ b/fixtures/react-router-docker/.webstudio/data.json
@@ -1,5 +1,5 @@
{
- "bundleVersion": "bundle-1kghc5n",
+ "bundleVersion": "bundle-7ljlhp",
"build": {
"id": "f565d527-32e7-4731-bc71-aca9e9574587",
"projectId": "d845c167-ea07-4875-b08d-83e97c09dcce",
diff --git a/fixtures/react-router-docker/app/__generated__/$resources.assets.ts b/fixtures/react-router-docker/app/__generated__/$resources.assets.ts
index 2a5c535b6a..b8478a593d 100644
--- a/fixtures/react-router-docker/app/__generated__/$resources.assets.ts
+++ b/fixtures/react-router-docker/app/__generated__/$resources.assets.ts
@@ -3,12 +3,14 @@
"1d8bf4398f643f5333d415091507d778aaed62f28883642636cbed0be156a0ee": {
"url": "/assets/iconly_svg_converted-converted_zMaMiAAutUl8XrITgz7d1.svg",
"width": 14,
- "height": 16
+ "height": 16,
+ "contentRef": "iconly_svg_converted-converted_zMaMiAAutUl8XrITgz7d1.svg"
},
"d0974db9300c1a3b0fb8b291dd9fabd45ad136478908394280af2f7087e3aecd": {
"url": "/assets/147-1478573_cat-icon-png-black-cat-png-icon.png_ZJ6-qJjk1RlFzuYwyCXdp.jpeg",
"width": 820,
- "height": 985
+ "height": 985,
+ "contentRef": "147-1478573_cat-icon-png-black-cat-png-icon.png_ZJ6-qJjk1RlFzuYwyCXdp.jpeg"
}
};
\ No newline at end of file
diff --git a/fixtures/react-router-docker/vite.config.ts b/fixtures/react-router-docker/vite.config.ts
index f8a0782b3c..482f370c3a 100644
--- a/fixtures/react-router-docker/vite.config.ts
+++ b/fixtures/react-router-docker/vite.config.ts
@@ -13,6 +13,7 @@ export default defineConfig({
conditions: [...sourceConditions, "browser", "development|production"],
},
ssr: {
+ noExternal: ["nanoid"],
resolve: {
conditions: [...sourceConditions, "node", "development|production"],
},
diff --git a/fixtures/react-router-netlify/.webstudio/data.json b/fixtures/react-router-netlify/.webstudio/data.json
index b3a725eb3a..018b75f45a 100644
--- a/fixtures/react-router-netlify/.webstudio/data.json
+++ b/fixtures/react-router-netlify/.webstudio/data.json
@@ -1,5 +1,5 @@
{
- "bundleVersion": "bundle-1kghc5n",
+ "bundleVersion": "bundle-7ljlhp",
"build": {
"id": "f565d527-32e7-4731-bc71-aca9e9574587",
"projectId": "d845c167-ea07-4875-b08d-83e97c09dcce",
diff --git a/fixtures/react-router-netlify/app/__generated__/$resources.assets.ts b/fixtures/react-router-netlify/app/__generated__/$resources.assets.ts
index 2a5c535b6a..b8478a593d 100644
--- a/fixtures/react-router-netlify/app/__generated__/$resources.assets.ts
+++ b/fixtures/react-router-netlify/app/__generated__/$resources.assets.ts
@@ -3,12 +3,14 @@
"1d8bf4398f643f5333d415091507d778aaed62f28883642636cbed0be156a0ee": {
"url": "/assets/iconly_svg_converted-converted_zMaMiAAutUl8XrITgz7d1.svg",
"width": 14,
- "height": 16
+ "height": 16,
+ "contentRef": "iconly_svg_converted-converted_zMaMiAAutUl8XrITgz7d1.svg"
},
"d0974db9300c1a3b0fb8b291dd9fabd45ad136478908394280af2f7087e3aecd": {
"url": "/assets/147-1478573_cat-icon-png-black-cat-png-icon.png_ZJ6-qJjk1RlFzuYwyCXdp.jpeg",
"width": 820,
- "height": 985
+ "height": 985,
+ "contentRef": "147-1478573_cat-icon-png-black-cat-png-icon.png_ZJ6-qJjk1RlFzuYwyCXdp.jpeg"
}
};
\ No newline at end of file
diff --git a/fixtures/react-router-vercel/.webstudio/data.json b/fixtures/react-router-vercel/.webstudio/data.json
index b3a725eb3a..018b75f45a 100644
--- a/fixtures/react-router-vercel/.webstudio/data.json
+++ b/fixtures/react-router-vercel/.webstudio/data.json
@@ -1,5 +1,5 @@
{
- "bundleVersion": "bundle-1kghc5n",
+ "bundleVersion": "bundle-7ljlhp",
"build": {
"id": "f565d527-32e7-4731-bc71-aca9e9574587",
"projectId": "d845c167-ea07-4875-b08d-83e97c09dcce",
diff --git a/fixtures/react-router-vercel/app/__generated__/$resources.assets.ts b/fixtures/react-router-vercel/app/__generated__/$resources.assets.ts
index 2a5c535b6a..b8478a593d 100644
--- a/fixtures/react-router-vercel/app/__generated__/$resources.assets.ts
+++ b/fixtures/react-router-vercel/app/__generated__/$resources.assets.ts
@@ -3,12 +3,14 @@
"1d8bf4398f643f5333d415091507d778aaed62f28883642636cbed0be156a0ee": {
"url": "/assets/iconly_svg_converted-converted_zMaMiAAutUl8XrITgz7d1.svg",
"width": 14,
- "height": 16
+ "height": 16,
+ "contentRef": "iconly_svg_converted-converted_zMaMiAAutUl8XrITgz7d1.svg"
},
"d0974db9300c1a3b0fb8b291dd9fabd45ad136478908394280af2f7087e3aecd": {
"url": "/assets/147-1478573_cat-icon-png-black-cat-png-icon.png_ZJ6-qJjk1RlFzuYwyCXdp.jpeg",
"width": 820,
- "height": 985
+ "height": 985,
+ "contentRef": "147-1478573_cat-icon-png-black-cat-png-icon.png_ZJ6-qJjk1RlFzuYwyCXdp.jpeg"
}
};
\ No newline at end of file
diff --git a/fixtures/react-router-vercel/vite.config.ts b/fixtures/react-router-vercel/vite.config.ts
index f8a0782b3c..482f370c3a 100644
--- a/fixtures/react-router-vercel/vite.config.ts
+++ b/fixtures/react-router-vercel/vite.config.ts
@@ -13,6 +13,7 @@ export default defineConfig({
conditions: [...sourceConditions, "browser", "development|production"],
},
ssr: {
+ noExternal: ["nanoid"],
resolve: {
conditions: [...sourceConditions, "node", "development|production"],
},
diff --git a/fixtures/ssg-cloudflare-pages/.webstudio/data.json b/fixtures/ssg-cloudflare-pages/.webstudio/data.json
index e0ac58547f..91913915dc 100644
--- a/fixtures/ssg-cloudflare-pages/.webstudio/data.json
+++ b/fixtures/ssg-cloudflare-pages/.webstudio/data.json
@@ -1,5 +1,5 @@
{
- "bundleVersion": "bundle-1kghc5n",
+ "bundleVersion": "bundle-7ljlhp",
"build": {
"id": "a2e8de30-03d5-4514-a3a6-406b3266a3af",
"projectId": "d845c167-ea07-4875-b08d-83e97c09dcce",
diff --git a/fixtures/ssg-cloudflare-pages/app/__generated__/$resources.assets.ts b/fixtures/ssg-cloudflare-pages/app/__generated__/$resources.assets.ts
index 2a5c535b6a..b8478a593d 100644
--- a/fixtures/ssg-cloudflare-pages/app/__generated__/$resources.assets.ts
+++ b/fixtures/ssg-cloudflare-pages/app/__generated__/$resources.assets.ts
@@ -3,12 +3,14 @@
"1d8bf4398f643f5333d415091507d778aaed62f28883642636cbed0be156a0ee": {
"url": "/assets/iconly_svg_converted-converted_zMaMiAAutUl8XrITgz7d1.svg",
"width": 14,
- "height": 16
+ "height": 16,
+ "contentRef": "iconly_svg_converted-converted_zMaMiAAutUl8XrITgz7d1.svg"
},
"d0974db9300c1a3b0fb8b291dd9fabd45ad136478908394280af2f7087e3aecd": {
"url": "/assets/147-1478573_cat-icon-png-black-cat-png-icon.png_ZJ6-qJjk1RlFzuYwyCXdp.jpeg",
"width": 820,
- "height": 985
+ "height": 985,
+ "contentRef": "147-1478573_cat-icon-png-black-cat-png-icon.png_ZJ6-qJjk1RlFzuYwyCXdp.jpeg"
}
};
\ No newline at end of file
diff --git a/fixtures/ssg-netlify-by-project-id/.webstudio/data.json b/fixtures/ssg-netlify-by-project-id/.webstudio/data.json
index 80690523f8..fa26559da3 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-1kghc5n",
+ "bundleVersion": "bundle-7ljlhp",
"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 e0ac58547f..91913915dc 100644
--- a/fixtures/webstudio-cloudflare-template/.webstudio/data.json
+++ b/fixtures/webstudio-cloudflare-template/.webstudio/data.json
@@ -1,5 +1,5 @@
{
- "bundleVersion": "bundle-1kghc5n",
+ "bundleVersion": "bundle-7ljlhp",
"build": {
"id": "a2e8de30-03d5-4514-a3a6-406b3266a3af",
"projectId": "d845c167-ea07-4875-b08d-83e97c09dcce",
diff --git a/fixtures/webstudio-cloudflare-template/app/__generated__/$resources.assets.ts b/fixtures/webstudio-cloudflare-template/app/__generated__/$resources.assets.ts
index 2a5c535b6a..b8478a593d 100644
--- a/fixtures/webstudio-cloudflare-template/app/__generated__/$resources.assets.ts
+++ b/fixtures/webstudio-cloudflare-template/app/__generated__/$resources.assets.ts
@@ -3,12 +3,14 @@
"1d8bf4398f643f5333d415091507d778aaed62f28883642636cbed0be156a0ee": {
"url": "/assets/iconly_svg_converted-converted_zMaMiAAutUl8XrITgz7d1.svg",
"width": 14,
- "height": 16
+ "height": 16,
+ "contentRef": "iconly_svg_converted-converted_zMaMiAAutUl8XrITgz7d1.svg"
},
"d0974db9300c1a3b0fb8b291dd9fabd45ad136478908394280af2f7087e3aecd": {
"url": "/assets/147-1478573_cat-icon-png-black-cat-png-icon.png_ZJ6-qJjk1RlFzuYwyCXdp.jpeg",
"width": 820,
- "height": 985
+ "height": 985,
+ "contentRef": "147-1478573_cat-icon-png-black-cat-png-icon.png_ZJ6-qJjk1RlFzuYwyCXdp.jpeg"
}
};
\ No newline at end of file
diff --git a/fixtures/webstudio-features/.webstudio/data.json b/fixtures/webstudio-features/.webstudio/data.json
index b8733301b0..be5f6bb7af 100644
--- a/fixtures/webstudio-features/.webstudio/data.json
+++ b/fixtures/webstudio-features/.webstudio/data.json
@@ -1,5 +1,5 @@
{
- "bundleVersion": "bundle-1kghc5n",
+ "bundleVersion": "bundle-7ljlhp",
"build": {
"id": "1b66ee06-8ea5-4420-9a0e-e0d3a67aca32",
"projectId": "cddc1d44-af37-4cb6-a430-d300cf6f932d",
diff --git a/fixtures/webstudio-features/app/__generated__/$resources.asset-query-manifest.ts b/fixtures/webstudio-features/app/__generated__/$resources.asset-query-manifest.ts
index 1f405c174c..6aa65a7c75 100644
--- a/fixtures/webstudio-features/app/__generated__/$resources.asset-query-manifest.ts
+++ b/fixtures/webstudio-features/app/__generated__/$resources.asset-query-manifest.ts
@@ -1,2 +1,2 @@
export const assetQueryDeploymentId = "1b66ee06-8ea5-4420-9a0e-e0d3a67aca32";
-export const assetQueryDatabase = {"assetRevision":"sha256:55e51683a123fa9724ffe8c4e71de1e342708975690008480005002d2c1e739e","database":{"maxBytes":512000,"sourceDocumentCount":7,"unboundedBytes":1023},"documents":[{"_id":"2b151fc7b4b0324e6ab78c40f72c7f59273f81fb1be3d08b3f9976428601b95e"},{"_id":"42e55b0464790758b9352d675cf28fadfcf8a3259fc1e890100617d3e731be88"},{"_id":"4afe692f78ec0530e355a551a3860302c4478037db7b25a3bdae82c32c78634d"},{"_id":"7cf5892080fa66b5e6175ffd2d27c304ee6b09ce1f21847a95000225ad1afa59"},{"_id":"9a8bc926-7804-4d3f-af81-69196b1d2ed8"},{"_id":"cbf6b1b052e52b256cef54a032a546bf43bf3f5441be4d1c5eeaabce26903d78"},{"_id":"cd939c56-bcdd-4e64-bd9c-567a9bccd3da"}],"fieldCatalog":{"canonicalRevision":"sha256:55e51683a123fa9724ffe8c4e71de1e342708975690008480005002d2c1e739e","documentCount":7,"fields":{},"format":"webstudio-builder-asset-field-catalog","version":1},"format":"webstudio-content-database","integrity":{"algorithm":"sha256","checksum":"sha256:8ec5939a945f85326475b8351e5a343e82b9c6971c490550a9e2dd4079503225"},"version":1};
+export const assetQueryDatabase = {"documents":[{"_id":"2b151fc7b4b0324e6ab78c40f72c7f59273f81fb1be3d08b3f9976428601b95e"},{"_id":"42e55b0464790758b9352d675cf28fadfcf8a3259fc1e890100617d3e731be88"},{"_id":"4afe692f78ec0530e355a551a3860302c4478037db7b25a3bdae82c32c78634d"},{"_id":"7cf5892080fa66b5e6175ffd2d27c304ee6b09ce1f21847a95000225ad1afa59"},{"_id":"9a8bc926-7804-4d3f-af81-69196b1d2ed8"},{"_id":"cbf6b1b052e52b256cef54a032a546bf43bf3f5441be4d1c5eeaabce26903d78"},{"_id":"cd939c56-bcdd-4e64-bd9c-567a9bccd3da"}],"revision":"sha256:8ec5939a945f85326475b8351e5a343e82b9c6971c490550a9e2dd4079503225"};
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 95b697272e..c1c75d42ca 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,194 @@
-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 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 => ({
+var Af=Object.defineProperty;var Df=(e,t)=>{for(var n in t)Af(e,n,{get:t[n],enumerable:!0})};var vs;function g(e,t,n){function r(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,d=Object.keys(u);for(let l=0;l<d.length;l++){let f=d[l];f in c||(c[f]=u[f].bind(c))}}let o=n?.Parent??Object;class s extends o{}Object.defineProperty(s,"name",{value:e});function i(c){var a;let u=n?.Parent?new s:this;r(u,c),(a=u._zod).deferred??(a.deferred=[]);for(let d of u._zod.deferred)d();return u}return Object.defineProperty(i,"init",{value:r}),Object.defineProperty(i,Symbol.hasInstance,{value:c=>n?.Parent&&c instanceof n.Parent?!0:c?._zod?.traits?.has(e)}),Object.defineProperty(i,"name",{value:e}),i}var yh=Symbol("zod_brand"),De=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},_t=class extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}};(vs=globalThis).__zod_globalConfig??(vs.__zod_globalConfig={});var xt=globalThis.__zod_globalConfig;function he(e){return e&&Object.assign(xt,e),xt}var z={};Df(z,{BIGINT_FORMAT_RANGES:()=>Os,Class:()=>Yr,NUMBER_FORMAT_RANGES:()=>ro,aborted:()=>Xe,allowsEval:()=>eo,assert:()=>Nf,assertEqual:()=>If,assertIs:()=>$f,assertNever:()=>Rf,assertNotEqual:()=>Of,assignProp:()=>We,base64ToUint8Array:()=>Rs,base64urlToUint8Array:()=>Yf,cached:()=>St,captureStackTrace:()=>zn,cleanEnum:()=>Wf,cleanRegex:()=>Xt,clone:()=>ye,cloneDef:()=>zf,createTransparentProxy:()=>Bf,defineLazy:()=>C,esc:()=>Tn,escapeRegex:()=>Be,explicitlyAborted:()=>oo,extend:()=>Qf,finalizeIssue:()=>fe,floatSafeRemainder:()=>Xr,getElementAtPath:()=>Pf,getEnumValues:()=>Wt,getLengthableOrigin:()=>Ht,getParsedType:()=>Ff,getSizableOrigin:()=>$s,hexToUint8Array:()=>Hf,isObject:()=>dt,isPlainObject:()=>Ye,issue:()=>vt,joinValues:()=>Cf,jsonStringifyReplacer:()=>Et,merge:()=>Vf,mergeDefs:()=>Fe,normalizeParams:()=>I,nullish:()=>Yt,numKeys:()=>Zf,objectClone:()=>Tf,omit:()=>Uf,optionalKeys:()=>no,parsedType:()=>Kf,partial:()=>Gf,pick:()=>jf,prefixIssues:()=>je,primitiveTypes:()=>Ds,promiseAllObject:()=>Lf,propertyKeyTypes:()=>to,randomString:()=>Mf,required:()=>qf,safeExtend:()=>Jf,shallowClone:()=>As,slugify:()=>Hr,stringifyPrimitive:()=>Is,uint8ArrayToBase64:()=>Ns,uint8ArrayToBase64url:()=>Xf,uint8ArrayToHex:()=>ed,unwrapMessage:()=>Kt});function If(e){return e}function Of(e){return e}function $f(e){}function Rf(e){throw new Error("Unexpected value in exhaustive check")}function Nf(e){}function Wt(e){let t=Object.values(e).filter(r=>typeof r=="number");return Object.entries(e).filter(([r,o])=>t.indexOf(+r)===-1).map(([r,o])=>o)}function Cf(e,t="|"){return e.map(n=>Is(n)).join(t)}function Et(e,t){return typeof t=="bigint"?t.toString():t}function St(e){return{get value(){{let n=e();return Object.defineProperty(this,"value",{value:n}),n}throw new Error("cached value already set")}}}function Yt(e){return e==null}function Xt(e){let t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}function Xr(e,t){let n=e/t,r=Math.round(n),o=Number.EPSILON*Math.max(Math.abs(n),1);return Math.abs(n-r)<o?0:n-r}var ks=Symbol("evaluating");function C(e,t,n){let r;Object.defineProperty(e,t,{get(){if(r!==ks)return r===void 0&&(r=ks,r=n()),r},set(o){Object.defineProperty(e,t,{value:o})},configurable:!0})}function Tf(e){return Object.create(Object.getPrototypeOf(e),Object.getOwnPropertyDescriptors(e))}function We(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function Fe(...e){let t={};for(let n of e){let r=Object.getOwnPropertyDescriptors(n);Object.assign(t,r)}return Object.defineProperties({},t)}function zf(e){return Fe(e._zod.def)}function Pf(e,t){return t?t.reduce((n,r)=>n?.[r],e):e}function Lf(e){let t=Object.keys(e),n=t.map(r=>e[r]);return Promise.all(n).then(r=>{let o={};for(let s=0;s<t.length;s++)o[t[s]]=r[s];return o})}function Mf(e=10){let t="abcdefghijklmnopqrstuvwxyz",n="";for(let r=0;r<e;r++)n+=t[Math.floor(Math.random()*t.length)];return n}function Tn(e){return JSON.stringify(e)}function Hr(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var zn="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function dt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var eo=St(()=>{if(xt.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let e=Function;return new e(""),!0}catch{return!1}});function Ye(e){if(dt(e)===!1)return!1;let t=e.constructor;if(t===void 0||typeof t!="function")return!0;let n=t.prototype;return!(dt(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function As(e){return Ye(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}function Zf(e){let t=0;for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&t++;return t}var Ff=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}`)}},to=new Set(["string","number","symbol"]),Ds=new Set(["string","number","bigint","boolean","symbol","undefined"]);function Be(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ye(e,t,n){let r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function I(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 Bf(e){let t;return new Proxy({},{get(n,r,o){return t??(t=e()),Reflect.get(t,r,o)},set(n,r,o,s){return t??(t=e()),Reflect.set(t,r,o,s)},has(n,r){return t??(t=e()),Reflect.has(t,r)},deleteProperty(n,r){return t??(t=e()),Reflect.deleteProperty(t,r)},ownKeys(n){return t??(t=e()),Reflect.ownKeys(t)},getOwnPropertyDescriptor(n,r){return t??(t=e()),Reflect.getOwnPropertyDescriptor(t,r)},defineProperty(n,r,o){return t??(t=e()),Reflect.defineProperty(t,r,o)}})}function Is(e){return typeof e=="bigint"?e.toString()+"n":typeof e=="string"?`"${e}"`:`${e}`}function no(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}var ro={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]},Os={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function jf(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");let s=Fe(e._zod.def,{get shape(){let i={};for(let c in t){if(!(c in n.shape))throw new Error(`Unrecognized key: "${c}"`);t[c]&&(i[c]=n.shape[c])}return We(this,"shape",i),i},checks:[]});return ye(e,s)}function Uf(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");let s=Fe(e._zod.def,{get shape(){let i={...e._zod.def.shape};for(let c in t){if(!(c in n.shape))throw new Error(`Unrecognized key: "${c}"`);t[c]&&delete i[c]}return We(this,"shape",i),i},checks:[]});return ye(e,s)}function Qf(e,t){if(!Ye(t))throw new Error("Invalid input to extend: expected a plain object");let n=e._zod.def.checks;if(n&&n.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=Fe(e._zod.def,{get shape(){let s={...e._zod.def.shape,...t};return We(this,"shape",s),s}});return ye(e,o)}function Jf(e,t){if(!Ye(t))throw new Error("Invalid input to safeExtend: expected a plain object");let n=Fe(e._zod.def,{get shape(){let r={...e._zod.def.shape,...t};return We(this,"shape",r),r}});return ye(e,n)}function Vf(e,t){if(e._zod.def.checks?.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let n=Fe(e._zod.def,{get shape(){let r={...e._zod.def.shape,...t._zod.def.shape};return We(this,"shape",r),r},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return ye(e,n)}function Gf(e,t,n){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=Fe(t._zod.def,{get shape(){let c=t._zod.def.shape,a={...c};if(n)for(let u in n){if(!(u in c))throw new Error(`Unrecognized key: "${u}"`);n[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 We(this,"shape",a),a},checks:[]});return ye(t,i)}function qf(e,t,n){let r=Fe(t._zod.def,{get shape(){let o=t._zod.def.shape,s={...o};if(n)for(let i in n){if(!(i in s))throw new Error(`Unrecognized key: "${i}"`);n[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 We(this,"shape",s),s}});return ye(t,r)}function Xe(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function oo(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue===!1)return!0;return!1}function je(e,t){return t.map(n=>{var r;return(r=n).path??(r.path=[]),n.path.unshift(e),n})}function Kt(e){return typeof e=="string"?e:e?.message}function fe(e,t,n){let r=e.message?e.message:Kt(e.inst?._zod.def?.error?.(e))??Kt(t?.error?.(e))??Kt(n.customError?.(e))??Kt(n.localeError?.(e))??"Invalid input",{inst:o,continue:s,input:i,...c}=e;return c.path??(c.path=[]),c.message=r,t?.reportInput&&(c.input=i),c}function $s(e){return e instanceof Set?"set":e instanceof Map?"map":e instanceof File?"file":"unknown"}function Ht(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function Kf(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 n=e;if(n&&Object.getPrototypeOf(n)!==Object.prototype&&"constructor"in n&&n.constructor)return n.constructor.name}}return t}function vt(...e){let[t,n,r]=e;return typeof t=="string"?{message:t,code:"custom",input:n,inst:r}:{...t}}function Wf(e){return Object.entries(e).filter(([t,n])=>Number.isNaN(Number.parseInt(t,10))).map(t=>t[1])}function Rs(e){let t=atob(e),n=new Uint8Array(t.length);for(let r=0;r<t.length;r++)n[r]=t.charCodeAt(r);return n}function Ns(e){let t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)}function Yf(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),n="=".repeat((4-t.length%4)%4);return Rs(t+n)}function Xf(e){return Ns(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function Hf(e){let t=e.replace(/^0x/,"");if(t.length%2!==0)throw new Error("Invalid hex string length");let n=new Uint8Array(t.length/2);for(let r=0;r<t.length;r+=2)n[r/2]=Number.parseInt(t.slice(r,r+2),16);return n}function ed(e){return Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")}var Yr=class{constructor(...t){}};var Cs=(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,Et,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Pn=g("$ZodError",Cs),so=g("$ZodError",Cs,{Parent:Error});function Ts(e,t=n=>n.message){let n={},r=[];for(let o of e.issues)o.path.length>0?(n[o.path[0]]=n[o.path[0]]||[],n[o.path[0]].push(t(o))):r.push(t(o));return{formErrors:r,fieldErrors:n}}function zs(e,t=n=>n.message){let n={_errors:[]},r=(o,s=[])=>{for(let i of o.issues)if(i.code==="invalid_union"&&i.errors.length)i.errors.map(c=>r({issues:c},[...s,...i.path]));else if(i.code==="invalid_key")r({issues:i.issues},[...s,...i.path]);else if(i.code==="invalid_element")r({issues:i.issues},[...s,...i.path]);else{let c=[...s,...i.path];if(c.length===0)n._errors.push(t(i));else{let a=n,u=0;for(;u<c.length;){let d=c[u];u===c.length-1?(a[d]=a[d]||{_errors:[]},a[d]._errors.push(t(i))):a[d]=a[d]||{_errors:[]},a=a[d],u++}}}};return r(e),n}var Ln=e=>(t,n,r,o)=>{let s=r?{...r,async:!1}:{async:!1},i=t._zod.run({value:n,issues:[]},s);if(i instanceof Promise)throw new De;if(i.issues.length){let c=new(o?.Err??e)(i.issues.map(a=>fe(a,s,he())));throw zn(c,o?.callee),c}return i.value};var Mn=e=>async(t,n,r,o)=>{let s=r?{...r,async:!0}:{async:!0},i=t._zod.run({value:n,issues:[]},s);if(i instanceof Promise&&(i=await i),i.issues.length){let c=new(o?.Err??e)(i.issues.map(a=>fe(a,s,he())));throw zn(c,o?.callee),c}return i.value};var en=e=>(t,n,r)=>{let o=r?{...r,async:!1}:{async:!1},s=t._zod.run({value:n,issues:[]},o);if(s instanceof Promise)throw new De;return s.issues.length?{success:!1,error:new(e??Pn)(s.issues.map(i=>fe(i,o,he())))}:{success:!0,data:s.value}},Ps=en(so),tn=e=>async(t,n,r)=>{let o=r?{...r,async:!0}:{async:!0},s=t._zod.run({value:n,issues:[]},o);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new e(s.issues.map(i=>fe(i,o,he())))}:{success:!0,data:s.value}},Ls=tn(so),Ms=e=>(t,n,r)=>{let o=r?{...r,direction:"backward"}:{direction:"backward"};return Ln(e)(t,n,o)};var Zs=e=>(t,n,r)=>Ln(e)(t,n,r);var Fs=e=>async(t,n,r)=>{let o=r?{...r,direction:"backward"}:{direction:"backward"};return Mn(e)(t,n,o)};var Bs=e=>async(t,n,r)=>Mn(e)(t,n,r);var js=e=>(t,n,r)=>{let o=r?{...r,direction:"backward"}:{direction:"backward"};return en(e)(t,n,o)};var Us=e=>(t,n,r)=>en(e)(t,n,r);var Qs=e=>async(t,n,r)=>{let o=r?{...r,direction:"backward"}:{direction:"backward"};return tn(e)(t,n,o)};var Js=e=>async(t,n,r)=>tn(e)(t,n,r);var Vs=/^[cC][0-9a-z]{6,}$/,Gs=/^[0-9a-z]+$/,qs=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Ks=/^[0-9a-vA-V]{20}$/,Ws=/^[A-Za-z0-9]{27}$/,Ys=/^[a-zA-Z0-9_-]{21}$/,Xs=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var Hs=/^([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})$/,io=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 ei=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var nd="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function ti(){return new RegExp(nd,"u")}var ni=/^(?:(?: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])$/,ri=/^(([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 oi=/^((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])$/,si=/^(([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])$/,ii=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,co=/^[A-Za-z0-9_-]*$/;var ci=/^https?$/,ai=/^\+[1-9]\d{6,14}$/,ui="(?:(?:\\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])))",li=new RegExp(`^${ui}$`);function fi(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 di(e){return new RegExp(`^${fi(e)}$`)}function pi(e){let t=fi({precision:e.precision}),n=["Z"];e.local&&n.push(""),e.offset&&n.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let r=`${t}(?:${n.join("|")})`;return new RegExp(`^${ui}T(?:${r})$`)}var mi=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)};var hi=/^-?\d+$/,ao=/^-?\d+(?:\.\d+)?$/,yi=/^(?:true|false)$/i,gi=/^null$/i;var bi=/^[^A-Z]*$/,wi=/^[^a-z]*$/;var Y=g("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),_i={number:"number",bigint:"bigint",object:"date"},uo=g("$ZodCheckLessThan",(e,t)=>{Y.init(e,t);let n=_i[typeof t.value];e._zod.onattach.push(r=>{let o=r._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=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:n,code:"too_big",maximum:typeof t.value=="object"?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),lo=g("$ZodCheckGreaterThan",(e,t)=>{Y.init(e,t);let n=_i[typeof t.value];e._zod.onattach.push(r=>{let o=r._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=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:n,code:"too_small",minimum:typeof t.value=="object"?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),xi=g("$ZodCheckMultipleOf",(e,t)=>{Y.init(e,t),e._zod.onattach.push(n=>{var r;(r=n._zod.bag).multipleOf??(r.multipleOf=t.value)}),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof n.value=="bigint"?n.value%t.value===BigInt(0):Xr(n.value,t.value)===0)||n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),Ei=g("$ZodCheckNumberFormat",(e,t)=>{Y.init(e,t),t.format=t.format||"float64";let n=t.format?.includes("int"),r=n?"int":"number",[o,s]=ro[t.format];e._zod.onattach.push(i=>{let c=i._zod.bag;c.format=t.format,c.minimum=o,c.maximum=s,n&&(c.pattern=hi)}),e._zod.check=i=>{let c=i.value;if(n){if(!Number.isInteger(c)){i.issues.push({expected:r,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:r,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:r,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 Si=g("$ZodCheckMaxLength",(e,t)=>{var n;Y.init(e,t),(n=e._zod.def).when??(n.when=r=>{let o=r.value;return!Yt(o)&&o.length!==void 0}),e._zod.onattach.push(r=>{let o=r._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<o&&(r._zod.bag.maximum=t.maximum)}),e._zod.check=r=>{let o=r.value;if(o.length<=t.maximum)return;let i=Ht(o);r.issues.push({origin:i,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),vi=g("$ZodCheckMinLength",(e,t)=>{var n;Y.init(e,t),(n=e._zod.def).when??(n.when=r=>{let o=r.value;return!Yt(o)&&o.length!==void 0}),e._zod.onattach.push(r=>{let o=r._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>o&&(r._zod.bag.minimum=t.minimum)}),e._zod.check=r=>{let o=r.value;if(o.length>=t.minimum)return;let i=Ht(o);r.issues.push({origin:i,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),ki=g("$ZodCheckLengthEquals",(e,t)=>{var n;Y.init(e,t),(n=e._zod.def).when??(n.when=r=>{let o=r.value;return!Yt(o)&&o.length!==void 0}),e._zod.onattach.push(r=>{let o=r._zod.bag;o.minimum=t.length,o.maximum=t.length,o.length=t.length}),e._zod.check=r=>{let o=r.value,s=o.length;if(s===t.length)return;let i=Ht(o),c=s>t.length;r.issues.push({origin:i,...c?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:r.value,inst:e,continue:!t.abort})}}),nn=g("$ZodCheckStringFormat",(e,t)=>{var n,r;Y.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?(n=e._zod).check??(n.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})}):(r=e._zod).check??(r.check=()=>{})}),Ai=g("$ZodCheckRegex",(e,t)=>{nn.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),Di=g("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=bi),nn.init(e,t)}),Ii=g("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=wi),nn.init(e,t)}),Oi=g("$ZodCheckIncludes",(e,t)=>{Y.init(e,t);let n=Be(t.includes),r=new RegExp(typeof t.position=="number"?`^.{${t.position}}${n}`:n);t.pattern=r,e._zod.onattach.push(o=>{let s=o._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(r)}),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})}}),$i=g("$ZodCheckStartsWith",(e,t)=>{Y.init(e,t);let n=new RegExp(`^${Be(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.onattach.push(r=>{let o=r._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(n)}),e._zod.check=r=>{r.value.startsWith(t.prefix)||r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:r.value,inst:e,continue:!t.abort})}}),Ri=g("$ZodCheckEndsWith",(e,t)=>{Y.init(e,t);let n=new RegExp(`.*${Be(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.onattach.push(r=>{let o=r._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(n)}),e._zod.check=r=>{r.value.endsWith(t.suffix)||r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:r.value,inst:e,continue:!t.abort})}});var Ni=g("$ZodCheckOverwrite",(e,t)=>{Y.init(e,t),e._zod.check=n=>{n.value=t.tx(n.value)}});var Fn=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 r=t.split(`
+`).filter(i=>i),o=Math.min(...r.map(i=>i.length-i.trimStart().length)),s=r.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,n=this?.args,o=[...(this?.content??[""]).map(s=>` ${s}`)];return new t(...n,o.join(`
+`))}};var Ti={major:4,minor:4,patch:3};var Z=g("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Ti;let r=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&r.unshift(e);for(let o of r)for(let s of o._zod.onattach)s(e);if(r.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let o=(i,c,a)=>{let u=Xe(i),d;for(let l of c){if(l._zod.def.when){if(oo(i)||!l._zod.def.when(i))continue}else if(u)continue;let f=i.issues.length,p=l._zod.check(i);if(p instanceof Promise&&a?.async===!1)throw new De;if(d||p instanceof Promise)d=(d??Promise.resolve()).then(async()=>{await p,i.issues.length!==f&&(u||(u=Xe(i,f)))});else{if(i.issues.length===f)continue;u||(u=Xe(i,f))}}return d?d.then(()=>i):i},s=(i,c,a)=>{if(Xe(i))return i.aborted=!0,i;let u=o(c,r,a);if(u instanceof Promise){if(a.async===!1)throw new De;return u.then(d=>e._zod.parse(d,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(d=>s(d,i,c)):s(u,i,c)}let a=e._zod.parse(i,c);if(a instanceof Promise){if(c.async===!1)throw new De;return a.then(u=>o(u,r,c))}return o(a,r,c)}}C(e,"~standard",()=>({validate:o=>{try{let s=Ps(e,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return Ls(e,o).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}))}),Un=g("$ZodString",(e,t)=>{Z.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??mi(e._zod.bag),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch{}return typeof n.value=="string"||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:e}),n}}),F=g("$ZodStringFormat",(e,t)=>{nn.init(e,t),Un.init(e,t)}),Ui=g("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=Hs),F.init(e,t)}),Qi=g("$ZodUUID",(e,t)=>{if(t.version){let r={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(r===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=io(r))}else t.pattern??(t.pattern=io());F.init(e,t)}),Ji=g("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=ei),F.init(e,t)}),Vi=g("$ZodURL",(e,t)=>{F.init(e,t),e._zod.check=n=>{try{let r=n.value.trim();if(!t.normalize&&t.protocol?.source===ci.source&&!/^https?:\/\//i.test(r)){n.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:n.value,inst:e,continue:!t.abort});return}let o=new URL(r);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(o.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:n.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)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})),t.normalize?n.value=o.href:n.value=r;return}catch{n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),Gi=g("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=ti()),F.init(e,t)}),qi=g("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=Ys),F.init(e,t)}),Ki=g("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=Vs),F.init(e,t)}),Wi=g("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=Gs),F.init(e,t)}),Yi=g("$ZodULID",(e,t)=>{t.pattern??(t.pattern=qs),F.init(e,t)}),Xi=g("$ZodXID",(e,t)=>{t.pattern??(t.pattern=Ks),F.init(e,t)}),Hi=g("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=Ws),F.init(e,t)}),ec=g("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=pi(t)),F.init(e,t)}),tc=g("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=li),F.init(e,t)}),nc=g("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=di(t)),F.init(e,t)}),rc=g("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=Xs),F.init(e,t)}),oc=g("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=ni),F.init(e,t),e._zod.bag.format="ipv4"}),sc=g("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=ri),F.init(e,t),e._zod.bag.format="ipv6",e._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:e,continue:!t.abort})}}});var ic=g("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=oi),F.init(e,t)}),cc=g("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=si),F.init(e,t),e._zod.check=n=>{let r=n.value.split("/");try{if(r.length!==2)throw new Error;let[o,s]=r;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{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}}});function ac(e){if(e==="")return!0;if(/\s/.test(e)||e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}var uc=g("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=ii),F.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=n=>{ac(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}});function rd(e){if(!co.test(e))return!1;let t=e.replace(/[-_]/g,r=>r==="-"?"+":"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return ac(n)}var lc=g("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=co),F.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=n=>{rd(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),fc=g("$ZodE164",(e,t)=>{t.pattern??(t.pattern=ai),F.init(e,t)});function od(e,t=null){try{let n=e.split(".");if(n.length!==3)return!1;let[r]=n;if(!r)return!1;let o=JSON.parse(atob(r));return!("typ"in o&&o?.typ!=="JWT"||!o.alg||t&&(!("alg"in o)||o.alg!==t))}catch{return!1}}var dc=g("$ZodJWT",(e,t)=>{F.init(e,t),e._zod.check=n=>{od(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}});var po=g("$ZodNumber",(e,t)=>{Z.init(e,t),e._zod.pattern=e._zod.bag.pattern??ao,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}let o=n.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return n;let s=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:o,inst:e,...s?{received:s}:{}}),n}}),pc=g("$ZodNumberFormat",(e,t)=>{Ei.init(e,t),po.init(e,t)}),mc=g("$ZodBoolean",(e,t)=>{Z.init(e,t),e._zod.pattern=yi,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=!!n.value}catch{}let o=n.value;return typeof o=="boolean"||n.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:e}),n}});var hc=g("$ZodNull",(e,t)=>{Z.init(e,t),e._zod.pattern=gi,e._zod.values=new Set([null]),e._zod.parse=(n,r)=>{let o=n.value;return o===null||n.issues.push({expected:"null",code:"invalid_type",input:o,inst:e}),n}});var yc=g("$ZodUnknown",(e,t)=>{Z.init(e,t),e._zod.parse=n=>n}),gc=g("$ZodNever",(e,t)=>{Z.init(e,t),e._zod.parse=(n,r)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:e}),n)});function zi(e,t,n){e.issues.length&&t.issues.push(...je(n,e.issues)),t.value[n]=e.value}var bc=g("$ZodArray",(e,t)=>{Z.init(e,t),e._zod.parse=(n,r)=>{let o=n.value;if(!Array.isArray(o))return n.issues.push({expected:"array",code:"invalid_type",input:o,inst:e}),n;n.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:[]},r);a instanceof Promise?s.push(a.then(u=>zi(u,n,i))):zi(a,n,i)}return s.length?Promise.all(s).then(()=>n):n}});function jn(e,t,n,r,o,s){let i=n in r;if(e.issues.length){if(o&&s&&!i)return;t.issues.push(...je(n,e.issues))}if(!i&&!o){e.issues.length||t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[n]});return}e.value===void 0?i&&(t.value[n]=void 0):t.value[n]=e.value}function wc(e){let t=Object.keys(e.shape);for(let r of t)if(!e.shape?.[r]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${r}": expected a Zod schema`);let n=no(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function _c(e,t,n,r,o,s){let i=[],c=o.keySet,a=o.catchall._zod,u=a.def.type,d=a.optin==="optional",l=a.optout==="optional";for(let f in t){if(f==="__proto__"||c.has(f))continue;if(u==="never"){i.push(f);continue}let p=a.run({value:t[f],issues:[]},r);p instanceof Promise?e.push(p.then(y=>jn(y,n,f,t,d,l))):jn(p,n,f,t,d,l)}return i.length&&n.issues.push({code:"unrecognized_keys",keys:i,input:t,inst:s}),e.length?Promise.all(e).then(()=>n):n}var sd=g("$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 r=St(()=>wc(t));C(e._zod,"propValues",()=>{let c=t.shape,a={};for(let u in c){let d=c[u]._zod;if(d.values){a[u]??(a[u]=new Set);for(let l of d.values)a[u].add(l)}}return a});let o=dt,s=t.catchall,i;e._zod.parse=(c,a)=>{i??(i=r.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 d=[],l=i.shape;for(let f of i.keys){let p=l[f],y=p._zod.optin==="optional",m=p._zod.optout==="optional",h=p._zod.run({value:u[f],issues:[]},a);h instanceof Promise?d.push(h.then(b=>jn(b,c,f,u,y,m))):jn(h,c,f,u,y,m)}return s?_c(d,u,c,a,r.value,e):d.length?Promise.all(d).then(()=>c):c}}),xc=g("$ZodObjectJIT",(e,t)=>{sd.init(e,t);let n=e._zod.parse,r=St(()=>wc(t)),o=f=>{let p=new Fn(["shape","payload","ctx"]),y=r.value,m=x=>{let w=Tn(x);return`shape[${w}]._zod.run({ value: input[${w}], issues: [] }, ctx)`};p.write("const input = payload.value;");let h=Object.create(null),b=0;for(let x of y.keys)h[x]=`key_${b++}`;p.write("const newResult = {};");for(let x of y.keys){let w=h[x],S=Tn(x),v=f[x],R=v?._zod?.optin==="optional",E=v?._zod?.optout==="optional";p.write(`const ${w} = ${m(x)};`),R&&E?p.write(`
+ if (${w}.issues.length) {
+ if (${S} in input) {
+ payload.issues = payload.issues.concat(${w}.issues.map(iss => ({
...iss,
- path: iss.path ? [${C}, ...iss.path] : [${C}]
+ path: iss.path ? [${S}, ...iss.path] : [${S}]
})));
}
}
- if (${$}.value === undefined) {
- if (${C} in input) {
- newResult[${C}] = undefined;
+ if (${w}.value === undefined) {
+ if (${S} in input) {
+ newResult[${S}] = undefined;
}
} else {
- newResult[${C}] = ${$}.value;
+ newResult[${S}] = ${w}.value;
}
- `):or?d.write(`
- if (${$}.issues.length) {
- payload.issues = payload.issues.concat(${$}.issues.map(iss => ({
+ `):R?p.write(`
+ if (${w}.issues.length) {
+ payload.issues = payload.issues.concat(${w}.issues.map(iss => ({
...iss,
- path: iss.path ? [${C}, ...iss.path] : [${C}]
+ path: iss.path ? [${S}, ...iss.path] : [${S}]
})));
}
- if (${$}.value === undefined) {
- if (${C} in input) {
- newResult[${C}] = undefined;
+ if (${w}.value === undefined) {
+ if (${S} in input) {
+ newResult[${S}] = undefined;
}
} else {
- newResult[${C}] = ${$}.value;
+ newResult[${S}] = ${w}.value;
}
- `):d.write(`
- const ${$}_present = ${C} in input;
- if (${$}.issues.length) {
- payload.issues = payload.issues.concat(${$}.issues.map(iss => ({
+ `):p.write(`
+ const ${w}_present = ${S} in input;
+ if (${w}.issues.length) {
+ payload.issues = payload.issues.concat(${w}.issues.map(iss => ({
...iss,
- path: iss.path ? [${C}, ...iss.path] : [${C}]
+ path: iss.path ? [${S}, ...iss.path] : [${S}]
})));
}
- if (!${$}_present && !${$}.issues.length) {
+ if (!${w}_present && !${w}.issues.length) {
payload.issues.push({
code: "invalid_type",
expected: "nonoptional",
input: undefined,
- path: [${C}]
+ path: [${S}]
});
}
- if (${$}_present) {
- if (${$}.value === undefined) {
- newResult[${C}] = undefined;
+ if (${w}_present) {
+ if (${w}.value === undefined) {
+ newResult[${S}] = undefined;
} else {
- newResult[${C}] = ${$}.value;
+ newResult[${S}] = ${w}.value;
}
}
- `)}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>
+ `)}p.write("payload.value = newResult;"),p.write("return payload;");let _=p.compile();return(x,w)=>_(f,x,w)},s,i=dt,c=!xt.jitless,u=c&&eo.value,d=t.catchall,l;e._zod.parse=(f,p)=>{l??(l=r.value);let y=f.value;return i(y)?c&&u&&p?.async===!1&&p.jitless!==!0?(s||(s=o(t.shape)),f=s(f,p),d?_c([],y,f,p,l,e):f):n(f,p):(f.issues.push({expected:"object",code:"invalid_type",input:y,inst:e}),f)}});function Pi(e,t,n,r){for(let s of e)if(s.issues.length===0)return t.value=s.value,t;let o=e.filter(s=>!Xe(s));return o.length===1?(t.value=o[0].value,o[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map(s=>s.issues.map(i=>fe(i,r,he())))}),t)}var mo=g("$ZodUnion",(e,t)=>{Z.init(e,t),C(e._zod,"optin",()=>t.options.some(r=>r._zod.optin==="optional")?"optional":void 0),C(e._zod,"optout",()=>t.options.some(r=>r._zod.optout==="optional")?"optional":void 0),C(e._zod,"values",()=>{if(t.options.every(r=>r._zod.values))return new Set(t.options.flatMap(r=>Array.from(r._zod.values)))}),C(e._zod,"pattern",()=>{if(t.options.every(r=>r._zod.pattern)){let r=t.options.map(o=>o._zod.pattern);return new RegExp(`^(${r.map(o=>Xt(o.source)).join("|")})$`)}});let n=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(r,o)=>{if(n)return n(r,o);let s=!1,i=[];for(let c of t.options){let a=c._zod.run({value:r.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=>Pi(c,r,e,o)):Pi(i,r,e,o)}});var Ec=g("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,mo.init(e,t);let n=e._zod.parse;C(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 r=St(()=>{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(!dt(i))return o.issues.push({code:"invalid_type",expected:"object",input:i,inst:e}),o;let c=r.value.get(i?.[t.discriminator]);return c?c._zod.run(o,s):t.unionFallback||s.direction==="backward"?n(o,s):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:t.discriminator,options:Array.from(r.value.keys()),input:i,path:[t.discriminator],inst:e}),o)}}),Sc=g("$ZodIntersection",(e,t)=>{Z.init(e,t),e._zod.parse=(n,r)=>{let o=n.value,s=t.left._zod.run({value:o,issues:[]},r),i=t.right._zod.run({value:o,issues:[]},r);return s instanceof Promise||i instanceof Promise?Promise.all([s,i]).then(([a,u])=>Li(n,a,u)):Li(n,s,i)}});function fo(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(Ye(e)&&Ye(t)){let n=Object.keys(t),r=Object.keys(e).filter(s=>n.indexOf(s)!==-1),o={...e,...t};for(let s of r){let i=fo(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 n=[];for(let r=0;r<e.length;r++){let o=e[r],s=t[r],i=fo(o,s);if(!i.valid)return{valid:!1,mergeErrorPath:[r,...i.mergeErrorPath]};n.push(i.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function Li(e,t,n){let r=new Map,o;for(let c of t.issues)if(c.code==="unrecognized_keys"){o??(o=c);for(let a of c.keys)r.has(a)||r.set(a,{}),r.get(a).l=!0}else e.issues.push(c);for(let c of n.issues)if(c.code==="unrecognized_keys")for(let a of c.keys)r.has(a)||r.set(a,{}),r.get(a).r=!0;else e.issues.push(c);let s=[...r].filter(([,c])=>c.l&&c.r).map(([c])=>c);if(s.length&&o&&e.issues.push({...o,keys:s}),Xe(e))return e;let i=fo(t.value,n.value);if(!i.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(i.mergeErrorPath)}`);return e.value=i.data,e}var vc=g("$ZodRecord",(e,t)=>{Z.init(e,t),e._zod.parse=(n,r)=>{let o=n.value;if(!Ye(o))return n.issues.push({expected:"record",code:"invalid_type",input:o,inst:e}),n;let s=[],i=t.keyType._zod.values;if(i){n.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 d=t.keyType._zod.run({value:u,issues:[]},r);if(d instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(d.issues.length){n.issues.push({code:"invalid_key",origin:"record",issues:d.issues.map(p=>fe(p,r,he())),input:u,path:[u],inst:e});continue}let l=d.value,f=t.valueType._zod.run({value:o[u],issues:[]},r);f instanceof Promise?s.push(f.then(p=>{p.issues.length&&n.issues.push(...je(u,p.issues)),n.value[l]=p.value})):(f.issues.length&&n.issues.push(...je(u,f.issues)),n.value[l]=f.value)}let a;for(let u in o)c.has(u)||(a=a??[],a.push(u));a&&a.length>0&&n.issues.push({code:"unrecognized_keys",input:o,inst:e,keys:a})}else{n.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:[]},r);if(a instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(typeof c=="string"&&ao.test(c)&&a.issues.length){let l=t.keyType._zod.run({value:Number(c),issues:[]},r);if(l instanceof Promise)throw new Error("Async schemas not supported in object keys currently");l.issues.length===0&&(a=l)}if(a.issues.length){t.mode==="loose"?n.value[c]=o[c]:n.issues.push({code:"invalid_key",origin:"record",issues:a.issues.map(l=>fe(l,r,he())),input:c,path:[c],inst:e});continue}let d=t.valueType._zod.run({value:o[c],issues:[]},r);d instanceof Promise?s.push(d.then(l=>{l.issues.length&&n.issues.push(...je(c,l.issues)),n.value[a.value]=l.value})):(d.issues.length&&n.issues.push(...je(c,d.issues)),n.value[a.value]=d.value)}}return s.length?Promise.all(s).then(()=>n):n}});var kc=g("$ZodEnum",(e,t)=>{Z.init(e,t);let n=Wt(t.entries),r=new Set(n);e._zod.values=r,e._zod.pattern=new RegExp(`^(${n.filter(o=>to.has(typeof o)).map(o=>typeof o=="string"?Be(o):o.toString()).join("|")})$`),e._zod.parse=(o,s)=>{let i=o.value;return r.has(i)||o.issues.push({code:"invalid_value",values:n,input:i,inst:e}),o}}),Ac=g("$ZodLiteral",(e,t)=>{if(Z.init(e,t),t.values.length===0)throw new Error("Cannot create literal schema with no valid values");let n=new Set(t.values);e._zod.values=n,e._zod.pattern=new RegExp(`^(${t.values.map(r=>typeof r=="string"?Be(r):r?Be(r.toString()):String(r)).join("|")})$`),e._zod.parse=(r,o)=>{let s=r.value;return n.has(s)||r.issues.push({code:"invalid_value",values:t.values,input:s,inst:e}),r}});var Dc=g("$ZodTransform",(e,t)=>{Z.init(e,t),e._zod.optin="optional",e._zod.parse=(n,r)=>{if(r.direction==="backward")throw new _t(e.constructor.name);let o=t.transform(n.value,n);if(r.async)return(o instanceof Promise?o:Promise.resolve(o)).then(i=>(n.value=i,n.fallback=!0,n));if(o instanceof Promise)throw new De;return n.value=o,n.fallback=!0,n}});function Mi(e,t){return t===void 0&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}var ho=g("$ZodOptional",(e,t)=>{Z.init(e,t),e._zod.optin="optional",e._zod.optout="optional",C(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),C(e._zod,"pattern",()=>{let n=t.innerType._zod.pattern;return n?new RegExp(`^(${Xt(n.source)})?$`):void 0}),e._zod.parse=(n,r)=>{if(t.innerType._zod.optin==="optional"){let o=n.value,s=t.innerType._zod.run(n,r);return s instanceof Promise?s.then(i=>Mi(i,o)):Mi(s,o)}return n.value===void 0?n:t.innerType._zod.run(n,r)}}),Ic=g("$ZodExactOptional",(e,t)=>{ho.init(e,t),C(e._zod,"values",()=>t.innerType._zod.values),C(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(n,r)=>t.innerType._zod.run(n,r)}),Oc=g("$ZodNullable",(e,t)=>{Z.init(e,t),C(e._zod,"optin",()=>t.innerType._zod.optin),C(e._zod,"optout",()=>t.innerType._zod.optout),C(e._zod,"pattern",()=>{let n=t.innerType._zod.pattern;return n?new RegExp(`^(${Xt(n.source)}|null)$`):void 0}),C(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(n,r)=>n.value===null?n:t.innerType._zod.run(n,r)}),$c=g("$ZodDefault",(e,t)=>{Z.init(e,t),e._zod.optin="optional",C(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);if(n.value===void 0)return n.value=t.defaultValue,n;let o=t.innerType._zod.run(n,r);return o instanceof Promise?o.then(s=>Zi(s,t)):Zi(o,t)}});function Zi(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}var Rc=g("$ZodPrefault",(e,t)=>{Z.init(e,t),e._zod.optin="optional",C(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>(r.direction==="backward"||n.value===void 0&&(n.value=t.defaultValue),t.innerType._zod.run(n,r))}),Nc=g("$ZodNonOptional",(e,t)=>{Z.init(e,t),C(e._zod,"values",()=>{let n=t.innerType._zod.values;return n?new Set([...n].filter(r=>r!==void 0)):void 0}),e._zod.parse=(n,r)=>{let o=t.innerType._zod.run(n,r);return o instanceof Promise?o.then(s=>Fi(s,e)):Fi(o,e)}});function Fi(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 Cc=g("$ZodCatch",(e,t)=>{Z.init(e,t),e._zod.optin="optional",C(e._zod,"optout",()=>t.innerType._zod.optout),C(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);let o=t.innerType._zod.run(n,r);return o instanceof Promise?o.then(s=>(n.value=s.value,s.issues.length&&(n.value=t.catchValue({...n,error:{issues:s.issues.map(i=>fe(i,r,he()))},input:n.value}),n.issues=[],n.fallback=!0),n)):(n.value=o.value,o.issues.length&&(n.value=t.catchValue({...n,error:{issues:o.issues.map(s=>fe(s,r,he()))},input:n.value}),n.issues=[],n.fallback=!0),n)}});var Tc=g("$ZodPipe",(e,t)=>{Z.init(e,t),C(e._zod,"values",()=>t.in._zod.values),C(e._zod,"optin",()=>t.in._zod.optin),C(e._zod,"optout",()=>t.out._zod.optout),C(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(n,r)=>{if(r.direction==="backward"){let s=t.out._zod.run(n,r);return s instanceof Promise?s.then(i=>Bn(i,t.in,r)):Bn(s,t.in,r)}let o=t.in._zod.run(n,r);return o instanceof Promise?o.then(s=>Bn(s,t.out,r)):Bn(o,t.out,r)}});function Bn(e,t,n){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues,fallback:e.fallback},n)}var zc=g("$ZodReadonly",(e,t)=>{Z.init(e,t),C(e._zod,"propValues",()=>t.innerType._zod.propValues),C(e._zod,"values",()=>t.innerType._zod.values),C(e._zod,"optin",()=>t.innerType?._zod?.optin),C(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);let o=t.innerType._zod.run(n,r);return o instanceof Promise?o.then(Bi):Bi(o)}});function Bi(e){return e.value=Object.freeze(e.value),e}var Pc=g("$ZodLazy",(e,t)=>{Z.init(e,t),C(e._zod,"innerType",()=>{let n=t;return n._cachedInner||(n._cachedInner=t.getter()),n._cachedInner}),C(e._zod,"pattern",()=>e._zod.innerType?._zod?.pattern),C(e._zod,"propValues",()=>e._zod.innerType?._zod?.propValues),C(e._zod,"optin",()=>e._zod.innerType?._zod?.optin??void 0),C(e._zod,"optout",()=>e._zod.innerType?._zod?.optout??void 0),e._zod.parse=(n,r)=>e._zod.innerType._zod.run(n,r)}),Lc=g("$ZodCustom",(e,t)=>{Y.init(e,t),Z.init(e,t),e._zod.parse=(n,r)=>n,e._zod.check=n=>{let r=n.value,o=t.fn(r);if(o instanceof Promise)return o.then(s=>ji(s,n,r,e));ji(o,n,r,e)}});function ji(e,t,n,r){if(!e){let o={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(o.params=r._zod.def.params),t.issues.push(vt(o))}}var Mc,Ch=Symbol("ZodOutput"),Th=Symbol("ZodInput"),yo=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(t,...n){let r=n[0];return this._map.set(t,r),r&&typeof r=="object"&&"id"in r&&this._idmap.set(r.id,t),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(t){let n=this._map.get(t);return n&&typeof n=="object"&&"id"in n&&this._idmap.delete(n.id),this._map.delete(t),this}get(t){let n=t._zod.parent;if(n){let r={...this.get(n)??{}};delete r.id;let o={...r,...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 id(){return new yo}(Mc=globalThis).__zod_globalRegistry??(Mc.__zod_globalRegistry=id());var pt=globalThis.__zod_globalRegistry;function Zc(e,t){return new e({type:"string",...I(t)})}function Fc(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...I(t)})}function go(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...I(t)})}function Bc(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...I(t)})}function jc(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...I(t)})}function Uc(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...I(t)})}function Qc(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...I(t)})}function Jc(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...I(t)})}function Vc(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...I(t)})}function Gc(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...I(t)})}function qc(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...I(t)})}function Kc(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...I(t)})}function Wc(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...I(t)})}function Yc(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...I(t)})}function Xc(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...I(t)})}function Hc(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...I(t)})}function ea(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...I(t)})}function ta(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...I(t)})}function na(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...I(t)})}function ra(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...I(t)})}function oa(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...I(t)})}function sa(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...I(t)})}function ia(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...I(t)})}function ca(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...I(t)})}function aa(e,t){return new e({type:"string",format:"date",check:"string_format",...I(t)})}function ua(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...I(t)})}function la(e,t){return new e({type:"string",format:"duration",check:"string_format",...I(t)})}function fa(e,t){return new e({type:"number",checks:[],...I(t)})}function da(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...I(t)})}function pa(e,t){return new e({type:"boolean",...I(t)})}function ma(e,t){return new e({type:"null",...I(t)})}function ha(e){return new e({type:"unknown"})}function ya(e,t){return new e({type:"never",...I(t)})}function Qn(e,t){return new uo({check:"less_than",...I(t),value:e,inclusive:!1})}function rn(e,t){return new uo({check:"less_than",...I(t),value:e,inclusive:!0})}function Jn(e,t){return new lo({check:"greater_than",...I(t),value:e,inclusive:!1})}function on(e,t){return new lo({check:"greater_than",...I(t),value:e,inclusive:!0})}function Vn(e,t){return new xi({check:"multiple_of",...I(t),value:e})}function Gn(e,t){return new Si({check:"max_length",...I(t),maximum:e})}function kt(e,t){return new vi({check:"min_length",...I(t),minimum:e})}function qn(e,t){return new ki({check:"length_equals",...I(t),length:e})}function bo(e,t){return new Ai({check:"string_format",format:"regex",...I(t),pattern:e})}function wo(e){return new Di({check:"string_format",format:"lowercase",...I(e)})}function _o(e){return new Ii({check:"string_format",format:"uppercase",...I(e)})}function xo(e,t){return new Oi({check:"string_format",format:"includes",...I(t),includes:e})}function Eo(e,t){return new $i({check:"string_format",format:"starts_with",...I(t),prefix:e})}function So(e,t){return new Ri({check:"string_format",format:"ends_with",...I(t),suffix:e})}function He(e){return new Ni({check:"overwrite",tx:e})}function vo(e){return He(t=>t.normalize(e))}function ko(){return He(e=>e.trim())}function Ao(){return He(e=>e.toLowerCase())}function Do(){return He(e=>e.toUpperCase())}function Io(){return He(e=>Hr(e))}function ga(e,t,n){return new e({type:"array",element:t,...I(n)})}function ba(e,t,n){return new e({type:"custom",check:"custom",fn:t,...I(n)})}function wa(e,t){let n=cd(r=>(r.addIssue=o=>{if(typeof o=="string")r.issues.push(vt(o,r.value,n._zod.def));else{let s=o;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=r.value),s.inst??(s.inst=n),s.continue??(s.continue=!n._zod.def.abort),r.issues.push(vt(s))}},e(r.value,r)),t);return n}function cd(e,t){let n=new Y({check:"custom",...I(t)});return n._zod.check=e,n}function Oo(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??pt,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 Q(e,t,n={path:[],schemaPath:[]}){var r;let o=e._zod.def,s=t.seen.get(e);if(s)return s.count++,n.schemaPath.includes(e)&&(s.cycle=n.path),s.schema;let i={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,i);let c=e._zod.toJSONSchema?.();if(c)i.schema=c;else{let d={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,i.schema,d);else{let f=i.schema,p=t.processors[o.type];if(!p)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${o.type}`);p(e,t,f,d)}let l=e._zod.parent;l&&(i.ref||(i.ref=l),Q(l,t,d),t.seen.get(l).isParent=!0)}let a=t.metadataRegistry.get(e);return a&&Object.assign(i.schema,a),t.io==="input"&&ee(e)&&(delete i.schema.examples,delete i.schema.default),t.io==="input"&&"_prefault"in i.schema&&((r=i.schema).default??(r.default=i.schema._prefault)),delete i.schema._prefault,t.seen.get(e).schema}function $o(e,t){let n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");let r=new Map;for(let i of e.seen.entries()){let c=e.metadataRegistry.get(i[0])?.id;if(c){let a=r.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.`);r.set(c,i[0])}}let o=i=>{let c=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){let l=e.external.registry.get(i[0])?.id,f=e.external.uri??(y=>y);if(l)return{ref:f(l)};let p=i[1].defId??i[1].schema.id??`schema${e.counter++}`;return i[1].defId=p,{defId:p,ref:`${f("__shared")}#/${c}/${p}`}}if(i[1]===n)return{ref:"#"};let u=`#/${c}/`,d=i[1].schema.id??`__schema${e.counter++}`;return{defId:d,ref:u+d}},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 d=c.schema;for(let l in d)delete d[l];d.$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 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};
+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 Ro(e,t){let n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");let r=c=>{let a=e.seen.get(c);if(a.ref===null)return;let u=a.def??a.schema,d={...u},l=a.ref;if(a.ref=null,l){r(l);let p=e.seen.get(l),y=p.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,d),c._zod.parent===l)for(let h in u)h==="$ref"||h==="allOf"||h in d||delete u[h];if(y.$ref&&p.def)for(let h in u)h==="$ref"||h==="allOf"||h in p.def&&JSON.stringify(u[h])===JSON.stringify(p.def[h])&&delete u[h]}let f=c._zod.parent;if(f&&f!==l){r(f);let p=e.seen.get(f);if(p?.schema.$ref&&(u.$ref=p.schema.$ref,p.def))for(let y in u)y==="$ref"||y==="allOf"||y in p.def&&JSON.stringify(u[y])===JSON.stringify(p.def[y])&&delete u[y]}e.override({zodSchema:c,jsonSchema:u,path:a.path??[]})};for(let c of[...e.seen.entries()].reverse())r(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,n.def??n.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:sn(t,"input",e.processors),output:sn(t,"output",e.processors)}},enumerable:!1,writable:!1}),c}catch{throw new Error("Error converting schema to JSON.")}}function ee(e,t){let n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);let r=e._zod.def;if(r.type==="transform")return!0;if(r.type==="array")return ee(r.element,n);if(r.type==="set")return ee(r.valueType,n);if(r.type==="lazy")return ee(r.getter(),n);if(r.type==="promise"||r.type==="optional"||r.type==="nonoptional"||r.type==="nullable"||r.type==="readonly"||r.type==="default"||r.type==="prefault")return ee(r.innerType,n);if(r.type==="intersection")return ee(r.left,n)||ee(r.right,n);if(r.type==="record"||r.type==="map")return ee(r.keyType,n)||ee(r.valueType,n);if(r.type==="pipe")return e._zod.traits.has("$ZodCodec")?!0:ee(r.in,n)||ee(r.out,n);if(r.type==="object"){for(let o in r.shape)if(ee(r.shape[o],n))return!0;return!1}if(r.type==="union"){for(let o of r.options)if(ee(o,n))return!0;return!1}if(r.type==="tuple"){for(let o of r.items)if(ee(o,n))return!0;return!!(r.rest&&ee(r.rest,n))}return!1}var _a=(e,t={})=>n=>{let r=Oo({...n,processors:t});return Q(e,r),$o(r,e),Ro(r,e)},sn=(e,t,n={})=>r=>{let{libraryOptions:o,target:s}=r??{},i=Oo({...o??{},target:s,io:t,processors:n});return Q(e,i),$o(i,e),Ro(i,e)};var ad={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},xa=(e,t,n,r)=>{let o=n;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=ad[c]??c,o.format===""&&delete o.format,c==="time"&&delete o.format),u&&(o.contentEncoding=u),a&&a.size>0){let d=[...a];d.length===1?o.pattern=d[0].source:d.length>1&&(o.allOf=[...d.map(l=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:l.source}))])}},Ea=(e,t,n,r)=>{let o=n,{minimum:s,maximum:i,format:c,multipleOf:a,exclusiveMaximum:u,exclusiveMinimum:d}=e._zod.bag;typeof c=="string"&&c.includes("int")?o.type="integer":o.type="number";let l=typeof d=="number"&&d>=(s??Number.NEGATIVE_INFINITY),f=typeof u=="number"&&u<=(i??Number.POSITIVE_INFINITY),p=t.target==="draft-04"||t.target==="openapi-3.0";l?p?(o.minimum=d,o.exclusiveMinimum=!0):o.exclusiveMinimum=d:typeof s=="number"&&(o.minimum=s),f?p?(o.maximum=u,o.exclusiveMaximum=!0):o.exclusiveMaximum=u:typeof i=="number"&&(o.maximum=i),typeof a=="number"&&(o.multipleOf=a)},Sa=(e,t,n,r)=>{n.type="boolean"};var va=(e,t,n,r)=>{t.target==="openapi-3.0"?(n.type="string",n.nullable=!0,n.enum=[null]):n.type="null"};var ka=(e,t,n,r)=>{n.not={}};var Aa=(e,t,n,r)=>{};var Da=(e,t,n,r)=>{let o=e._zod.def,s=Wt(o.entries);s.every(i=>typeof i=="number")&&(n.type="number"),s.every(i=>typeof i=="string")&&(n.type="string"),n.enum=s},Ia=(e,t,n,r)=>{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];n.type=i===null?"null":typeof i,t.target==="draft-04"||t.target==="openapi-3.0"?n.enum=[i]:n.const=i}else s.every(i=>typeof i=="number")&&(n.type="number"),s.every(i=>typeof i=="string")&&(n.type="string"),s.every(i=>typeof i=="boolean")&&(n.type="boolean"),s.every(i=>i===null)&&(n.type="null"),n.enum=s};var Oa=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")};var $a=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")};var Ra=(e,t,n,r)=>{let o=n,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=Q(s.element,t,{...r,path:[...r.path,"items"]})},Na=(e,t,n,r)=>{let o=n,s=e._zod.def;o.type="object",o.properties={};let i=s.shape;for(let u in i)o.properties[u]=Q(i[u],t,{...r,path:[...r.path,"properties",u]});let c=new Set(Object.keys(i)),a=new Set([...c].filter(u=>{let d=s.shape[u]._zod;return t.io==="input"?d.optin===void 0:d.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=Q(s.catchall,t,{...r,path:[...r.path,"additionalProperties"]})):t.io==="output"&&(o.additionalProperties=!1)},Ca=(e,t,n,r)=>{let o=e._zod.def,s=o.inclusive===!1,i=o.options.map((c,a)=>Q(c,t,{...r,path:[...r.path,s?"oneOf":"anyOf",a]}));s?n.oneOf=i:n.anyOf=i},Ta=(e,t,n,r)=>{let o=e._zod.def,s=Q(o.left,t,{...r,path:[...r.path,"allOf",0]}),i=Q(o.right,t,{...r,path:[...r.path,"allOf",1]}),c=u=>"allOf"in u&&Object.keys(u).length===1,a=[...c(s)?s.allOf:[s],...c(i)?i.allOf:[i]];n.allOf=a};var za=(e,t,n,r)=>{let o=n,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 d=Q(s.valueType,t,{...r,path:[...r.path,"patternProperties","*"]});o.patternProperties={};for(let l of a)o.patternProperties[l.source]=d}else(t.target==="draft-07"||t.target==="draft-2020-12")&&(o.propertyNames=Q(s.keyType,t,{...r,path:[...r.path,"propertyNames"]})),o.additionalProperties=Q(s.valueType,t,{...r,path:[...r.path,"additionalProperties"]});let u=i._zod.values;if(u){let d=[...u].filter(l=>typeof l=="string"||typeof l=="number");d.length>0&&(o.required=d)}},Pa=(e,t,n,r)=>{let o=e._zod.def,s=Q(o.innerType,t,r),i=t.seen.get(e);t.target==="openapi-3.0"?(i.ref=o.innerType,n.nullable=!0):n.anyOf=[s,{type:"null"}]},La=(e,t,n,r)=>{let o=e._zod.def;Q(o.innerType,t,r);let s=t.seen.get(e);s.ref=o.innerType},Ma=(e,t,n,r)=>{let o=e._zod.def;Q(o.innerType,t,r);let s=t.seen.get(e);s.ref=o.innerType,n.default=JSON.parse(JSON.stringify(o.defaultValue))},Za=(e,t,n,r)=>{let o=e._zod.def;Q(o.innerType,t,r);let s=t.seen.get(e);s.ref=o.innerType,t.io==="input"&&(n._prefault=JSON.parse(JSON.stringify(o.defaultValue)))},Fa=(e,t,n,r)=>{let o=e._zod.def;Q(o.innerType,t,r);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")}n.default=i},Ba=(e,t,n,r)=>{let o=e._zod.def,s=o.in._zod.traits.has("$ZodTransform"),i=t.io==="input"?s?o.out:o.in:o.out;Q(i,t,r);let c=t.seen.get(e);c.ref=i},ja=(e,t,n,r)=>{let o=e._zod.def;Q(o.innerType,t,r);let s=t.seen.get(e);s.ref=o.innerType,n.readOnly=!0};var No=(e,t,n,r)=>{let o=e._zod.def;Q(o.innerType,t,r);let s=t.seen.get(e);s.ref=o.innerType},Ua=(e,t,n,r)=>{let o=e._zod.innerType;Q(o,t,r);let s=t.seen.get(e);s.ref=o};var hd=g("ZodISODateTime",(e,t)=>{ec.init(e,t),j.init(e,t)});function Qa(e){return ca(hd,e)}var yd=g("ZodISODate",(e,t)=>{tc.init(e,t),j.init(e,t)});function Ja(e){return aa(yd,e)}var gd=g("ZodISOTime",(e,t)=>{nc.init(e,t),j.init(e,t)});function Va(e){return ua(gd,e)}var bd=g("ZodISODuration",(e,t)=>{rc.init(e,t),j.init(e,t)});function Ga(e){return la(bd,e)}var xd=(e,t)=>{Pn.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:n=>zs(e,n)},flatten:{value:n=>Ts(e,n)},addIssue:{value:n=>{e.issues.push(n),e.message=JSON.stringify(e.issues,Et,2)}},addIssues:{value:n=>{e.issues.push(...n),e.message=JSON.stringify(e.issues,Et,2)}},isEmpty:{get(){return e.issues.length===0}}})};var ie=g("ZodError",xd,{Parent:Error});var qa=Ln(ie),Ka=Mn(ie),Wa=en(ie),Ya=tn(ie),Xa=Ms(ie),Ha=Zs(ie),eu=Fs(ie),tu=Bs(ie),nu=js(ie),ru=Us(ie),ou=Qs(ie),su=Js(ie);var iu=new WeakMap;function cn(e,t,n){let r=Object.getPrototypeOf(e),o=iu.get(r);if(o||(o=new Set,iu.set(r,o)),!o.has(t)){o.add(t);for(let s in n){let i=n[s];Object.defineProperty(r,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 B=g("ZodType",(e,t)=>(Z.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:sn(e,"input"),output:sn(e,"output")}}),e.toJSONSchema=_a(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(n,r)=>qa(e,n,r,{callee:e.parse}),e.safeParse=(n,r)=>Wa(e,n,r),e.parseAsync=async(n,r)=>Ka(e,n,r,{callee:e.parseAsync}),e.safeParseAsync=async(n,r)=>Ya(e,n,r),e.spa=e.safeParseAsync,e.encode=(n,r)=>Xa(e,n,r),e.decode=(n,r)=>Ha(e,n,r),e.encodeAsync=async(n,r)=>eu(e,n,r),e.decodeAsync=async(n,r)=>tu(e,n,r),e.safeEncode=(n,r)=>nu(e,n,r),e.safeDecode=(n,r)=>ru(e,n,r),e.safeEncodeAsync=async(n,r)=>ou(e,n,r),e.safeDecodeAsync=async(n,r)=>su(e,n,r),cn(e,"ZodType",{check(...n){let r=this.def;return this.clone(z.mergeDefs(r,{checks:[...r.checks??[],...n.map(o=>typeof o=="function"?{_zod:{check:o,def:{check:"custom"},onattach:[]}}:o)]}),{parent:!0})},with(...n){return this.check(...n)},clone(n,r){return ye(this,n,r)},brand(){return this},register(n,r){return n.add(this,r),this},refine(n,r){return this.check(hp(n,r))},superRefine(n,r){return this.check(yp(n,r))},overwrite(n){return this.check(He(n))},optional(){return fu(this)},exactOptional(){return tp(this)},nullable(){return du(this)},nullish(){return fu(du(this))},nonoptional(n){return cp(this,n)},array(){return U(this)},or(n){return Yn([this,n])},and(n){return Wd(this,n)},transform(n){return pu(this,Hd(n))},default(n){return op(this,n)},prefault(n){return ip(this,n)},catch(n){return up(this,n)},pipe(n){return pu(this,n)},readonly(){return dp(this)},describe(n){let r=this.clone();return pt.add(r,{description:n}),r},meta(...n){if(n.length===0)return pt.get(this);let r=this.clone();return pt.add(r,n[0]),r},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(n){return n(this)}}),Object.defineProperty(e,"description",{get(){return pt.get(e)?.description},configurable:!0}),e)),mu=g("_ZodString",(e,t)=>{Un.init(e,t),B.init(e,t),e._zod.processJSONSchema=(r,o,s)=>xa(e,r,o,s);let n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,cn(e,"_ZodString",{regex(...r){return this.check(bo(...r))},includes(...r){return this.check(xo(...r))},startsWith(...r){return this.check(Eo(...r))},endsWith(...r){return this.check(So(...r))},min(...r){return this.check(kt(...r))},max(...r){return this.check(Gn(...r))},length(...r){return this.check(qn(...r))},nonempty(...r){return this.check(kt(1,...r))},lowercase(r){return this.check(wo(r))},uppercase(r){return this.check(_o(r))},trim(){return this.check(ko())},normalize(...r){return this.check(vo(...r))},toLowerCase(){return this.check(Ao())},toUpperCase(){return this.check(Do())},slugify(){return this.check(Io())}})}),Sd=g("ZodString",(e,t)=>{Un.init(e,t),mu.init(e,t),e.email=n=>e.check(Fc(vd,n)),e.url=n=>e.check(Jc(kd,n)),e.jwt=n=>e.check(ia(Fd,n)),e.emoji=n=>e.check(Vc(Ad,n)),e.guid=n=>e.check(go(cu,n)),e.uuid=n=>e.check(Bc(Wn,n)),e.uuidv4=n=>e.check(jc(Wn,n)),e.uuidv6=n=>e.check(Uc(Wn,n)),e.uuidv7=n=>e.check(Qc(Wn,n)),e.nanoid=n=>e.check(Gc(Dd,n)),e.guid=n=>e.check(go(cu,n)),e.cuid=n=>e.check(qc(Id,n)),e.cuid2=n=>e.check(Kc(Od,n)),e.ulid=n=>e.check(Wc($d,n)),e.base64=n=>e.check(ra(Ld,n)),e.base64url=n=>e.check(oa(Md,n)),e.xid=n=>e.check(Yc(Rd,n)),e.ksuid=n=>e.check(Xc(Nd,n)),e.ipv4=n=>e.check(Hc(Cd,n)),e.ipv6=n=>e.check(ea(Td,n)),e.cidrv4=n=>e.check(ta(zd,n)),e.cidrv6=n=>e.check(na(Pd,n)),e.e164=n=>e.check(sa(Zd,n)),e.datetime=n=>e.check(Qa(n)),e.date=n=>e.check(Ja(n)),e.time=n=>e.check(Va(n)),e.duration=n=>e.check(Ga(n))});function k(e){return Zc(Sd,e)}var j=g("ZodStringFormat",(e,t)=>{F.init(e,t),mu.init(e,t)}),vd=g("ZodEmail",(e,t)=>{Ji.init(e,t),j.init(e,t)});var cu=g("ZodGUID",(e,t)=>{Ui.init(e,t),j.init(e,t)});var Wn=g("ZodUUID",(e,t)=>{Qi.init(e,t),j.init(e,t)});var kd=g("ZodURL",(e,t)=>{Vi.init(e,t),j.init(e,t)});var Ad=g("ZodEmoji",(e,t)=>{Gi.init(e,t),j.init(e,t)});var Dd=g("ZodNanoID",(e,t)=>{qi.init(e,t),j.init(e,t)});var Id=g("ZodCUID",(e,t)=>{Ki.init(e,t),j.init(e,t)});var Od=g("ZodCUID2",(e,t)=>{Wi.init(e,t),j.init(e,t)});var $d=g("ZodULID",(e,t)=>{Yi.init(e,t),j.init(e,t)});var Rd=g("ZodXID",(e,t)=>{Xi.init(e,t),j.init(e,t)});var Nd=g("ZodKSUID",(e,t)=>{Hi.init(e,t),j.init(e,t)});var Cd=g("ZodIPv4",(e,t)=>{oc.init(e,t),j.init(e,t)});var Td=g("ZodIPv6",(e,t)=>{sc.init(e,t),j.init(e,t)});var zd=g("ZodCIDRv4",(e,t)=>{ic.init(e,t),j.init(e,t)});var Pd=g("ZodCIDRv6",(e,t)=>{cc.init(e,t),j.init(e,t)});var Ld=g("ZodBase64",(e,t)=>{uc.init(e,t),j.init(e,t)});var Md=g("ZodBase64URL",(e,t)=>{lc.init(e,t),j.init(e,t)});var Zd=g("ZodE164",(e,t)=>{fc.init(e,t),j.init(e,t)});var Fd=g("ZodJWT",(e,t)=>{dc.init(e,t),j.init(e,t)});var hu=g("ZodNumber",(e,t)=>{po.init(e,t),B.init(e,t),e._zod.processJSONSchema=(r,o,s)=>Ea(e,r,o,s),cn(e,"ZodNumber",{gt(r,o){return this.check(Jn(r,o))},gte(r,o){return this.check(on(r,o))},min(r,o){return this.check(on(r,o))},lt(r,o){return this.check(Qn(r,o))},lte(r,o){return this.check(rn(r,o))},max(r,o){return this.check(rn(r,o))},int(r){return this.check(au(r))},safe(r){return this.check(au(r))},positive(r){return this.check(Jn(0,r))},nonnegative(r){return this.check(on(0,r))},negative(r){return this.check(Qn(0,r))},nonpositive(r){return this.check(rn(0,r))},multipleOf(r,o){return this.check(Vn(r,o))},step(r,o){return this.check(Vn(r,o))},finite(){return this}});let n=e._zod.bag;e.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null});function M(e){return fa(hu,e)}var Bd=g("ZodNumberFormat",(e,t)=>{pc.init(e,t),hu.init(e,t)});function au(e){return da(Bd,e)}var jd=g("ZodBoolean",(e,t)=>{mc.init(e,t),B.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Sa(e,n,r,o)});function et(e){return pa(jd,e)}var Ud=g("ZodNull",(e,t)=>{hc.init(e,t),B.init(e,t),e._zod.processJSONSchema=(n,r,o)=>va(e,n,r,o)});function Qd(e){return ma(Ud,e)}var Jd=g("ZodUnknown",(e,t)=>{yc.init(e,t),B.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Aa(e,n,r,o)});function uu(){return ha(Jd)}var Vd=g("ZodNever",(e,t)=>{gc.init(e,t),B.init(e,t),e._zod.processJSONSchema=(n,r,o)=>ka(e,n,r,o)});function yu(e){return ya(Vd,e)}var Gd=g("ZodArray",(e,t)=>{bc.init(e,t),B.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Ra(e,n,r,o),e.element=t.element,cn(e,"ZodArray",{min(n,r){return this.check(kt(n,r))},nonempty(n){return this.check(kt(1,n))},max(n,r){return this.check(Gn(n,r))},length(n,r){return this.check(qn(n,r))},unwrap(){return this.element}})});function U(e,t){return ga(Gd,e,t)}var gu=g("ZodObject",(e,t)=>{xc.init(e,t),B.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Na(e,n,r,o),z.defineLazy(e,"shape",()=>t.shape),cn(e,"ZodObject",{keyof(){return ce(Object.keys(this._zod.def.shape))},catchall(n){return this.clone({...this._zod.def,catchall:n})},passthrough(){return this.clone({...this._zod.def,catchall:uu()})},loose(){return this.clone({...this._zod.def,catchall:uu()})},strict(){return this.clone({...this._zod.def,catchall:yu()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(n){return z.extend(this,n)},safeExtend(n){return z.safeExtend(this,n)},merge(n){return z.merge(this,n)},pick(n){return z.pick(this,n)},omit(n){return z.omit(this,n)},partial(...n){return z.partial(wu,this,n[0])},required(...n){return z.required(_u,this,n[0])}})});function de(e,t){let n={type:"object",shape:e??{},...z.normalizeParams(t)};return new gu(n)}function O(e,t){return new gu({type:"object",shape:e,catchall:yu(),...z.normalizeParams(t)})}var bu=g("ZodUnion",(e,t)=>{mo.init(e,t),B.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Ca(e,n,r,o),e.options=t.options});function Yn(e,t){return new bu({type:"union",options:e,...z.normalizeParams(t)})}var qd=g("ZodDiscriminatedUnion",(e,t)=>{bu.init(e,t),Ec.init(e,t)});function At(e,t,n){return new qd({type:"union",options:t,discriminator:e,...z.normalizeParams(n)})}var Kd=g("ZodIntersection",(e,t)=>{Sc.init(e,t),B.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Ta(e,n,r,o)});function Wd(e,t){return new Kd({type:"intersection",left:e,right:t})}var lu=g("ZodRecord",(e,t)=>{vc.init(e,t),B.init(e,t),e._zod.processJSONSchema=(n,r,o)=>za(e,n,r,o),e.keyType=t.keyType,e.valueType=t.valueType});function Ie(e,t,n){return!t||!t._zod?new lu({type:"record",keyType:k(),valueType:e,...z.normalizeParams(t)}):new lu({type:"record",keyType:e,valueType:t,...z.normalizeParams(n)})}var Co=g("ZodEnum",(e,t)=>{kc.init(e,t),B.init(e,t),e._zod.processJSONSchema=(r,o,s)=>Da(e,r,o,s),e.enum=t.entries,e.options=Object.values(t.entries);let n=new Set(Object.keys(t.entries));e.extract=(r,o)=>{let s={};for(let i of r)if(n.has(i))s[i]=t.entries[i];else throw new Error(`Key ${i} not found in enum`);return new Co({...t,checks:[],...z.normalizeParams(o),entries:s})},e.exclude=(r,o)=>{let s={...t.entries};for(let i of r)if(n.has(i))delete s[i];else throw new Error(`Key ${i} not found in enum`);return new Co({...t,checks:[],...z.normalizeParams(o),entries:s})}});function ce(e,t){let n=Array.isArray(e)?Object.fromEntries(e.map(r=>[r,r])):e;return new Co({type:"enum",entries:n,...z.normalizeParams(t)})}var Yd=g("ZodLiteral",(e,t)=>{Ac.init(e,t),B.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Ia(e,n,r,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 P(e,t){return new Yd({type:"literal",values:Array.isArray(e)?e:[e],...z.normalizeParams(t)})}var Xd=g("ZodTransform",(e,t)=>{Dc.init(e,t),B.init(e,t),e._zod.processJSONSchema=(n,r,o)=>$a(e,n,r,o),e._zod.parse=(n,r)=>{if(r.direction==="backward")throw new _t(e.constructor.name);n.addIssue=s=>{if(typeof s=="string")n.issues.push(z.issue(s,n.value,t));else{let i=s;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=n.value),i.inst??(i.inst=e),n.issues.push(z.issue(i))}};let o=t.transform(n.value,n);return o instanceof Promise?o.then(s=>(n.value=s,n.fallback=!0,n)):(n.value=o,n.fallback=!0,n)}});function Hd(e){return new Xd({type:"transform",transform:e})}var wu=g("ZodOptional",(e,t)=>{ho.init(e,t),B.init(e,t),e._zod.processJSONSchema=(n,r,o)=>No(e,n,r,o),e.unwrap=()=>e._zod.def.innerType});function fu(e){return new wu({type:"optional",innerType:e})}var ep=g("ZodExactOptional",(e,t)=>{Ic.init(e,t),B.init(e,t),e._zod.processJSONSchema=(n,r,o)=>No(e,n,r,o),e.unwrap=()=>e._zod.def.innerType});function tp(e){return new ep({type:"optional",innerType:e})}var np=g("ZodNullable",(e,t)=>{Oc.init(e,t),B.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Pa(e,n,r,o),e.unwrap=()=>e._zod.def.innerType});function du(e){return new np({type:"nullable",innerType:e})}var rp=g("ZodDefault",(e,t)=>{$c.init(e,t),B.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Ma(e,n,r,o),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function op(e,t){return new rp({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():z.shallowClone(t)}})}var sp=g("ZodPrefault",(e,t)=>{Rc.init(e,t),B.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Za(e,n,r,o),e.unwrap=()=>e._zod.def.innerType});function ip(e,t){return new sp({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():z.shallowClone(t)}})}var _u=g("ZodNonOptional",(e,t)=>{Nc.init(e,t),B.init(e,t),e._zod.processJSONSchema=(n,r,o)=>La(e,n,r,o),e.unwrap=()=>e._zod.def.innerType});function cp(e,t){return new _u({type:"nonoptional",innerType:e,...z.normalizeParams(t)})}var ap=g("ZodCatch",(e,t)=>{Cc.init(e,t),B.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Fa(e,n,r,o),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function up(e,t){return new ap({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}var lp=g("ZodPipe",(e,t)=>{Tc.init(e,t),B.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Ba(e,n,r,o),e.in=t.in,e.out=t.out});function pu(e,t){return new lp({type:"pipe",in:e,out:t})}var fp=g("ZodReadonly",(e,t)=>{zc.init(e,t),B.init(e,t),e._zod.processJSONSchema=(n,r,o)=>ja(e,n,r,o),e.unwrap=()=>e._zod.def.innerType});function dp(e){return new fp({type:"readonly",innerType:e})}var pp=g("ZodLazy",(e,t)=>{Pc.init(e,t),B.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Ua(e,n,r,o),e.unwrap=()=>e._zod.def.getter()});function To(e){return new pp({type:"lazy",getter:e})}var mp=g("ZodCustom",(e,t)=>{Lc.init(e,t),B.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Oa(e,n,r,o)});function hp(e,t={}){return ba(mp,e,t)}function yp(e,t){return wa(e,t)}function tt(e){let t=To(()=>Yn([k(e),M(),et(),Qd(),U(t),Ie(k(),t)]));return t}var xu=e=>"field"in e?[e]:("all"in e?e.all:e.any).flatMap(xu),Xn=e=>xu(e);var Dt=(e,t)=>{if("field"in e)return t(e);let n="all"in e?e.all:e.any,r=!1;if("all"in e){for(let o of n){let s=Dt(o,t);if(s===!1)return!1;r||=s===void 0}return r?void 0:!0}for(let o of n){let s=Dt(o,t);if(s===!0)return!0;r||=s===void 0}return r?void 0:!1},Eu=e=>JSON.stringify(e),zo=e=>{if("field"in e)return{conditions:1,depth:0};let t="all"in e?e.all:e.any,n=0,r=1;for(let o of t){let s=zo(o);n+=s.conditions,r=Math.max(r,s.depth+1)}return{conditions:n,depth:r}},Su=(e,t={})=>{let n=o=>{let s=U(o),i=t.maximumChildren===void 0?s:s.max(t.maximumChildren);return Yn([e,O({all:i}),O({any:i})])},r=To(()=>n(r));return t.maximumConditions===void 0&&t.maximumDepth===void 0?r:r.superRefine((o,s)=>{let{conditions:i,depth:c}=zo(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 D={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};function mt(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 r=mt(e.toJSON(),t);return t.delete(e),r}if(t.has(e))throw new Error("Circular reference detected");t.add(e);let n;if(Array.isArray(e))n=`[${e.map(o=>mt(o===void 0||typeof o=="symbol"?null:o,t)).join(",")}]`;else{let r=[];for(let o of Object.keys(e).sort())e[o]===void 0||typeof e[o]=="symbol"||r.push(`${mt(o)}:${mt(e[o],t)}`);n=`{${r.join(",")}}`}return t.delete(e),n}var gp=new TextEncoder,It=e=>gp.encode(e),Oe=e=>It(e).byteLength,te=class extends Error{constructor(){super("Byte stream exceeds the configured limit"),this.name="ByteLimitExceededError"}},bp=(e,t)=>{let n=new Uint8Array(t),r=0;for(let o of e)n.set(o,r),r+=o.byteLength;return n},Ot=e=>typeof e=="string"?{async*[Symbol.asyncIterator](){yield It(e)}}:e instanceof Uint8Array?{async*[Symbol.asyncIterator](){yield e}}:e,wp=async(e,t)=>{let n=[],r=0;for await(let o of Ot(e)){let s=t-r;if(s<=0)break;let i=o.subarray(0,s);if(n.push(i),r+=i.byteLength,r===t)break}return bp(n,r)},pe=async(e,t)=>{let n=await wp(e,t+1);if(n.byteLength>t)throw new te;return n},ae=e=>new TextDecoder("utf-8",{fatal:!0}).decode(e),$t=e=>e.charCodeAt(0)===65279?e.slice(1):e;var vu=e=>{for(let t=0;t<e.length;t+=1){let n=e.charCodeAt(t);if(n>=55296&&n<=56319){let r=e.charCodeAt(t+1);if(t+1>=e.length||r<56320||r>57343)throw new Error("JSON strings cannot contain lone Unicode surrogates");t+=1;continue}if(n>=56320&&n<=57343)throw new Error("JSON strings cannot contain lone Unicode surrogates")}},Po=(e,t)=>{if(e===null||typeof e=="boolean")return e;if(typeof e=="string")return vu(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 n=[];for(let r=0;r<e.length;r+=1){if(Object.hasOwn(e,r)===!1)throw new Error("JSON arrays cannot be sparse");let o=e[r];if(o===void 0)throw new Error("JSON arrays cannot contain undefined values");n.push(Po(o,t))}if(Object.keys(e).length!==e.length)throw new Error("JSON arrays cannot contain named properties");return n}finally{t.delete(e)}}if(typeof e=="object"){let n=Object.getPrototypeOf(e);if(n!==Object.prototype&&n!==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 r={};try{for(let[o,s]of Object.entries(e))vu(o),s!==void 0&&Object.defineProperty(r,o,{value:Po(s,t),enumerable:!0,configurable:!0,writable:!0})}finally{t.delete(e)}return r}throw new Error("Value cannot be represented as JSON")},nt=e=>Po(e,new Set),$e=e=>{let t=mt(nt(e));if(t===void 0)throw new Error("Value cannot be represented as canonical JSON");return t},Re=(e,t)=>e<t?-1:e>t?1:0,Lo=async e=>{let t=typeof e=="string"?It(e):e,n=await globalThis.crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(n),r=>r.toString(16).padStart(2,"0")).join("")},ku=async e=>`sha256:${await Lo(e)}`;var Au=At("type",[O({type:P("document")}),O({type:P("json"),path:U(k()).min(1)}),O({type:P("markdown-body")}),O({type:P("markdown-frontmatter")})]),Mo=O({documentId:k().min(1),revision:k().min(1),representation:Au}),_p=e=>{let t=Au.parse(e);return t.type==="json"?Object.freeze({...t,path:Object.freeze([...t.path])}):Object.freeze(t)},Du=e=>{let t=Mo.parse(e);return Object.freeze({...t,representation:_p(t.representation)})};var Hn=O({id:k().min(1),revision:k().min(1),contentRef:k().min(1),format:ce(["json","markdown"]).optional()}),er=O({sourceId:k().min(1),referenceId:k().min(1),reference:Mo});var Rt=e=>{let t=new Map;for(let n of e){let r=t.get(n.sourceId)??[];r.push(n),t.set(n.sourceId,r)}return t};var Ne=class extends Error{code;documentIds;constructor({code:t,message:n,documentIds:r=[]}){super(n),this.name="DocumentGraphError",this.code=t,this.documentIds=Object.freeze([...r])}},xp=(e,t)=>Re(e.sourceId,t.sourceId)||Re(e.referenceId,t.referenceId),an=({nodes:e,edges:t})=>{let n=e.map(c=>Object.freeze(Hn.parse(c))).sort((c,a)=>Re(c.id,a.id)),r=new Map,o=new Map;for(let c of n){if(r.has(c.id))throw new Ne({code:"DUPLICATE_NODE",message:`Document graph contains duplicate node ${c.id}`,documentIds:[c.id]});r.set(c.id,c);let a=o.get(c.contentRef);if(a!==void 0&&(a.revision!==c.revision||a.format!==c.format))throw new Ne({code:"CONTENT_IDENTITY_CONFLICT",message:`Document graph content reference ${c.contentRef} has conflicting identities`,documentIds:[a.id,c.id]});o.set(c.contentRef,c)}let s=t.map(c=>{let a=er.parse(c);return Object.freeze({...a,reference:Du(a.reference)})}).sort(xp),i=new Set;for(let c of s){if(r.get(c.sourceId)===void 0)throw new Ne({code:"SOURCE_NOT_FOUND",message:`Document graph source ${c.sourceId} does not exist`,documentIds:[c.sourceId]});let u=r.get(c.reference.documentId);if(u===void 0)throw new Ne({code:"TARGET_NOT_FOUND",message:`Document graph target ${c.reference.documentId} does not exist`,documentIds:[c.sourceId,c.reference.documentId]});if(u.revision!==c.reference.revision)throw new Ne({code:"TARGET_REVISION_MISMATCH",message:`Document graph target ${u.id} revision does not match its reference`,documentIds:[c.sourceId,u.id]});let d=`${c.sourceId}\0${c.referenceId}`;if(i.has(d))throw new Ne({code:"DUPLICATE_REFERENCE",message:`Document ${c.sourceId} contains duplicate reference ID ${c.referenceId}`,documentIds:[c.sourceId]});i.add(d)}return Object.freeze({nodes:Object.freeze(n),edges:Object.freeze(s)})},Ep=e=>new Map(e.nodes.map(t=>[t.id,t]));var tr=({graph:e,rootIds:t})=>{let n=Ep(e),r=Rt(e.edges),o=new Map,s=[],i=[],c=a=>{let u=n.get(a);if(u===void 0)throw new Ne({code:"ROOT_NOT_FOUND",message:`Document graph root ${a} does not exist`,documentIds:[a]});let d=o.get(a);if(d!=="visited"){if(d==="visiting"){let l=s.indexOf(a),f=[...s.slice(l),a];throw new Ne({code:"CYCLE",message:`Document graph contains a cycle: ${f.join(" -> ")}`,documentIds:f})}o.set(a,"visiting"),s.push(a);for(let l of r.get(a)??[])c(l.reference.documentId);s.pop(),o.set(a,"visited"),i.push(u)}};for(let a of[...new Set(t)].sort(Re))c(a);return Object.freeze(i)};var Sp=k().regex(/^sha256:[a-f0-9]{64}$/),Iu=O({format:P("webstudio-document-graph"),version:P(1),nodes:U(Hn),edges:U(er),integrity:O({algorithm:P("sha256"),checksum:Sp})});var vp=k().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"}),Ru=O({_id:k().min(1),_type:P("asset.file"),name:k().min(1),description:k().optional(),path:vp,key:k(),folderId:k().min(1).optional(),extension:k().regex(/^[a-z0-9]*$/),mimeType:k().min(1),size:M().int().nonnegative(),createdAt:k().datetime().optional(),revision:k().min(1),contentRef:k().min(1),properties:Ie(k(),tt()),excerpt:k().optional(),metadataError:O({code:k().min(1),message:k().min(1)}).optional()}),Fo=Ru.partial().required({_id:!0}),kp=ce(["null","boolean","number","string","object","array"]),Ap=de({format:P("webstudio-builder-asset-field-catalog"),version:P(1),canonicalRevision:k().regex(/^sha256:[a-f0-9]{64}$/),documentCount:M().int().nonnegative(),fields:Ie(k().min(1),de({queryPath:U(k().min(1)).min(1).max(D.fieldPathDepth).optional(),types:U(kp).min(1),occurrences:M().int().positive(),optional:P(!0).optional(),mixed:P(!0).optional()}))}).superRefine((e,t)=>{for(let[n,r]of Object.entries(e.fields)){let o=[...new Set(r.types)].sort();JSON.stringify(r.types)!==JSON.stringify(o)&&t.addIssue({code:"custom",path:["fields",n,"types"],message:"Observed field types must be unique and sorted"}),r.occurrences>e.documentCount&&t.addIssue({code:"custom",path:["fields",n,"occurrences"],message:"Field occurrences cannot exceed the document count"});let s=r.occurrences<e.documentCount;r.optional===!0!==s&&t.addIssue({code:"custom",path:["fields",n,"optional"],message:"Field optionality must match its occurrence count"});let i=o.length>1;r.mixed===!0!==i&&t.addIssue({code:"custom",path:["fields",n,"mixed"],message:"Mixed status must match the observed types"})}}),nr=k().regex(/^sha256:[a-f0-9]{64}$/),Nu=O({fields:U(U(k().min(1)).min(1).max(D.fieldPathDepth)).min(1).max(D.outputFieldCount+1),rows:U(U(tt())).max(D.resultCount),totalCount:M().int().nonnegative().max(D.candidateDocuments),hasMore:et()}).superRefine(({fields:e,rows:t},n)=>{for(let[r,o]of t.entries())o.length!==e.length&&n.addIssue({code:"custom",path:["rows",r],message:"Materialized query rows must match the field count"})}),Ou=O({format:P("webstudio-content-database"),version:P(1),assetRevision:nr,documents:U(Fo),documentGraph:Iu.optional(),contents:Ie(k().min(1),k()).optional(),assetReferences:Ie(k().min(1),U(O({start:M().int().nonnegative(),end:M().int().positive(),assetId:k().min(1),suffix:k().min(1).optional()}).refine(({start:e,end:t})=>t>e,{message:"Markdown asset reference range must not be empty"}))).optional(),fieldCatalog:Ap,queries:Ie(nr,Nu).optional(),database:O({maxBytes:M().int().positive(),unboundedBytes:M().int().nonnegative(),sourceDocumentCount:M().int().nonnegative(),includedDocumentCount:M().int().nonnegative().optional()}).optional(),integrity:O({algorithm:P("sha256"),checksum:nr})}).superRefine((e,t)=>{e.documents.length>D.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 n;for(let[o,s]of e.documents.entries())n!==void 0&&s._id<=n&&t.addIssue({code:"custom",path:["documents",o,"_id"],message:"Asset index documents must have unique sorted IDs"}),n=s._id;let r=new Set(e.documents.flatMap(({contentRef:o})=>o===void 0?[]:[o]));for(let o of Object.keys(e.contents??{}))r.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??{}))r.has(o)===!1&&t.addIssue({code:"custom",path:["assetReferences",o],message:"Asset references must belong to an indexed document"})}),Dp=At("mode",[de({mode:P("none")}),de({mode:P("full"),maxBytes:M().int().positive().max(D.hydratedFileBytes).optional()}),de({mode:P("range"),offset:M().int().nonnegative(),length:M().int().positive().max(D.hydratedRangeBytes)}),de({mode:P("markdown-body"),maxBytes:M().int().positive().max(D.hydratedFileBytes).optional()})]),Bo={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"]},Cu=Object.keys(Bo),Tu=["url","width","height"],rr=e=>Tu.includes(e),zu=Cu.filter(e=>rr(e)===!1&&e!=="excerpt"),Pu=zu.filter(e=>e!=="id"),Lu=e=>zu.includes(e),Ip=ce(Cu),un=U(k().min(1)).min(1).max(D.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||Ip.safeParse(e[0]).success===!1)&&t.addIssue({code:"custom",message:"Asset query field path is unsupported"})}),Zo=et().default(!0),Op=At("mode",[O({mode:P("all"),includeMetadata:Zo}),O({mode:P("base"),includeMetadata:Zo}),O({mode:P("fields"),includeMetadata:Zo,fields:U(un).max(D.outputFieldCount).refine(e=>new Set(e.map(Eu)).size===e.length,{error:"Selected output fields must be unique"})})]),$p={mode:"fields",includeMetadata:!1,fields:Tu.map(e=>[e])},Mu=["eq","ne","contains","startsWith","endsWith","gt","gte","lt","lte"],Ug=[...Mu,"in","exists","isEmpty"],Rp=O({field:un,operator:ce(Mu),value:tt()}),Np=O({field:un,operator:P("in"),value:U(tt()).max(D.resultCount)}),Cp=O({field:un,operator:ce(["exists","isEmpty"]),value:et()}),Tp=At("operator",[Rp,Np,Cp]),zp=Su(Tp,{maximumChildren:D.filterCount,maximumConditions:D.filterCount,maximumDepth:D.filterDepth,maximumConditionsMessage:"Asset query exceeds the filter limit",maximumDepthMessage:"Asset query exceeds the filter nesting limit"});var Pp=zp,Zu=e=>{let t=new Set(["eq","ne","in","exists"]);return e.some(n=>n==="string"||n==="array")&&t.add("contains"),e.includes("string")&&(t.add("startsWith"),t.add("endsWith")),e.some(n=>n==="string"||n==="number")&&(t.add("gt"),t.add("gte"),t.add("lt"),t.add("lte")),e.some(n=>n==="string"||n==="array"||n==="object")&&t.add("isEmpty"),[...t]},Lp=O({field:un,direction:ce(["asc","desc"])}),Mp=({output:e,content:t})=>e.includeMetadata||e.mode==="all"||e.mode==="fields"&&e.fields.length>0||t.mode!=="none",rt=O({where:Pp.default({all:[]}),sort:U(Lp).max(D.sortCount).default([]),limit:M().int().nonnegative().max(D.resultCount).default(D.defaultResultCount),offset:M().int().nonnegative().max(D.candidateDocuments).default(0),output:Op.default($p),content:Dp.default({mode:"none"})}).refine(Mp,{error:"Select at least one asset query output"}),Fu=O({query:rt,indexRevision:k().min(1).max(255).optional()}),Zp=de({_id:k().min(1),revision:k().min(1),contentRef:k().min(1),encoding:P("utf-8"),text:k(),range:de({offset:M().int().nonnegative(),length:M().int().nonnegative(),total:M().int().nonnegative()}).optional()}),Fp=Zp.omit({_id:!0,revision:!0,contentRef:!0}),Bp=Ru.omit({_id:!0,_type:!0,contentRef:!0}).partial().extend({id:k().min(1),url:k().min(1).optional(),width:M().positive().optional(),height:M().positive().optional(),content:Fp.optional()}).refine(e=>e.width===void 0==(e.height===void 0),{error:"Asset dimensions must include both width and height"}),jp=O({format:P("webstudio-content-database"),version:P(1),revision:nr,usedBytes:M().int().nonnegative(),maxBytes:M().int().positive(),unboundedBytes:M().int().nonnegative(),includedDocumentCount:M().int().nonnegative(),omittedDocumentCount:M().int().nonnegative(),omissionReason:ce(["size","unavailable"]).optional(),truncated:et()}),$u=jp.pick({usedBytes:!0,maxBytes:!0,unboundedBytes:!0,includedDocumentCount:!0,omittedDocumentCount:!0,omissionReason:!0,truncated:!0}),or=O({items:U(Bp),totalCount:M().int().nonnegative(),hasMore:et()}),Up=O({scope:P("query-preview"),query:$u,database:$u,artifacts:O({query:Ou,database:Ou}).optional(),unresolved:or.optional()}),Qg=O({data:or,__diagnostics__:Up}),Qp=ce(["INVALID_REQUEST","REQUEST_CANCELLED","UNAUTHORIZED","FORBIDDEN","STALE_INDEX","CONTENT_IDENTITY_REQUIRED","CONTENT_NOT_TEXT","CONTENT_DECODING_FAILED","CONTENT_LIMIT_EXCEEDED","INTERNAL_ERROR"]),Jp=de({ok:P(!1),error:de({code:Qp,message:k().min(1),retryable:et(),details:Ie(k(),tt()).optional()}),meta:de({queryHash:k().min(1).optional(),indexRevision:k().min(1).optional(),assetRevision:k().min(1).optional()}).optional()}),Bu=({code:e,message:t,retryable:n=!1,details:r})=>Jp.parse({ok:!1,error:{code:e,message:t,retryable:n,details:r}});var ju=function*(e){if(e.length>0&&!e.startsWith("/")||/~(?![01])/.test(e))throw Error("Invalid JSON Pointer");let t=1,n=0;for(;n<e.length;){let r=e.indexOf("/",t);n=r===-1?e.length:r;let o=e.slice(t,n);t=n+1,yield Gp(o)}};var jo=(e,t)=>t+"/"+Vp(e),Vp=e=>e.toString().replace(/~/g,"~0").replace(/\//g,"~1"),Gp=e=>e.toString().replace(/~1/g,"/").replace(/~0/g,"~");var sr=async(e,t,n)=>{if(Number.isSafeInteger(t)===!1||t<=0)throw new Error("Concurrency must be a positive safe integer");let r=0,o=new Array(e.length),s=async()=>{for(;r<e.length;){let u=r;r+=1,o[u]=await n(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 Nt=e=>typeof e=="object"&&e!==null&&Array.isArray(e)===!1,Uu=e=>{if(Nt(e)===!1)return;let t=Object.keys(e);if(!(t.length!==1||t[0]!=="$ref"))return e.$ref};var ue=class extends Error{code;referenceId;constructor({code:t,message:n,referenceId:r,cause:o}){super(n,{cause:o}),this.name="JsonDocumentError",this.code=t,this.referenceId=r}},qp=(e,t)=>{let n=Uu(e);if(n!==void 0){if(typeof n!="string")throw new ue({code:"INVALID_REFERENCE_MARKER",message:`JSON reference marker ${t} must contain a string $ref`,referenceId:t});return n}},Kp=e=>`#${e}`;var Qu=async({source:e,maximumBytes:t=D.hydratedFileBytes})=>{let n;try{n=await pe(e,t)}catch(o){throw o instanceof te?new ue({code:"CONTENT_LIMIT_EXCEEDED",message:"JSON document exceeds the byte limit",cause:o}):o}let r;try{r=$t(ae(n))}catch(o){throw new ue({code:"CONTENT_DECODING_FAILED",message:"JSON document is not valid UTF-8",cause:o})}try{return nt(JSON.parse(r))}catch(o){throw new ue({code:"INVALID_DOCUMENT",message:"JSON document is invalid",cause:o})}};var Wp=(e,t)=>{let n=e;for(let r of t){if(Array.isArray(n)){let o=Number(r);if(Number.isSafeInteger(o)===!1||o<0||String(o)!==r||o>=n.length)return;n=n[o];continue}if(Nt(n)&&Object.hasOwn(n,r)){n=n[r];continue}return}return n},Ju=({document:e,representation:t})=>{let n=nt(e);if(t.type==="document")return n;if(t.type!=="json")throw new ue({code:"UNSUPPORTED_REPRESENTATION",message:`JSON documents do not support ${t.type}`});let r=Wp(n,t.path);if(r===void 0)throw new ue({code:"JSON_PATH_NOT_FOUND",message:"JSON document path does not exist"});return r},Yp=(e,t,n)=>{Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0})},ir=({document:e,references:t,allowUnresolvedReferences:n=!1})=>{let r=nt(e),o=new Set,s=(c,a)=>{let u=Kp(a);if(qp(c,u)!==void 0){if(t.has(u)===!1){if(n)return c;throw new ue({code:"REFERENCE_NOT_FOUND",message:`Resolved JSON reference ${u} is unavailable`,referenceId:u})}o.add(u);try{return nt(t.get(u))}catch(l){throw new ue({code:"INVALID_RESOLVED_VALUE",message:`Resolved JSON reference ${u} is not JSON-compatible`,referenceId:u,cause:l})}}if(Array.isArray(c))return c.map((l,f)=>s(l,jo(String(f),a)));if(Nt(c)){let l={};for(let[f,p]of Object.entries(c))Yp(l,f,s(p,jo(f,a)));return l}return c},i=s(r,"");for(let c of[...t.keys()].sort())if(o.has(c)===!1)throw new ue({code:"UNUSED_REFERENCE",message:`Resolved JSON reference ${c} has no marker`,referenceId:c});return i};var cr=Symbol.for("yaml.alias"),ar=Symbol.for("yaml.document"),ge=Symbol.for("yaml.map"),Uo=Symbol.for("yaml.pair"),le=Symbol.for("yaml.scalar"),Ue=Symbol.for("yaml.seq"),ne=Symbol.for("yaml.node.type"),be=e=>!!e&&typeof e=="object"&&e[ne]===cr,Ce=e=>!!e&&typeof e=="object"&&e[ne]===ar,we=e=>!!e&&typeof e=="object"&&e[ne]===ge,N=e=>!!e&&typeof e=="object"&&e[ne]===Uo,$=e=>!!e&&typeof e=="object"&&e[ne]===le,_e=e=>!!e&&typeof e=="object"&&e[ne]===Ue;function L(e){if(e&&typeof e=="object")switch(e[ne]){case ge:case Ue:return!0}return!1}function T(e){if(e&&typeof e=="object")switch(e[ne]){case cr:case ge:case le:case Ue:return!0}return!1}var ur=e=>($(e)||L(e))&&!!e.anchor;var se=Symbol("break visit"),Vu=Symbol("skip children"),Te=Symbol("remove node");function ze(e,t){let n=Gu(t);Ce(e)?Ct(null,e.contents,n,Object.freeze([e]))===Te&&(e.contents=null):Ct(null,e,n,Object.freeze([]))}ze.BREAK=se;ze.SKIP=Vu;ze.REMOVE=Te;function Ct(e,t,n,r){let o=qu(e,t,n,r);if(T(o)||N(o))return Ku(e,r,o),Ct(e,o,n,r);if(typeof o!="symbol"){if(L(t)){r=Object.freeze(r.concat(t));for(let s=0;s<t.items.length;++s){let i=Ct(s,t.items[s],n,r);if(typeof i=="number")s=i-1;else{if(i===se)return se;i===Te&&(t.items.splice(s,1),s-=1)}}}else if(N(t)){r=Object.freeze(r.concat(t));let s=Ct("key",t.key,n,r);if(s===se)return se;s===Te&&(t.key=null);let i=Ct("value",t.value,n,r);if(i===se)return se;i===Te&&(t.value=null)}}return o}async function lr(e,t){let n=Gu(t);Ce(e)?await Tt(null,e.contents,n,Object.freeze([e]))===Te&&(e.contents=null):await Tt(null,e,n,Object.freeze([]))}lr.BREAK=se;lr.SKIP=Vu;lr.REMOVE=Te;async function Tt(e,t,n,r){let o=await qu(e,t,n,r);if(T(o)||N(o))return Ku(e,r,o),Tt(e,o,n,r);if(typeof o!="symbol"){if(L(t)){r=Object.freeze(r.concat(t));for(let s=0;s<t.items.length;++s){let i=await Tt(s,t.items[s],n,r);if(typeof i=="number")s=i-1;else{if(i===se)return se;i===Te&&(t.items.splice(s,1),s-=1)}}}else if(N(t)){r=Object.freeze(r.concat(t));let s=await Tt("key",t.key,n,r);if(s===se)return se;s===Te&&(t.key=null);let i=await Tt("value",t.value,n,r);if(i===se)return se;i===Te&&(t.value=null)}}return o}function Gu(e){return typeof e=="object"&&(e.Collection||e.Node||e.Value)?Object.assign({Alias:e.Node,Map:e.Node,Scalar:e.Node,Seq:e.Node},e.Value&&{Map:e.Value,Scalar:e.Value,Seq:e.Value},e.Collection&&{Map:e.Collection,Seq:e.Collection},e):e}function qu(e,t,n,r){if(typeof n=="function")return n(e,t,r);if(we(t))return n.Map?.(e,t,r);if(_e(t))return n.Seq?.(e,t,r);if(N(t))return n.Pair?.(e,t,r);if($(t))return n.Scalar?.(e,t,r);if(be(t))return n.Alias?.(e,t,r)}function Ku(e,t,n){let r=t[t.length-1];if(L(r))r.items[e]=n;else if(N(r))e==="key"?r.key=n:r.value=n;else if(Ce(r))r.contents=n;else{let o=be(r)?"alias":"scalar";throw new Error(`Cannot replace node with ${o} parent`)}}var Xp={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},Hp=e=>e.replace(/[!,[\]{}]/g,t=>Xp[t]),Pe=class e{constructor(t,n){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},e.defaultYaml,t),this.tags=Object.assign({},e.defaultTags,n)}clone(){let t=new e(this.yaml,this.tags);return t.docStart=this.docStart,t}atDocument(){let t=new e(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:e.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},e.defaultTags);break}return t}add(t,n){this.atNextDocument&&(this.yaml={explicit:e.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},e.defaultTags),this.atNextDocument=!1);let r=t.trim().split(/[ \t]+/),o=r.shift();switch(o){case"%TAG":{if(r.length!==2&&(n(0,"%TAG directive should contain exactly two parts"),r.length<2))return!1;let[s,i]=r;return this.tags[s]=i,!0}case"%YAML":{if(this.yaml.explicit=!0,r.length!==1)return n(0,"%YAML directive should contain exactly one part"),!1;let[s]=r;if(s==="1.1"||s==="1.2")return this.yaml.version=s,!0;{let i=/^\d+\.\d+$/.test(s);return n(6,`Unsupported YAML version ${s}`,i),!1}}default:return n(0,`Unknown directive ${o}`,!0),!1}}tagName(t,n){if(t==="!")return"!";if(t[0]!=="!")return n(`Not a valid tag: ${t}`),null;if(t[1]==="<"){let i=t.slice(2,-1);return i==="!"||i==="!!"?(n(`Verbatim tags aren't resolved, so ${t} is invalid.`),null):(t[t.length-1]!==">"&&n("Verbatim tags must end with a >"),i)}let[,r,o]=t.match(/^(.*!)([^!]*)$/s);o||n(`The ${t} tag has no suffix`);let s=this.tags[r];if(s)try{return s+decodeURIComponent(o)}catch(i){return n(String(i)),null}return r==="!"?t:(n(`Could not resolve tag: ${t}`),null)}tagString(t){for(let[n,r]of Object.entries(this.tags))if(t.startsWith(r))return n+Hp(t.substring(r.length));return t[0]==="!"?t:`!<${t}>`}toString(t){let n=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],r=Object.entries(this.tags),o;if(t&&r.length>0&&T(t.contents)){let s={};ze(t.contents,(i,c)=>{T(c)&&c.tag&&(s[c.tag]=!0)}),o=Object.keys(s)}else o=[];for(let[s,i]of r)s==="!!"&&i==="tag:yaml.org,2002:"||(!t||o.some(c=>c.startsWith(i)))&&n.push(`%TAG ${s} ${i}`);return n.join(`
+`)}};Pe.defaultYaml={explicit:!1,version:"1.2"};Pe.defaultTags={"!!":"tag:yaml.org,2002:"};function fr(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){let n=`Anchor must not contain whitespace or control characters: ${JSON.stringify(e)}`;throw new Error(n)}return!0}function Qo(e){let t=new Set;return ze(e,{Value(n,r){r.anchor&&t.add(r.anchor)}}),t}function Jo(e,t){for(let n=1;;++n){let r=`${e}${n}`;if(!t.has(r))return r}}function Wu(e,t){let n=[],r=new Map,o=null;return{onAnchor:s=>{n.push(s),o??(o=Qo(e));let i=Jo(t,o);return o.add(i),i},setAnchors:()=>{for(let s of n){let i=r.get(s);if(typeof i=="object"&&i.anchor&&($(i.node)||L(i.node)))i.node.anchor=i.anchor;else{let c=new Error("Failed to resolve repeated object (this should not happen)");throw c.source=s,c}}},sourceObjects:r}}function ot(e,t,n,r){if(r&&typeof r=="object")if(Array.isArray(r))for(let o=0,s=r.length;o<s;++o){let i=r[o],c=ot(e,r,String(o),i);c===void 0?delete r[o]:c!==i&&(r[o]=c)}else if(r instanceof Map)for(let o of Array.from(r.keys())){let s=r.get(o),i=ot(e,r,o,s);i===void 0?r.delete(o):i!==s&&r.set(o,i)}else if(r instanceof Set)for(let o of Array.from(r)){let s=ot(e,r,o,o);s===void 0?r.delete(o):s!==o&&(r.delete(o),r.add(s))}else for(let[o,s]of Object.entries(r)){let i=ot(e,r,o,s);i===void 0?delete r[o]:i!==s&&(r[o]=i)}return e.call(t,n,r)}function K(e,t,n){if(Array.isArray(e))return e.map((r,o)=>K(r,String(o),n));if(e&&typeof e.toJSON=="function"){if(!n||!ur(e))return e.toJSON(t,n);let r={aliasCount:0,count:1,res:void 0};n.anchors.set(e,r),n.onCreate=s=>{r.res=s,delete n.onCreate};let o=e.toJSON(t,n);return n.onCreate&&n.onCreate(o),o}return typeof e=="bigint"&&!n?.keep?Number(e):e}var st=class{constructor(t){Object.defineProperty(this,ne,{value:t})}clone(){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(t.range=this.range.slice()),t}toJS(t,{mapAsMap:n,maxAliasCount:r,onAnchor:o,reviver:s}={}){if(!Ce(t))throw new TypeError("A document argument is required");let i={anchors:new Map,doc:t,keep:!0,mapAsMap:n===!0,mapKeyWarned:!1,maxAliasCount:typeof r=="number"?r:100},c=K(this,"",i);if(typeof o=="function")for(let{count:a,res:u}of i.anchors.values())o(u,a);return typeof s=="function"?ot(s,{"":c},"",c):c}};var Qe=class extends st{constructor(t){super(cr),this.source=t,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(t,n){if(n?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let r;n?.aliasResolveCache?r=n.aliasResolveCache:(r=[],ze(t,{Node:(s,i)=>{(be(i)||ur(i))&&r.push(i)}}),n&&(n.aliasResolveCache=r));let o;for(let s of r){if(s===this)break;s.anchor===this.source&&(o=s)}return o}toJSON(t,n){if(!n)return{source:this.source};let{anchors:r,doc:o,maxAliasCount:s}=n,i=this.resolve(o,n);if(!i){let a=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(a)}let c=r.get(i);if(c||(K(i,null,n),c=r.get(i)),c?.res===void 0){let a="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(a)}if(s>=0&&(c.count+=1,c.aliasCount===0&&(c.aliasCount=dr(o,i,r)),c.count*c.aliasCount>s)){let a="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(a)}return c.res}toString(t,n,r){let o=`*${this.source}`;if(t){if(fr(this.source),t.options.verifyAliasOrder&&!t.anchors.has(this.source)){let s=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(s)}if(t.implicitKey)return`${o} `}return o}};function dr(e,t,n){if(be(t)){let r=t.resolve(e),o=n&&r&&n.get(r);return o?o.count*o.aliasCount:0}else if(L(t)){let r=0;for(let o of t.items){let s=dr(e,o,n);s>r&&(r=s)}return r}else if(N(t)){let r=dr(e,t.key,n),o=dr(e,t.value,n);return Math.max(r,o)}return 1}var pr=e=>!e||typeof e!="function"&&typeof e!="object",A=class extends st{constructor(t){super(le),this.value=t}toJSON(t,n){return n?.keep?this.value:K(this.value,t,n)}toString(){return String(this.value)}};A.BLOCK_FOLDED="BLOCK_FOLDED";A.BLOCK_LITERAL="BLOCK_LITERAL";A.PLAIN="PLAIN";A.QUOTE_DOUBLE="QUOTE_DOUBLE";A.QUOTE_SINGLE="QUOTE_SINGLE";var em="tag:yaml.org,2002:";function tm(e,t,n){if(t){let r=n.filter(s=>s.tag===t),o=r.find(s=>!s.format)??r[0];if(!o)throw new Error(`Tag ${t} not found`);return o}return n.find(r=>r.identify?.(e)&&!r.format)}function Je(e,t,n){if(Ce(e)&&(e=e.contents),T(e))return e;if(N(e)){let l=n.schema[ge].createNode?.(n.schema,null,n);return l.items.push(e),l}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<"u"&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects:r,onAnchor:o,onTagObj:s,schema:i,sourceObjects:c}=n,a;if(r&&e&&typeof e=="object"){if(a=c.get(e),a)return a.anchor??(a.anchor=o(e)),new Qe(a.anchor);a={anchor:null,node:null},c.set(e,a)}t?.startsWith("!!")&&(t=em+t.slice(2));let u=tm(e,t,i.tags);if(!u){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){let l=new A(e);return a&&(a.node=l),l}u=e instanceof Map?i[ge]:Symbol.iterator in Object(e)?i[Ue]:i[ge]}s&&(s(u),delete n.onTagObj);let d=u?.createNode?u.createNode(n.schema,e,n):typeof u?.nodeClass?.from=="function"?u.nodeClass.from(n.schema,e,n):new A(e);return t?d.tag=t:u.default||(d.tag=u.tag),a&&(a.node=d),d}function ln(e,t,n){let r=n;for(let o=t.length-1;o>=0;--o){let s=t[o];if(typeof s=="number"&&Number.isInteger(s)&&s>=0){let i=[];i[s]=r,r=i}else r=new Map([[s,r]])}return Je(r,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:e,sourceObjects:new Map})}var Pt=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done,zt=class extends st{constructor(t,n){super(t),Object.defineProperty(this,"schema",{value:n,configurable:!0,enumerable:!1,writable:!0})}clone(t){let n=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return t&&(n.schema=t),n.items=n.items.map(r=>T(r)||N(r)?r.clone(t):r),this.range&&(n.range=this.range.slice()),n}addIn(t,n){if(Pt(t))this.add(n);else{let[r,...o]=t,s=this.get(r,!0);if(L(s))s.addIn(o,n);else if(s===void 0&&this.schema)this.set(r,ln(this.schema,o,n));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${o}`)}}deleteIn(t){let[n,...r]=t;if(r.length===0)return this.delete(n);let o=this.get(n,!0);if(L(o))return o.deleteIn(r);throw new Error(`Expected YAML collection at ${n}. Remaining path: ${r}`)}getIn(t,n){let[r,...o]=t,s=this.get(r,!0);return o.length===0?!n&&$(s)?s.value:s:L(s)?s.getIn(o,n):void 0}hasAllNullValues(t){return this.items.every(n=>{if(!N(n))return!1;let r=n.value;return r==null||t&&$(r)&&r.value==null&&!r.commentBefore&&!r.comment&&!r.tag})}hasIn(t){let[n,...r]=t;if(r.length===0)return this.has(n);let o=this.get(n,!0);return L(o)?o.hasIn(r):!1}setIn(t,n){let[r,...o]=t;if(o.length===0)this.set(r,n);else{let s=this.get(r,!0);if(L(s))s.setIn(o,n);else if(s===void 0&&this.schema)this.set(r,ln(this.schema,o,n));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${o}`)}}};var Yu=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function me(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var Le=(e,t,n)=>e.endsWith(`
+`)?me(n,t):n.includes(`
+`)?`
+`+me(n,t):(e.endsWith(" ")?"":" ")+n;var Vo="flow",mr="block",fn="quoted";function dn(e,t,n="flow",{indentAtStart:r,lineWidth:o=80,minContentWidth:s=20,onFold:i,onOverflow:c}={}){if(!o||o<0)return e;o<s&&(s=0);let a=Math.max(1+s,1+o-t.length);if(e.length<=a)return e;let u=[],d={},l=o-t.length;typeof r=="number"&&(r>o-Math.max(2,s)?u.push(0):l=o-r);let f,p,y=!1,m=-1,h=-1,b=-1;n===mr&&(m=Xu(e,m,t.length),m!==-1&&(l=m+a));for(let x;x=e[m+=1];){if(n===fn&&x==="\\"){switch(h=m,e[m+1]){case"x":m+=3;break;case"u":m+=5;break;case"U":m+=9;break;default:m+=1}b=m}if(x===`
+`)n===mr&&(m=Xu(e,m,t.length)),l=m+t.length+a,f=void 0;else{if(x===" "&&p&&p!==" "&&p!==`
+`&&p!==" "){let w=e[m+1];w&&w!==" "&&w!==`
+`&&w!==" "&&(f=m)}if(m>=l)if(f)u.push(f),l=f+a,f=void 0;else if(n===fn){for(;p===" "||p===" ";)p=x,x=e[m+=1],y=!0;let w=m>b+1?m-2:h-1;if(d[w])return e;u.push(w),d[w]=!0,l=w+a,f=void 0}else y=!0}p=x}if(y&&c&&c(),u.length===0)return e;i&&i();let _=e.slice(0,u[0]);for(let x=0;x<u.length;++x){let w=u[x],S=u[x+1]||e.length;w===0?_=`
+${t}${e.slice(0,S)}`:(n===fn&&d[w]&&(_+=`${e[w]}\\`),_+=`
+${t}${e.slice(w+1,S)}`)}return _}function Xu(e,t,n){let r=t,o=t+1,s=e[o];for(;s===" "||s===" ";)if(t<o+n)s=e[++t];else{do s=e[++t];while(s&&s!==`
+`);r=t,o=t+1,s=e[o]}return r}var yr=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),gr=e=>/^(%|---|\.\.\.)/m.test(e);function nm(e,t,n){if(!t||t<0)return!1;let r=t-n,o=e.length;if(o<=r)return!1;for(let s=0,i=0;s<o;++s)if(e[s]===`
+`){if(s-i>r)return!0;if(i=s+1,o-i<=r)return!1}return!0}function pn(e,t){let n=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return n;let{implicitKey:r}=t,o=t.options.doubleQuotedMinMultiLineLength,s=t.indent||(gr(e)?" ":""),i="",c=0;for(let a=0,u=n[a];u;u=n[++a])if(u===" "&&n[a+1]==="\\"&&n[a+2]==="n"&&(i+=n.slice(c,a)+"\\ ",a+=1,c=a,u="\\"),u==="\\")switch(n[a+1]){case"u":{i+=n.slice(c,a);let d=n.substr(a+2,4);switch(d){case"0000":i+="\\0";break;case"0007":i+="\\a";break;case"000b":i+="\\v";break;case"001b":i+="\\e";break;case"0085":i+="\\N";break;case"00a0":i+="\\_";break;case"2028":i+="\\L";break;case"2029":i+="\\P";break;default:d.substr(0,2)==="00"?i+="\\x"+d.substr(2):i+=n.substr(a,6)}a+=5,c=a+1}break;case"n":if(r||n[a+2]==='"'||n.length<o)a+=1;else{for(i+=n.slice(c,a)+`
+
+`;n[a+2]==="\\"&&n[a+3]==="n"&&n[a+4]!=='"';)i+=`
+`,a+=2;i+=s,n[a+2]===" "&&(i+="\\"),a+=1,c=a+1}break;default:a+=1}return i=c?i+n.slice(c):n,r?i:dn(i,s,fn,yr(t,!1))}function Go(e,t){if(t.options.singleQuote===!1||t.implicitKey&&e.includes(`
+`)||/[ \t]\n|\n[ \t]/.test(e))return pn(e,t);let n=t.indent||(gr(e)?" ":""),r="'"+e.replace(/'/g,"''").replace(/\n+/g,`$&
+${n}`)+"'";return t.implicitKey?r:dn(r,n,Vo,yr(t,!1))}function Lt(e,t){let{singleQuote:n}=t.options,r;if(n===!1)r=pn;else{let o=e.includes('"'),s=e.includes("'");o&&!s?r=Go:s&&!o?r=pn:r=n?Go:pn}return r(e,t)}var qo;try{qo=new RegExp(`(^|(?<!
+))
++(?!
+|$)`,"g")}catch{qo=/\n+(?!\n|$)/g}function hr({comment:e,type:t,value:n},r,o,s){let{blockQuote:i,commentString:c,lineWidth:a}=r.options;if(!i||/\n[\t ]+$/.test(n))return Lt(n,r);let u=r.indent||(r.forceBlockIndent||gr(n)?" ":""),d=i==="literal"?!0:i==="folded"||t===A.BLOCK_FOLDED?!1:t===A.BLOCK_LITERAL?!0:!nm(n,a,u.length);if(!n)return d?`|
+`:`>
+`;let l,f;for(f=n.length;f>0;--f){let S=n[f-1];if(S!==`
+`&&S!==" "&&S!==" ")break}let p=n.substring(f),y=p.indexOf(`
+`);y===-1?l="-":n===p||y!==p.length-1?(l="+",s&&s()):l="",p&&(n=n.slice(0,-p.length),p[p.length-1]===`
+`&&(p=p.slice(0,-1)),p=p.replace(qo,`$&${u}`));let m=!1,h,b=-1;for(h=0;h<n.length;++h){let S=n[h];if(S===" ")m=!0;else if(S===`
+`)b=h;else break}let _=n.substring(0,b<h?b+1:h);_&&(n=n.substring(_.length),_=_.replace(/\n+/g,`$&${u}`));let w=(m?u?"2":"1":"")+l;if(e&&(w+=" "+c(e.replace(/ ?[\r\n]+/g," ")),o&&o()),!d){let S=n.replace(/\n+/g,`
+$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${u}`),v=!1,R=yr(r,!0);i!=="folded"&&t!==A.BLOCK_FOLDED&&(R.onOverflow=()=>{v=!0});let E=dn(`${_}${S}${p}`,u,mr,R);if(!v)return`>${w}
+${u}${E}`}return n=n.replace(/\n+/g,`$&${u}`),`|${w}
+${u}${_}${n}${p}`}function rm(e,t,n,r){let{type:o,value:s}=e,{actualString:i,implicitKey:c,indent:a,indentStep:u,inFlow:d}=t;if(c&&s.includes(`
+`)||d&&/[[\]{},]/.test(s))return Lt(s,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(s))return c||d||!s.includes(`
+`)?Lt(s,t):hr(e,t,n,r);if(!c&&!d&&o!==A.PLAIN&&s.includes(`
+`))return hr(e,t,n,r);if(gr(s)){if(a==="")return t.forceBlockIndent=!0,hr(e,t,n,r);if(c&&a===u)return Lt(s,t)}let l=s.replace(/\n+/g,`$&
+${a}`);if(i){let f=m=>m.default&&m.tag!=="tag:yaml.org,2002:str"&&m.test?.test(l),{compat:p,tags:y}=t.doc.schema;if(y.some(f)||p?.some(f))return Lt(s,t)}return c?l:dn(l,a,Vo,yr(t,!1))}function ht(e,t,n,r){let{implicitKey:o,inFlow:s}=t,i=typeof e.value=="string"?e:Object.assign({},e,{value:String(e.value)}),{type:c}=e;c!==A.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(i.value)&&(c=A.QUOTE_DOUBLE);let a=d=>{switch(d){case A.BLOCK_FOLDED:case A.BLOCK_LITERAL:return o||s?Lt(i.value,t):hr(i,t,n,r);case A.QUOTE_DOUBLE:return pn(i.value,t);case A.QUOTE_SINGLE:return Go(i.value,t);case A.PLAIN:return rm(i,t,n,r);default:return null}},u=a(c);if(u===null){let{defaultKeyType:d,defaultStringType:l}=t.options,f=o&&d||l;if(u=a(f),u===null)throw new Error(`Unsupported default string type ${f}`)}return u}function br(e,t){let n=Object.assign({blockQuote:!0,commentString:Yu,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},e.schema.toStringOptions,t),r;switch(n.collectionStyle){case"block":r=!1;break;case"flow":r=!0;break;default:r=null}return{anchors:new Set,doc:e,flowCollectionPadding:n.flowCollectionPadding?" ":"",indent:"",indentStep:typeof n.indent=="number"?" ".repeat(n.indent):" ",inFlow:r,options:n}}function om(e,t){if(t.tag){let o=e.filter(s=>s.tag===t.tag);if(o.length>0)return o.find(s=>s.format===t.format)??o[0]}let n,r;if($(t)){r=t.value;let o=e.filter(s=>s.identify?.(r));if(o.length>1){let s=o.filter(i=>i.test);s.length>0&&(o=s)}n=o.find(s=>s.format===t.format)??o.find(s=>!s.format)}else r=t,n=e.find(o=>o.nodeClass&&r instanceof o.nodeClass);if(!n){let o=r?.constructor?.name??(r===null?"null":typeof r);throw new Error(`Tag not resolved for ${o} value`)}return n}function sm(e,t,{anchors:n,doc:r}){if(!r.directives)return"";let o=[],s=($(e)||L(e))&&e.anchor;s&&fr(s)&&(n.add(s),o.push(`&${s}`));let i=e.tag??(t.default?null:t.tag);return i&&o.push(r.directives.tagString(i)),o.join(" ")}function Ve(e,t,n,r){if(N(e))return e.toString(t,n,r);if(be(e)){if(t.doc.directives)return e.toString(t);if(t.resolvedAliases?.has(e))throw new TypeError("Cannot stringify circular structure without alias nodes");t.resolvedAliases?t.resolvedAliases.add(e):t.resolvedAliases=new Set([e]),e=e.resolve(t.doc)}let o,s=T(e)?e:t.doc.createNode(e,{onTagObj:a=>o=a});o??(o=om(t.doc.schema.tags,s));let i=sm(s,o,t);i.length>0&&(t.indentAtStart=(t.indentAtStart??0)+i.length+1);let c=typeof o.stringify=="function"?o.stringify(s,t,n,r):$(s)?ht(s,t,n,r):s.toString(t,n,r);return i?$(s)||c[0]==="{"||c[0]==="["?`${i} ${c}`:`${i}
+${t.indent}${c}`:c}function Hu({key:e,value:t},n,r,o){let{allNullValues:s,doc:i,indent:c,indentStep:a,options:{commentString:u,indentSeq:d,simpleKeys:l}}=n,f=T(e)&&e.comment||null;if(l){if(f)throw new Error("With simple keys, key nodes cannot have comments");if(L(e)||!T(e)&&typeof e=="object"){let R="With simple keys, collection cannot be used as a key value";throw new Error(R)}}let p=!l&&(!e||f&&t==null&&!n.inFlow||L(e)||($(e)?e.type===A.BLOCK_FOLDED||e.type===A.BLOCK_LITERAL:typeof e=="object"));n=Object.assign({},n,{allNullValues:!1,implicitKey:!p&&(l||!s),indent:c+a});let y=!1,m=!1,h=Ve(e,n,()=>y=!0,()=>m=!0);if(!p&&!n.inFlow&&h.length>1024){if(l)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");p=!0}if(n.inFlow){if(s||t==null)return y&&r&&r(),h===""?"?":p?`? ${h}`:h}else if(s&&!l||t==null&&p)return h=`? ${h}`,f&&!y?h+=Le(h,n.indent,u(f)):m&&o&&o(),h;y&&(f=null),p?(f&&(h+=Le(h,n.indent,u(f))),h=`? ${h}
+${c}:`):(h=`${h}:`,f&&(h+=Le(h,n.indent,u(f))));let b,_,x;T(t)?(b=!!t.spaceBefore,_=t.commentBefore,x=t.comment):(b=!1,_=null,x=null,t&&typeof t=="object"&&(t=i.createNode(t))),n.implicitKey=!1,!p&&!f&&$(t)&&(n.indentAtStart=h.length+1),m=!1,!d&&a.length>=2&&!n.inFlow&&!p&&_e(t)&&!t.flow&&!t.tag&&!t.anchor&&(n.indent=n.indent.substring(2));let w=!1,S=Ve(t,n,()=>w=!0,()=>m=!0),v=" ";if(f||b||_){if(v=b?`
+`:"",_){let R=u(_);v+=`
+${me(R,n.indent)}`}S===""&&!n.inFlow?v===`
+`&&x&&(v=`
+
+`):v+=`
+${n.indent}`}else if(!p&&L(t)){let R=S[0],E=S.indexOf(`
+`),G=E!==-1,Ke=n.inFlow??t.flow??t.items.length===0;if(G||!Ke){let wt=!1;if(G&&(R==="&"||R==="!")){let q=S.indexOf(" ");R==="&"&&q!==-1&&q<E&&S[q+1]==="!"&&(q=S.indexOf(" ",q+1)),(q===-1||E<q)&&(wt=!0)}wt||(v=`
+${n.indent}`)}}else(S===""||S[0]===`
+`)&&(v="");return h+=v+S,n.inFlow?w&&r&&r():x&&!w?h+=Le(h,n.indent,u(x)):m&&o&&o(),h}function Ko(e,t){(e==="debug"||e==="warn")&&console.warn(t)}var wr="<<",xe={identify:e=>e===wr||typeof e=="symbol"&&e.description===wr,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new A(Symbol(wr)),{addToJSMap:Yo}),stringify:()=>wr},el=(e,t)=>(xe.identify(t)||$(t)&&(!t.type||t.type===A.PLAIN)&&xe.identify(t.value))&&e?.doc.schema.tags.some(n=>n.tag===xe.tag&&n.default);function Yo(e,t,n){let r=tl(e,n);if(_e(r))for(let o of r.items)Wo(e,t,o);else if(Array.isArray(r))for(let o of r)Wo(e,t,o);else Wo(e,t,r)}function Wo(e,t,n){let r=tl(e,n);if(!we(r))throw new Error("Merge sources must be maps or map aliases");let o=r.toJSON(null,e,Map);for(let[s,i]of o)t instanceof Map?t.has(s)||t.set(s,i):t instanceof Set?t.add(s):Object.prototype.hasOwnProperty.call(t,s)||Object.defineProperty(t,s,{value:i,writable:!0,enumerable:!0,configurable:!0});return t}function tl(e,t){return e&&be(t)?t.resolve(e.doc,e):t}function _r(e,t,{key:n,value:r}){if(T(n)&&n.addToJSMap)n.addToJSMap(e,t,r);else if(el(e,n))Yo(e,t,r);else{let o=K(n,"",e);if(t instanceof Map)t.set(o,K(r,o,e));else if(t instanceof Set)t.add(o);else{let s=im(n,o,e),i=K(r,s,e);s in t?Object.defineProperty(t,s,{value:i,writable:!0,enumerable:!0,configurable:!0}):t[s]=i}}return t}function im(e,t,n){if(t===null)return"";if(typeof t!="object")return String(t);if(T(e)&&n?.doc){let r=br(n.doc,{});r.anchors=new Set;for(let s of n.anchors.keys())r.anchors.add(s.anchor);r.inFlow=!0,r.inStringifyKey=!0;let o=e.toString(r);if(!n.mapKeyWarned){let s=JSON.stringify(o);s.length>40&&(s=s.substring(0,36)+'..."'),Ko(n.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${s}. Set mapAsMap: true to use object keys.`),n.mapKeyWarned=!0}return o}return JSON.stringify(t)}function Mt(e,t,n){let r=Je(e,void 0,n),o=Je(t,void 0,n);return new J(r,o)}var J=class e{constructor(t,n=null){Object.defineProperty(this,ne,{value:Uo}),this.key=t,this.value=n}clone(t){let{key:n,value:r}=this;return T(n)&&(n=n.clone(t)),T(r)&&(r=r.clone(t)),new e(n,r)}toJSON(t,n){let r=n?.mapAsMap?new Map:{};return _r(n,r,this)}toString(t,n,r){return t?.doc?Hu(this,t,n,r):JSON.stringify(this)}};function Er(e,t,n){return(t.inFlow??e.flow?am:cm)(e,t,n)}function cm({comment:e,items:t},n,{blockItemPrefix:r,flowChars:o,itemIndent:s,onChompKeep:i,onComment:c}){let{indent:a,options:{commentString:u}}=n,d=Object.assign({},n,{indent:s,type:null}),l=!1,f=[];for(let y=0;y<t.length;++y){let m=t[y],h=null;if(T(m))!l&&m.spaceBefore&&f.push(""),xr(n,f,m.commentBefore,l),m.comment&&(h=m.comment);else if(N(m)){let _=T(m.key)?m.key:null;_&&(!l&&_.spaceBefore&&f.push(""),xr(n,f,_.commentBefore,l))}l=!1;let b=Ve(m,d,()=>h=null,()=>l=!0);h&&(b+=Le(b,s,u(h))),l&&h&&(l=!1),f.push(r+b)}let p;if(f.length===0)p=o.start+o.end;else{p=f[0];for(let y=1;y<f.length;++y){let m=f[y];p+=m?`
+${a}${m}`:`
+`}}return e?(p+=`
+`+me(u(e),a),c&&c()):l&&i&&i(),p}function am({items:e},t,{flowChars:n,itemIndent:r}){let{indent:o,indentStep:s,flowCollectionPadding:i,options:{commentString:c}}=t;r+=s;let a=Object.assign({},t,{indent:r,inFlow:!0,type:null}),u=!1,d=0,l=[];for(let y=0;y<e.length;++y){let m=e[y],h=null;if(T(m))m.spaceBefore&&l.push(""),xr(t,l,m.commentBefore,!1),m.comment&&(h=m.comment);else if(N(m)){let _=T(m.key)?m.key:null;_&&(_.spaceBefore&&l.push(""),xr(t,l,_.commentBefore,!1),_.comment&&(u=!0));let x=T(m.value)?m.value:null;x?(x.comment&&(h=x.comment),x.commentBefore&&(u=!0)):m.value==null&&_?.comment&&(h=_.comment)}h&&(u=!0);let b=Ve(m,a,()=>h=null);u||(u=l.length>d||b.includes(`
+`)),y<e.length-1?b+=",":t.options.trailingComma&&(t.options.lineWidth>0&&(u||(u=l.reduce((_,x)=>_+x.length+2,2)+(b.length+2)>t.options.lineWidth)),u&&(b+=",")),h&&(b+=Le(b,r,c(h))),l.push(b),d=l.length}let{start:f,end:p}=n;if(l.length===0)return f+p;if(!u){let y=l.reduce((m,h)=>m+h.length+2,2);u=t.options.lineWidth>0&&y>t.options.lineWidth}if(u){let y=f;for(let m of l)y+=m?`
+${s}${o}${m}`:`
+`;return`${y}
+${o}${p}`}else return`${f}${i}${l.join(" ")}${i}${p}`}function xr({indent:e,options:{commentString:t}},n,r,o){if(r&&o&&(r=r.replace(/^\n+/,"")),r){let s=me(t(r),e);n.push(s.trimStart())}}function it(e,t){let n=$(t)?t.value:t;for(let r of e)if(N(r)&&(r.key===t||r.key===n||$(r.key)&&r.key.value===n))return r}var V=class extends zt{static get tagName(){return"tag:yaml.org,2002:map"}constructor(t){super(ge,t),this.items=[]}static from(t,n,r){let{keepUndefined:o,replacer:s}=r,i=new this(t),c=(a,u)=>{if(typeof s=="function")u=s.call(n,a,u);else if(Array.isArray(s)&&!s.includes(a))return;(u!==void 0||o)&&i.items.push(Mt(a,u,r))};if(n instanceof Map)for(let[a,u]of n)c(a,u);else if(n&&typeof n=="object")for(let a of Object.keys(n))c(a,n[a]);return typeof t.sortMapEntries=="function"&&i.items.sort(t.sortMapEntries),i}add(t,n){let r;N(t)?r=t:!t||typeof t!="object"||!("key"in t)?r=new J(t,t?.value):r=new J(t.key,t.value);let o=it(this.items,r.key),s=this.schema?.sortMapEntries;if(o){if(!n)throw new Error(`Key ${r.key} already set`);$(o.value)&&pr(r.value)?o.value.value=r.value:o.value=r.value}else if(s){let i=this.items.findIndex(c=>s(r,c)<0);i===-1?this.items.push(r):this.items.splice(i,0,r)}else this.items.push(r)}delete(t){let n=it(this.items,t);return n?this.items.splice(this.items.indexOf(n),1).length>0:!1}get(t,n){let o=it(this.items,t)?.value;return(!n&&$(o)?o.value:o)??void 0}has(t){return!!it(this.items,t)}set(t,n){this.add(new J(t,n),!0)}toJSON(t,n,r){let o=r?new r:n?.mapAsMap?new Map:{};n?.onCreate&&n.onCreate(o);for(let s of this.items)_r(n,o,s);return o}toString(t,n,r){if(!t)return JSON.stringify(this);for(let o of this.items)if(!N(o))throw new Error(`Map items must all be pairs; found ${JSON.stringify(o)} instead`);return!t.allNullValues&&this.hasAllNullValues(!1)&&(t=Object.assign({},t,{allNullValues:!0})),Er(this,t,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:t.indent||"",onChompKeep:r,onComment:n})}};var Ee={collection:"map",default:!0,nodeClass:V,tag:"tag:yaml.org,2002:map",resolve(e,t){return we(e)||t("Expected a mapping for this tag"),e},createNode:(e,t,n)=>V.from(e,t,n)};var X=class extends zt{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(t){super(Ue,t),this.items=[]}add(t){this.items.push(t)}delete(t){let n=Sr(t);return typeof n!="number"?!1:this.items.splice(n,1).length>0}get(t,n){let r=Sr(t);if(typeof r!="number")return;let o=this.items[r];return!n&&$(o)?o.value:o}has(t){let n=Sr(t);return typeof n=="number"&&n<this.items.length}set(t,n){let r=Sr(t);if(typeof r!="number")throw new Error(`Expected a valid index, not ${t}.`);let o=this.items[r];$(o)&&pr(n)?o.value=n:this.items[r]=n}toJSON(t,n){let r=[];n?.onCreate&&n.onCreate(r);let o=0;for(let s of this.items)r.push(K(s,String(o++),n));return r}toString(t,n,r){return t?Er(this,t,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(t.indent||"")+" ",onChompKeep:r,onComment:n}):JSON.stringify(this)}static from(t,n,r){let{replacer:o}=r,s=new this(t);if(n&&Symbol.iterator in Object(n)){let i=0;for(let c of n){if(typeof o=="function"){let a=n instanceof Set?c:String(i++);c=o.call(n,a,c)}s.items.push(Je(c,void 0,r))}}return s}};function Sr(e){let t=$(e)?e.value:e;return t&&typeof t=="string"&&(t=Number(t)),typeof t=="number"&&Number.isInteger(t)&&t>=0?t:null}var Se={collection:"seq",default:!0,nodeClass:X,tag:"tag:yaml.org,2002:seq",resolve(e,t){return _e(e)||t("Expected a sequence for this tag"),e},createNode:(e,t,n)=>X.from(e,t,n)};var ct={identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify(e,t,n,r){return t=Object.assign({actualString:!0},t),ht(e,t,n,r)}};var yt={identify:e=>e==null,createNode:()=>new A(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new A(null),stringify:({source:e},t)=>typeof e=="string"&&yt.test.test(e)?e:t.options.nullStr};var mn={identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new A(e[0]==="t"||e[0]==="T"),stringify({source:e,value:t},n){if(e&&mn.test.test(e)){let r=e[0]==="t"||e[0]==="T";if(t===r)return e}return t?n.options.trueStr:n.options.falseStr}};function H({format:e,minFractionDigits:t,tag:n,value:r}){if(typeof r=="bigint")return String(r);let o=typeof r=="number"?r:Number(r);if(!isFinite(o))return isNaN(o)?".nan":o<0?"-.inf":".inf";let s=Object.is(r,-0)?"-0":JSON.stringify(r);if(!e&&t&&(!n||n==="tag:yaml.org,2002:float")&&/^-?\d/.test(s)&&!s.includes("e")){let i=s.indexOf(".");i<0&&(i=s.length,s+=".");let c=t-(s.length-i-1);for(;c-- >0;)s+="0"}return s}var vr={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>e.slice(-3).toLowerCase()==="nan"?NaN:e[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:H},kr={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e),stringify(e){let t=Number(e.value);return isFinite(t)?t.toExponential():H(e)}},Ar={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(e){let t=new A(parseFloat(e)),n=e.indexOf(".");return n!==-1&&e[e.length-1]==="0"&&(t.minFractionDigits=e.length-n-1),t},stringify:H};var Dr=e=>typeof e=="bigint"||Number.isInteger(e),Xo=(e,t,n,{intAsBigInt:r})=>r?BigInt(e):parseInt(e.substring(t),n);function nl(e,t,n){let{value:r}=e;return Dr(r)&&r>=0?n+r.toString(t):H(e)}var Ir={identify:e=>Dr(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(e,t,n)=>Xo(e,2,8,n),stringify:e=>nl(e,8,"0o")},Or={identify:Dr,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(e,t,n)=>Xo(e,0,10,n),stringify:H},$r={identify:e=>Dr(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,n)=>Xo(e,2,16,n),stringify:e=>nl(e,16,"0x")};var rl=[Ee,Se,ct,yt,mn,Ir,Or,$r,vr,kr,Ar];function ol(e){return typeof e=="bigint"||Number.isInteger(e)}var Rr=({value:e})=>JSON.stringify(e),um=[{identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:Rr},{identify:e=>e==null,createNode:()=>new A(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:Rr},{identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:e=>e==="true",stringify:Rr},{identify:ol,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(e,t,{intAsBigInt:n})=>n?BigInt(e):parseInt(e,10),stringify:({value:e})=>ol(e)?e.toString():JSON.stringify(e)},{identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:e=>parseFloat(e),stringify:Rr}],lm={default:!0,tag:"",test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}},sl=[Ee,Se].concat(um,lm);var hn={identify:e=>e instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(e,t){if(typeof atob=="function"){let n=atob(e.replace(/[\n\r]/g,"")),r=new Uint8Array(n.length);for(let o=0;o<n.length;++o)r[o]=n.charCodeAt(o);return r}else return t("This environment does not support reading binary tags; either Buffer or atob is required"),e},stringify({comment:e,type:t,value:n},r,o,s){if(!n)return"";let i=n,c;if(typeof btoa=="function"){let a="";for(let u=0;u<i.length;++u)a+=String.fromCharCode(i[u]);c=btoa(a)}else throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required");if(t??(t=A.BLOCK_LITERAL),t!==A.QUOTE_DOUBLE){let a=Math.max(r.options.lineWidth-r.indent.length,r.options.minContentWidth),u=Math.ceil(c.length/a),d=new Array(u);for(let l=0,f=0;l<u;++l,f+=a)d[l]=c.substr(f,a);c=d.join(t===A.BLOCK_LITERAL?`
+`:" ")}return ht({comment:e,type:t,value:c},r,o,s)}};function Ho(e,t){if(_e(e))for(let n=0;n<e.items.length;++n){let r=e.items[n];if(!N(r)){if(we(r)){r.items.length>1&&t("Each pair must have its own sequence indicator");let o=r.items[0]||new J(new A(null));if(r.commentBefore&&(o.key.commentBefore=o.key.commentBefore?`${r.commentBefore}
+${o.key.commentBefore}`:r.commentBefore),r.comment){let s=o.value??o.key;s.comment=s.comment?`${r.comment}
+${s.comment}`:r.comment}r=o}e.items[n]=N(r)?r:new J(r)}}else t("Expected a sequence for this tag");return e}function es(e,t,n){let{replacer:r}=n,o=new X(e);o.tag="tag:yaml.org,2002:pairs";let s=0;if(t&&Symbol.iterator in Object(t))for(let i of t){typeof r=="function"&&(i=r.call(t,String(s++),i));let c,a;if(Array.isArray(i))if(i.length===2)c=i[0],a=i[1];else throw new TypeError(`Expected [key, value] tuple: ${i}`);else if(i&&i instanceof Object){let u=Object.keys(i);if(u.length===1)c=u[0],a=i[c];else throw new TypeError(`Expected tuple with one key, not ${u.length} keys`)}else c=i;o.items.push(Mt(c,a,n))}return o}var yn={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Ho,createNode:es};var Zt=class e extends X{constructor(){super(),this.add=V.prototype.add.bind(this),this.delete=V.prototype.delete.bind(this),this.get=V.prototype.get.bind(this),this.has=V.prototype.has.bind(this),this.set=V.prototype.set.bind(this),this.tag=e.tag}toJSON(t,n){if(!n)return super.toJSON(t);let r=new Map;n?.onCreate&&n.onCreate(r);for(let o of this.items){let s,i;if(N(o)?(s=K(o.key,"",n),i=K(o.value,s,n)):s=K(o,"",n),r.has(s))throw new Error("Ordered maps must not include duplicate keys");r.set(s,i)}return r}static from(t,n,r){let o=es(t,n,r),s=new this;return s.items=o.items,s}};Zt.tag="tag:yaml.org,2002:omap";var gn={collection:"seq",identify:e=>e instanceof Map,nodeClass:Zt,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let n=Ho(e,t),r=[];for(let{key:o}of n.items)$(o)&&(r.includes(o.value)?t(`Ordered maps must not include duplicate keys: ${o.value}`):r.push(o.value));return Object.assign(new Zt,n)},createNode:(e,t,n)=>Zt.from(e,t,n)};function il({value:e,source:t},n){return t&&(e?ts:ns).test.test(t)?t:e?n.options.trueStr:n.options.falseStr}var ts={identify:e=>e===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new A(!0),stringify:il},ns={identify:e=>e===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new A(!1),stringify:il};var cl={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>e.slice(-3).toLowerCase()==="nan"?NaN:e[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:H},al={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e.replace(/_/g,"")),stringify(e){let t=Number(e.value);return isFinite(t)?t.toExponential():H(e)}},ul={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(e){let t=new A(parseFloat(e.replace(/_/g,""))),n=e.indexOf(".");if(n!==-1){let r=e.substring(n+1).replace(/_/g,"");r[r.length-1]==="0"&&(t.minFractionDigits=r.length)}return t},stringify:H};var bn=e=>typeof e=="bigint"||Number.isInteger(e);function Nr(e,t,n,{intAsBigInt:r}){let o=e[0];if((o==="-"||o==="+")&&(t+=1),e=e.substring(t).replace(/_/g,""),r){switch(n){case 2:e=`0b${e}`;break;case 8:e=`0o${e}`;break;case 16:e=`0x${e}`;break}let i=BigInt(e);return o==="-"?BigInt(-1)*i:i}let s=parseInt(e,n);return o==="-"?-1*s:s}function rs(e,t,n){let{value:r}=e;if(bn(r)){let o=r.toString(t);return r<0?"-"+n+o.substr(1):n+o}return H(e)}var ll={identify:bn,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,n)=>Nr(e,2,2,n),stringify:e=>rs(e,2,"0b")},fl={identify:bn,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,n)=>Nr(e,1,8,n),stringify:e=>rs(e,8,"0")},dl={identify:bn,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,n)=>Nr(e,0,10,n),stringify:H},pl={identify:bn,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,n)=>Nr(e,2,16,n),stringify:e=>rs(e,16,"0x")};var Ft=class e extends V{constructor(t){super(t),this.tag=e.tag}add(t){let n;N(t)?n=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?n=new J(t.key,null):n=new J(t,null),it(this.items,n.key)||this.items.push(n)}get(t,n){let r=it(this.items,t);return!n&&N(r)?$(r.key)?r.key.value:r.key:r}set(t,n){if(typeof n!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof n}`);let r=it(this.items,t);r&&!n?this.items.splice(this.items.indexOf(r),1):!r&&n&&this.items.push(new J(t))}toJSON(t,n){return super.toJSON(t,n,Set)}toString(t,n,r){if(!t)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},t,{allNullValues:!0}),n,r);throw new Error("Set items must all have null values")}static from(t,n,r){let{replacer:o}=r,s=new this(t);if(n&&Symbol.iterator in Object(n))for(let i of n)typeof o=="function"&&(i=o.call(n,i,i)),s.items.push(Mt(i,null,r));return s}};Ft.tag="tag:yaml.org,2002:set";var wn={collection:"map",identify:e=>e instanceof Set,nodeClass:Ft,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,n)=>Ft.from(e,t,n),resolve(e,t){if(we(e)){if(e.hasAllNullValues(!0))return Object.assign(new Ft,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};function os(e,t){let n=e[0],r=n==="-"||n==="+"?e.substring(1):e,o=i=>t?BigInt(i):Number(i),s=r.replace(/_/g,"").split(":").reduce((i,c)=>i*o(60)+o(c),o(0));return n==="-"?o(-1)*s:s}function ml(e){let{value:t}=e,n=i=>i;if(typeof t=="bigint")n=i=>BigInt(i);else if(isNaN(t)||!isFinite(t))return H(e);let r="";t<0&&(r="-",t*=n(-1));let o=n(60),s=[t%o];return t<60?s.unshift(0):(t=(t-s[0])/o,s.unshift(t%o),t>=60&&(t=(t-s[0])/o,s.unshift(t))),r+s.map(i=>String(i).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var Cr={identify:e=>typeof e=="bigint"||Number.isInteger(e),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(e,t,{intAsBigInt:n})=>os(e,n),stringify:ml},Tr={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:e=>os(e,!1),stringify:ml},Bt={identify:e=>e instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(e){let t=e.match(Bt.test);if(!t)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,n,r,o,s,i,c]=t.map(Number),a=t[7]?Number((t[7]+"00").substr(1,3)):0,u=Date.UTC(n,r-1,o,s||0,i||0,c||0,a),d=t[8];if(d&&d!=="Z"){let l=os(d,!1);Math.abs(l)<30&&(l*=60),u-=6e4*l}return new Date(u)},stringify:({value:e})=>e?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};var ss=[Ee,Se,ct,yt,ts,ns,ll,fl,dl,pl,cl,al,ul,hn,xe,gn,yn,wn,Cr,Tr,Bt];var hl=new Map([["core",rl],["failsafe",[Ee,Se,ct]],["json",sl],["yaml11",ss],["yaml-1.1",ss]]),yl={binary:hn,bool:mn,float:Ar,floatExp:kr,floatNaN:vr,floatTime:Tr,int:Or,intHex:$r,intOct:Ir,intTime:Cr,map:Ee,merge:xe,null:yt,omap:gn,pairs:yn,seq:Se,set:wn,timestamp:Bt},gl={"tag:yaml.org,2002:binary":hn,"tag:yaml.org,2002:merge":xe,"tag:yaml.org,2002:omap":gn,"tag:yaml.org,2002:pairs":yn,"tag:yaml.org,2002:set":wn,"tag:yaml.org,2002:timestamp":Bt};function zr(e,t,n){let r=hl.get(t);if(r&&!e)return n&&!r.includes(xe)?r.concat(xe):r.slice();let o=r;if(!o)if(Array.isArray(e))o=[];else{let s=Array.from(hl.keys()).filter(i=>i!=="yaml11").map(i=>JSON.stringify(i)).join(", ");throw new Error(`Unknown schema "${t}"; use one of ${s} or define customTags array`)}if(Array.isArray(e))for(let s of e)o=o.concat(s);else typeof e=="function"&&(o=e(o.slice()));return n&&(o=o.concat(xe)),o.reduce((s,i)=>{let c=typeof i=="string"?yl[i]:i;if(!c){let a=JSON.stringify(i),u=Object.keys(yl).map(d=>JSON.stringify(d)).join(", ");throw new Error(`Unknown custom tag ${a}; use one of ${u}`)}return s.includes(c)||s.push(c),s},[])}var fm=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0,_n=class e{constructor({compat:t,customTags:n,merge:r,resolveKnownTags:o,schema:s,sortMapEntries:i,toStringDefaults:c}){this.compat=Array.isArray(t)?zr(t,"compat"):t?zr(null,t):null,this.name=typeof s=="string"&&s||"core",this.knownTags=o?gl:{},this.tags=zr(n,this.name,r),this.toStringOptions=c??null,Object.defineProperty(this,ge,{value:Ee}),Object.defineProperty(this,le,{value:ct}),Object.defineProperty(this,Ue,{value:Se}),this.sortMapEntries=typeof i=="function"?i:i===!0?fm:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};function bl(e,t){let n=[],r=t.directives===!0;if(t.directives!==!1&&e.directives){let a=e.directives.toString(e);a?(n.push(a),r=!0):e.directives.docStart&&(r=!0)}r&&n.push("---");let o=br(e,t),{commentString:s}=o.options;if(e.commentBefore){n.length!==1&&n.unshift("");let a=s(e.commentBefore);n.unshift(me(a,""))}let i=!1,c=null;if(e.contents){if(T(e.contents)){if(e.contents.spaceBefore&&r&&n.push(""),e.contents.commentBefore){let d=s(e.contents.commentBefore);n.push(me(d,""))}o.forceBlockIndent=!!e.comment,c=e.contents.comment}let a=c?void 0:()=>i=!0,u=Ve(e.contents,o,()=>c=null,a);c&&(u+=Le(u,"",s(c))),(u[0]==="|"||u[0]===">")&&n[n.length-1]==="---"?n[n.length-1]=`--- ${u}`:n.push(u)}else n.push(Ve(e.contents,o));if(e.directives?.docEnd)if(e.comment){let a=s(e.comment);a.includes(`
+`)?(n.push("..."),n.push(me(a,""))):n.push(`... ${a}`)}else n.push("...");else{let a=e.comment;a&&i&&(a=a.replace(/^\n+/,"")),a&&((!i||c)&&n[n.length-1]!==""&&n.push(""),n.push(me(s(a),"")))}return n.join(`
+`)+`
+`}var at=class e{constructor(t,n,r){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,ne,{value:ar});let o=null;typeof n=="function"||Array.isArray(n)?o=n:r===void 0&&n&&(r=n,n=void 0);let s=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},r);this.options=s;let{version:i}=s;r?._directives?(this.directives=r._directives.atDocument(),this.directives.yaml.explicit&&(i=this.directives.yaml.version)):this.directives=new Pe({version:i}),this.setSchema(i,r),this.contents=t===void 0?null:this.createNode(t,o,r)}clone(){let t=Object.create(e.prototype,{[ne]:{value:ar}});return t.commentBefore=this.commentBefore,t.comment=this.comment,t.errors=this.errors.slice(),t.warnings=this.warnings.slice(),t.options=Object.assign({},this.options),this.directives&&(t.directives=this.directives.clone()),t.schema=this.schema.clone(),t.contents=T(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(t){jt(this.contents)&&this.contents.add(t)}addIn(t,n){jt(this.contents)&&this.contents.addIn(t,n)}createAlias(t,n){if(!t.anchor){let r=Qo(this);t.anchor=!n||r.has(n)?Jo(n||"a",r):n}return new Qe(t.anchor)}createNode(t,n,r){let o;if(typeof n=="function")t=n.call({"":t},"",t),o=n;else if(Array.isArray(n)){let h=_=>typeof _=="number"||_ instanceof String||_ instanceof Number,b=n.filter(h).map(String);b.length>0&&(n=n.concat(b)),o=n}else r===void 0&&n&&(r=n,n=void 0);let{aliasDuplicateObjects:s,anchorPrefix:i,flow:c,keepUndefined:a,onTagObj:u,tag:d}=r??{},{onAnchor:l,setAnchors:f,sourceObjects:p}=Wu(this,i||"a"),y={aliasDuplicateObjects:s??!0,keepUndefined:a??!1,onAnchor:l,onTagObj:u,replacer:o,schema:this.schema,sourceObjects:p},m=Je(t,d,y);return c&&L(m)&&(m.flow=!0),f(),m}createPair(t,n,r={}){let o=this.createNode(t,null,r),s=this.createNode(n,null,r);return new J(o,s)}delete(t){return jt(this.contents)?this.contents.delete(t):!1}deleteIn(t){return Pt(t)?this.contents==null?!1:(this.contents=null,!0):jt(this.contents)?this.contents.deleteIn(t):!1}get(t,n){return L(this.contents)?this.contents.get(t,n):void 0}getIn(t,n){return Pt(t)?!n&&$(this.contents)?this.contents.value:this.contents:L(this.contents)?this.contents.getIn(t,n):void 0}has(t){return L(this.contents)?this.contents.has(t):!1}hasIn(t){return Pt(t)?this.contents!==void 0:L(this.contents)?this.contents.hasIn(t):!1}set(t,n){this.contents==null?this.contents=ln(this.schema,[t],n):jt(this.contents)&&this.contents.set(t,n)}setIn(t,n){Pt(t)?this.contents=n:this.contents==null?this.contents=ln(this.schema,Array.from(t),n):jt(this.contents)&&this.contents.setIn(t,n)}setSchema(t,n={}){typeof t=="number"&&(t=String(t));let r;switch(t){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new Pe({version:"1.1"}),r={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=t:this.directives=new Pe({version:t}),r={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,r=null;break;default:{let o=JSON.stringify(t);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${o}`)}}if(n.schema instanceof Object)this.schema=n.schema;else if(r)this.schema=new _n(Object.assign(r,n));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:t,jsonArg:n,mapAsMap:r,maxAliasCount:o,onAnchor:s,reviver:i}={}){let c={anchors:new Map,doc:this,keep:!t,mapAsMap:r===!0,mapKeyWarned:!1,maxAliasCount:typeof o=="number"?o:100},a=K(this.contents,n??"",c);if(typeof s=="function")for(let{count:u,res:d}of c.anchors.values())s(d,u);return typeof i=="function"?ot(i,{"":a},"",a):a}toJSON(t,n){return this.toJS({json:!0,jsonArg:t,mapAsMap:!1,onAnchor:n})}toString(t={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in t&&(!Number.isInteger(t.indent)||Number(t.indent)<=0)){let n=JSON.stringify(t.indent);throw new Error(`"indent" option must be a positive integer, not ${n}`)}return bl(this,t)}};function jt(e){if(L(e))return!0;throw new Error("Expected a YAML collection as document contents")}var xn=class extends Error{constructor(t,n,r,o){super(),this.name=t,this.code=r,this.message=o,this.pos=n}},ve=class extends xn{constructor(t,n,r){super("YAMLParseError",t,n,r)}},En=class extends xn{constructor(t,n,r){super("YAMLWarning",t,n,r)}},is=(e,t)=>n=>{if(n.pos[0]===-1)return;n.linePos=n.pos.map(c=>t.linePos(c));let{line:r,col:o}=n.linePos[0];n.message+=` at line ${r}, column ${o}`;let s=o-1,i=e.substring(t.lineStarts[r-1],t.lineStarts[r]).replace(/[\n\r]+$/,"");if(s>=60&&i.length>80){let c=Math.min(s-39,i.length-79);i="\u2026"+i.substring(c),s-=c-1}if(i.length>80&&(i=i.substring(0,79)+"\u2026"),r>1&&/^ *$/.test(i.substring(0,s))){let c=e.substring(t.lineStarts[r-2],t.lineStarts[r-1]);c.length>80&&(c=c.substring(0,79)+`\u2026
+`),i=c+i}if(/[^ ]/.test(i)){let c=1,a=n.linePos[1];a?.line===r&&a.col>o&&(c=Math.max(1,Math.min(a.col-o,80-s)));let u=" ".repeat(s)+"^".repeat(c);n.message+=`:
+
+${i}
+${u}
+`}};function Me(e,{flow:t,indicator:n,next:r,offset:o,onError:s,parentIndent:i,startOnNewline:c}){let a=!1,u=c,d=c,l="",f="",p=!1,y=!1,m=null,h=null,b=null,_=null,x=null,w=null,S=null;for(let E of e)switch(y&&(E.type!=="space"&&E.type!=="newline"&&E.type!=="comma"&&s(E.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),y=!1),m&&(u&&E.type!=="comment"&&E.type!=="newline"&&s(m,"TAB_AS_INDENT","Tabs are not allowed as indentation"),m=null),E.type){case"space":!t&&(n!=="doc-start"||r?.type!=="flow-collection")&&E.source.includes(" ")&&(m=E),d=!0;break;case"comment":{d||s(E,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let G=E.source.substring(1)||" ";l?l+=f+G:l=G,f="",u=!1;break}case"newline":u?l?l+=E.source:(!w||n!=="seq-item-ind")&&(a=!0):f+=E.source,u=!0,p=!0,(h||b)&&(_=E),d=!0;break;case"anchor":h&&s(E,"MULTIPLE_ANCHORS","A node can have at most one anchor"),E.source.endsWith(":")&&s(E.offset+E.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),h=E,S??(S=E.offset),u=!1,d=!1,y=!0;break;case"tag":{b&&s(E,"MULTIPLE_TAGS","A node can have at most one tag"),b=E,S??(S=E.offset),u=!1,d=!1,y=!0;break}case n:(h||b)&&s(E,"BAD_PROP_ORDER",`Anchors and tags must be after the ${E.source} indicator`),w&&s(E,"UNEXPECTED_TOKEN",`Unexpected ${E.source} in ${t??"collection"}`),w=E,u=n==="seq-item-ind"||n==="explicit-key-ind",d=!1;break;case"comma":if(t){x&&s(E,"UNEXPECTED_TOKEN",`Unexpected , in ${t}`),x=E,u=!1,d=!1;break}default:s(E,"UNEXPECTED_TOKEN",`Unexpected ${E.type} token`),u=!1,d=!1}let v=e[e.length-1],R=v?v.offset+v.source.length:o;return y&&r&&r.type!=="space"&&r.type!=="newline"&&r.type!=="comma"&&(r.type!=="scalar"||r.source!=="")&&s(r.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),m&&(u&&m.indent<=i||r?.type==="block-map"||r?.type==="block-seq")&&s(m,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:x,found:w,spaceBefore:a,comment:l,hasNewline:p,anchor:h,tag:b,newlineAfterProp:_,end:R,start:S??R}}function ut(e){if(!e)return null;switch(e.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(e.source.includes(`
+`))return!0;if(e.end){for(let t of e.end)if(t.type==="newline")return!0}return!1;case"flow-collection":for(let t of e.items){for(let n of t.start)if(n.type==="newline")return!0;if(t.sep){for(let n of t.sep)if(n.type==="newline")return!0}if(ut(t.key)||ut(t.value))return!0}return!1;default:return!0}}function Sn(e,t,n){if(t?.type==="flow-collection"){let r=t.end[0];r.indent===e&&(r.source==="]"||r.source==="}")&&ut(t)&&n(r,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}function Pr(e,t,n){let{uniqueKeys:r}=e.options;if(r===!1)return!1;let o=typeof r=="function"?r:(s,i)=>s===i||$(s)&&$(i)&&s.value===i.value;return t.some(s=>o(s.key,n))}var wl="All mapping items must start at the same column";function _l({composeNode:e,composeEmptyNode:t},n,r,o,s){let i=s?.nodeClass??V,c=new i(n.schema);n.atRoot&&(n.atRoot=!1);let a=r.offset,u=null;for(let d of r.items){let{start:l,key:f,sep:p,value:y}=d,m=Me(l,{indicator:"explicit-key-ind",next:f??p?.[0],offset:a,onError:o,parentIndent:r.indent,startOnNewline:!0}),h=!m.found;if(h){if(f&&(f.type==="block-seq"?o(a,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in f&&f.indent!==r.indent&&o(a,"BAD_INDENT",wl)),!m.anchor&&!m.tag&&!p){u=m.end,m.comment&&(c.comment?c.comment+=`
+`+m.comment:c.comment=m.comment);continue}(m.newlineAfterProp||ut(f))&&o(f??l[l.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else m.found?.indent!==r.indent&&o(a,"BAD_INDENT",wl);n.atKey=!0;let b=m.end,_=f?e(n,f,m,o):t(n,b,l,null,m,o);n.schema.compat&&Sn(r.indent,f,o),n.atKey=!1,Pr(n,c.items,_)&&o(b,"DUPLICATE_KEY","Map keys must be unique");let x=Me(p??[],{indicator:"map-value-ind",next:y,offset:_.range[2],onError:o,parentIndent:r.indent,startOnNewline:!f||f.type==="block-scalar"});if(a=x.end,x.found){h&&(y?.type==="block-map"&&!x.hasNewline&&o(a,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),n.options.strict&&m.start<x.found.offset-1024&&o(_.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));let w=y?e(n,y,x,o):t(n,a,p,null,x,o);n.schema.compat&&Sn(r.indent,y,o),a=w.range[2];let S=new J(_,w);n.options.keepSourceTokens&&(S.srcToken=d),c.items.push(S)}else{h&&o(_.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),x.comment&&(_.comment?_.comment+=`
+`+x.comment:_.comment=x.comment);let w=new J(_);n.options.keepSourceTokens&&(w.srcToken=d),c.items.push(w)}}return u&&u<a&&o(u,"IMPOSSIBLE","Map comment with trailing content"),c.range=[r.offset,a,u??a],c}function xl({composeNode:e,composeEmptyNode:t},n,r,o,s){let i=s?.nodeClass??X,c=new i(n.schema);n.atRoot&&(n.atRoot=!1),n.atKey&&(n.atKey=!1);let a=r.offset,u=null;for(let{start:d,value:l}of r.items){let f=Me(d,{indicator:"seq-item-ind",next:l,offset:a,onError:o,parentIndent:r.indent,startOnNewline:!0});if(!f.found)if(f.anchor||f.tag||l)l?.type==="block-seq"?o(f.end,"BAD_INDENT","All sequence items must start at the same column"):o(a,"MISSING_CHAR","Sequence item without - indicator");else{u=f.end,f.comment&&(c.comment=f.comment);continue}let p=l?e(n,l,f,o):t(n,f.end,d,null,f,o);n.schema.compat&&Sn(r.indent,l,o),a=p.range[2],c.items.push(p)}return c.range=[r.offset,a,u??a],c}function Ze(e,t,n,r){let o="";if(e){let s=!1,i="";for(let c of e){let{source:a,type:u}=c;switch(u){case"space":s=!0;break;case"comment":{n&&!s&&r(c,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let d=a.substring(1)||" ";o?o+=i+d:o=d,i="";break}case"newline":o&&(i+=a),s=!0;break;default:r(c,"UNEXPECTED_TOKEN",`Unexpected ${u} at node end`)}t+=a.length}}return{comment:o,offset:t}}var cs="Block collections are not allowed within flow collections",as=e=>e&&(e.type==="block-map"||e.type==="block-seq");function El({composeNode:e,composeEmptyNode:t},n,r,o,s){let i=r.start.source==="{",c=i?"flow map":"flow sequence",a=s?.nodeClass??(i?V:X),u=new a(n.schema);u.flow=!0;let d=n.atRoot;d&&(n.atRoot=!1),n.atKey&&(n.atKey=!1);let l=r.offset+r.start.source.length;for(let h=0;h<r.items.length;++h){let b=r.items[h],{start:_,key:x,sep:w,value:S}=b,v=Me(_,{flow:c,indicator:"explicit-key-ind",next:x??w?.[0],offset:l,onError:o,parentIndent:r.indent,startOnNewline:!1});if(!v.found){if(!v.anchor&&!v.tag&&!w&&!S){h===0&&v.comma?o(v.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${c}`):h<r.items.length-1&&o(v.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${c}`),v.comment&&(u.comment?u.comment+=`
+`+v.comment:u.comment=v.comment),l=v.end;continue}!i&&n.options.strict&&ut(x)&&o(x,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(h===0)v.comma&&o(v.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${c}`);else if(v.comma||o(v.start,"MISSING_CHAR",`Missing , between ${c} items`),v.comment){let R="";e:for(let E of _)switch(E.type){case"comma":case"space":break;case"comment":R=E.source.substring(1);break e;default:break e}if(R){let E=u.items[u.items.length-1];N(E)&&(E=E.value??E.key),E.comment?E.comment+=`
+`+R:E.comment=R,v.comment=v.comment.substring(R.length+1)}}if(!i&&!w&&!v.found){let R=S?e(n,S,v,o):t(n,v.end,w,null,v,o);u.items.push(R),l=R.range[2],as(S)&&o(R.range,"BLOCK_IN_FLOW",cs)}else{n.atKey=!0;let R=v.end,E=x?e(n,x,v,o):t(n,R,_,null,v,o);as(x)&&o(E.range,"BLOCK_IN_FLOW",cs),n.atKey=!1;let G=Me(w??[],{flow:c,indicator:"map-value-ind",next:S,offset:E.range[2],onError:o,parentIndent:r.indent,startOnNewline:!1});if(G.found){if(!i&&!v.found&&n.options.strict){if(w)for(let q of w){if(q===G.found)break;if(q.type==="newline"){o(q,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}v.start<G.found.offset-1024&&o(G.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else S&&("source"in S&&S.source?.[0]===":"?o(S,"MISSING_CHAR",`Missing space after : in ${c}`):o(G.start,"MISSING_CHAR",`Missing , or : between ${c} items`));let Ke=S?e(n,S,G,o):G.found?t(n,G.end,w,null,G,o):null;Ke?as(S)&&o(Ke.range,"BLOCK_IN_FLOW",cs):G.comment&&(E.comment?E.comment+=`
+`+G.comment:E.comment=G.comment);let wt=new J(E,Ke);if(n.options.keepSourceTokens&&(wt.srcToken=b),i){let q=u;Pr(n,q.items,E)&&o(R,"DUPLICATE_KEY","Map keys must be unique"),q.items.push(wt)}else{let q=new V(n.schema);q.flow=!0,q.items.push(wt);let Ss=(Ke??E).range;q.range=[E.range[0],Ss[1],Ss[2]],u.items.push(q)}l=Ke?Ke.range[2]:G.end}}let f=i?"}":"]",[p,...y]=r.end,m=l;if(p?.source===f)m=p.offset+p.source.length;else{let h=c[0].toUpperCase()+c.substring(1),b=d?`${h} must end with a ${f}`:`${h} in block collection must be sufficiently indented and end with a ${f}`;o(l,d?"MISSING_CHAR":"BAD_INDENT",b),p&&p.source.length!==1&&y.unshift(p)}if(y.length>0){let h=Ze(y,m,n.options.strict,o);h.comment&&(u.comment?u.comment+=`
+`+h.comment:u.comment=h.comment),u.range=[r.offset,m,h.offset]}else u.range=[r.offset,m,m];return u}function us(e,t,n,r,o,s){let i=n.type==="block-map"?_l(e,t,n,r,s):n.type==="block-seq"?xl(e,t,n,r,s):El(e,t,n,r,s),c=i.constructor;return o==="!"||o===c.tagName?(i.tag=c.tagName,i):(o&&(i.tag=o),i)}function Sl(e,t,n,r,o){let s=r.tag,i=s?t.directives.tagName(s.source,f=>o(s,"TAG_RESOLVE_FAILED",f)):null;if(n.type==="block-seq"){let{anchor:f,newlineAfterProp:p}=r,y=f&&s?f.offset>s.offset?f:s:f??s;y&&(!p||p.offset<y.offset)&&o(y,"MISSING_CHAR","Missing newline after block sequence props")}let c=n.type==="block-map"?"map":n.type==="block-seq"?"seq":n.start.source==="{"?"map":"seq";if(!s||!i||i==="!"||i===V.tagName&&c==="map"||i===X.tagName&&c==="seq")return us(e,t,n,o,i);let a=t.schema.tags.find(f=>f.tag===i&&f.collection===c);if(!a){let f=t.schema.knownTags[i];if(f?.collection===c)t.schema.tags.push(Object.assign({},f,{default:!1})),a=f;else return f?o(s,"BAD_COLLECTION_TYPE",`${f.tag} used for ${c} collection, but expects ${f.collection??"scalar"}`,!0):o(s,"TAG_RESOLVE_FAILED",`Unresolved tag: ${i}`,!0),us(e,t,n,o,i)}let u=us(e,t,n,o,i,a),d=a.resolve?.(u,f=>o(s,"TAG_RESOLVE_FAILED",f),t.options)??u,l=T(d)?d:new A(d);return l.range=u.range,l.tag=i,a?.format&&(l.format=a.format),l}function ls(e,t,n){let r=t.offset,o=dm(t,e.options.strict,n);if(!o)return{value:"",type:null,comment:"",range:[r,r,r]};let s=o.mode===">"?A.BLOCK_FOLDED:A.BLOCK_LITERAL,i=t.source?pm(t.source):[],c=i.length;for(let m=i.length-1;m>=0;--m){let h=i[m][1];if(h===""||h==="\r")c=m;else break}if(c===0){let m=o.chomp==="+"&&i.length>0?`
+`.repeat(Math.max(1,i.length-1)):"",h=r+o.length;return t.source&&(h+=t.source.length),{value:m,type:s,comment:o.comment,range:[r,h,h]}}let a=t.indent+o.indent,u=t.offset+o.length,d=0;for(let m=0;m<c;++m){let[h,b]=i[m];if(b===""||b==="\r")o.indent===0&&h.length>a&&(a=h.length);else{h.length<a&&n(u+h.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator"),o.indent===0&&(a=h.length),d=m,a===0&&!e.atRoot&&n(u,"BAD_INDENT","Block scalar values in collections must be indented");break}u+=h.length+b.length+1}for(let m=i.length-1;m>=c;--m)i[m][0].length>a&&(c=m+1);let l="",f="",p=!1;for(let m=0;m<d;++m)l+=i[m][0].slice(a)+`
+`;for(let m=d;m<c;++m){let[h,b]=i[m];u+=h.length+b.length+1;let _=b[b.length-1]==="\r";if(_&&(b=b.slice(0,-1)),b&&h.length<a){let w=`Block scalar lines must not be less indented than their ${o.indent?"explicit indentation indicator":"first line"}`;n(u-b.length-(_?2:1),"BAD_INDENT",w),h=""}s===A.BLOCK_LITERAL?(l+=f+h.slice(a)+b,f=`
+`):h.length>a||b[0]===" "?(f===" "?f=`
+`:!p&&f===`
+`&&(f=`
+
+`),l+=f+h.slice(a)+b,f=`
+`,p=!0):b===""?f===`
+`?l+=`
+`:f=`
+`:(l+=f+b,f=" ",p=!1)}switch(o.chomp){case"-":break;case"+":for(let m=c;m<i.length;++m)l+=`
+`+i[m][0].slice(a);l[l.length-1]!==`
+`&&(l+=`
+`);break;default:l+=`
+`}let y=r+o.length+t.source.length;return{value:l,type:s,comment:o.comment,range:[r,y,y]}}function dm({offset:e,props:t},n,r){if(t[0].type!=="block-scalar-header")return r(t[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:o}=t[0],s=o[0],i=0,c="",a=-1;for(let f=1;f<o.length;++f){let p=o[f];if(!c&&(p==="-"||p==="+"))c=p;else{let y=Number(p);!i&&y?i=y:a===-1&&(a=e+f)}}a!==-1&&r(a,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${o}`);let u=!1,d="",l=o.length;for(let f=1;f<t.length;++f){let p=t[f];switch(p.type){case"space":u=!0;case"newline":l+=p.source.length;break;case"comment":n&&!u&&r(p,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),l+=p.source.length,d=p.source.substring(1);break;case"error":r(p,"UNEXPECTED_TOKEN",p.message),l+=p.source.length;break;default:{let y=`Unexpected token in block scalar header: ${p.type}`;r(p,"UNEXPECTED_TOKEN",y);let m=p.source;m&&typeof m=="string"&&(l+=m.length)}}}return{mode:s,indent:i,chomp:c,comment:d,length:l}}function pm(e){let t=e.split(/\n( *)/),n=t[0],r=n.match(/^( *)/),s=[r?.[1]?[r[1],n.slice(r[1].length)]:["",n]];for(let i=1;i<t.length;i+=2)s.push([t[i],t[i+1]]);return s}function fs(e,t,n){let{offset:r,type:o,source:s,end:i}=e,c,a,u=(f,p,y)=>n(r+f,p,y);switch(o){case"scalar":c=A.PLAIN,a=mm(s,u);break;case"single-quoted-scalar":c=A.QUOTE_SINGLE,a=hm(s,u);break;case"double-quoted-scalar":c=A.QUOTE_DOUBLE,a=ym(s,u);break;default:return n(e,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${o}`),{value:"",type:null,comment:"",range:[r,r+s.length,r+s.length]}}let d=r+s.length,l=Ze(i,d,t,n);return{value:a,type:c,comment:l.comment,range:[r,d,l.offset]}}function mm(e,t){let n="";switch(e[0]){case" ":n="a tab character";break;case",":n="flow indicator character ,";break;case"%":n="directive indicator character %";break;case"|":case">":{n=`block scalar indicator ${e[0]}`;break}case"@":case"`":{n=`reserved character ${e[0]}`;break}}return n&&t(0,"BAD_SCALAR_START",`Plain value cannot start with ${n}`),vl(e)}function hm(e,t){return(e[e.length-1]!=="'"||e.length===1)&&t(e.length,"MISSING_CHAR","Missing closing 'quote"),vl(e.slice(1,-1)).replace(/''/g,"'")}function vl(e){let t,n;try{t=new RegExp(`(.*?)(?<![ ])[ ]*\r?
+`,"sy"),n=new RegExp(`[ ]*(.*?)(?:(?<![ ])[ ]*)?\r?
+`,"sy")}catch{t=/(.*?)[ \t]*\r?\n/sy,n=/[ \t]*(.*?)[ \t]*\r?\n/sy}let r=t.exec(e);if(!r)return e;let o=r[1],s=" ",i=t.lastIndex;for(n.lastIndex=i;r=n.exec(e);)r[1]===""?s===`
+`?o+=s:s=`
+`:(o+=s+r[1],s=" "),i=n.lastIndex;let c=/[ \t]*(.*)/sy;return c.lastIndex=i,r=c.exec(e),o+s+(r?.[1]??"")}function ym(e,t){let n="";for(let r=1;r<e.length-1;++r){let o=e[r];if(!(o==="\r"&&e[r+1]===`
+`))if(o===`
+`){let{fold:s,offset:i}=gm(e,r);n+=s,r=i}else if(o==="\\"){let s=e[++r],i=bm[s];if(i)n+=i;else if(s===`
+`)for(s=e[r+1];s===" "||s===" ";)s=e[++r+1];else if(s==="\r"&&e[r+1]===`
+`)for(s=e[++r+1];s===" "||s===" ";)s=e[++r+1];else if(s==="x"||s==="u"||s==="U"){let c=s==="x"?2:s==="u"?4:8;n+=wm(e,r+1,c,t),r+=c}else{let c=e.substr(r-1,2);t(r-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${c}`),n+=c}}else if(o===" "||o===" "){let s=r,i=e[r+1];for(;i===" "||i===" ";)i=e[++r+1];i!==`
+`&&!(i==="\r"&&e[r+2]===`
+`)&&(n+=r>s?e.slice(s,r+1):o)}else n+=o}return(e[e.length-1]!=='"'||e.length===1)&&t(e.length,"MISSING_CHAR",'Missing closing "quote'),n}function gm(e,t){let n="",r=e[t+1];for(;(r===" "||r===" "||r===`
+`||r==="\r")&&!(r==="\r"&&e[t+2]!==`
+`);)r===`
+`&&(n+=`
+`),t+=1,r=e[t+1];return n||(n=" "),{fold:n,offset:t}}var bm={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
+`,r:"\r",t:" ",v:"\v",N:"\x85",_:"\xA0",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function wm(e,t,n,r){let o=e.substr(t,n),i=o.length===n&&/^[0-9a-fA-F]+$/.test(o)?parseInt(o,16):NaN;try{return String.fromCodePoint(i)}catch{let c=e.substr(t-2,n+2);return r(t-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${c}`),c}}function ds(e,t,n,r){let{value:o,type:s,comment:i,range:c}=t.type==="block-scalar"?ls(e,t,r):fs(t,e.options.strict,r),a=n?e.directives.tagName(n.source,l=>r(n,"TAG_RESOLVE_FAILED",l)):null,u;e.options.stringKeys&&e.atKey?u=e.schema[le]:a?u=_m(e.schema,o,a,n,r):t.type==="scalar"?u=xm(e,o,t,r):u=e.schema[le];let d;try{let l=u.resolve(o,f=>r(n??t,"TAG_RESOLVE_FAILED",f),e.options);d=$(l)?l:new A(l)}catch(l){let f=l instanceof Error?l.message:String(l);r(n??t,"TAG_RESOLVE_FAILED",f),d=new A(o)}return d.range=c,d.source=o,s&&(d.type=s),a&&(d.tag=a),u.format&&(d.format=u.format),i&&(d.comment=i),d}function _m(e,t,n,r,o){if(n==="!")return e[le];let s=[];for(let c of e.tags)if(!c.collection&&c.tag===n)if(c.default&&c.test)s.push(c);else return c;for(let c of s)if(c.test?.test(t))return c;let i=e.knownTags[n];return i&&!i.collection?(e.tags.push(Object.assign({},i,{default:!1,test:void 0})),i):(o(r,"TAG_RESOLVE_FAILED",`Unresolved tag: ${n}`,n!=="tag:yaml.org,2002:str"),e[le])}function xm({atKey:e,directives:t,schema:n},r,o,s){let i=n.tags.find(c=>(c.default===!0||e&&c.default==="key")&&c.test?.test(r))||n[le];if(n.compat){let c=n.compat.find(a=>a.default&&a.test?.test(r))??n[le];if(i.tag!==c.tag){let a=t.tagString(i.tag),u=t.tagString(c.tag),d=`Value may be parsed as either ${a} or ${u}`;s(o,"TAG_RESOLVE_FAILED",d,!0)}}return i}function kl(e,t,n){if(t){n??(n=t.length);for(let r=n-1;r>=0;--r){let o=t[r];switch(o.type){case"space":case"comment":case"newline":e-=o.source.length;continue}for(o=t[++r];o?.type==="space";)e+=o.source.length,o=t[++r];break}}return e}var Em={composeNode:ps,composeEmptyNode:Lr};function ps(e,t,n,r){let o=e.atKey,{spaceBefore:s,comment:i,anchor:c,tag:a}=n,u,d=!0;switch(t.type){case"alias":u=Sm(e,t,r),(c||a)&&r(t,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":u=ds(e,t,a,r),c&&(u.anchor=c.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{u=Sl(Em,e,t,n,r),c&&(u.anchor=c.source.substring(1))}catch(l){let f=l instanceof Error?l.message:String(l);r(t,"RESOURCE_EXHAUSTION",f)}break;default:{let l=t.type==="error"?t.message:`Unsupported token (type: ${t.type})`;r(t,"UNEXPECTED_TOKEN",l),d=!1}}return u??(u=Lr(e,t.offset,void 0,null,n,r)),c&&u.anchor===""&&r(c,"BAD_ALIAS","Anchor cannot be an empty string"),o&&e.options.stringKeys&&(!$(u)||typeof u.value!="string"||u.tag&&u.tag!=="tag:yaml.org,2002:str")&&r(a??t,"NON_STRING_KEY","With stringKeys, all keys must be strings"),s&&(u.spaceBefore=!0),i&&(t.type==="scalar"&&t.source===""?u.comment=i:u.commentBefore=i),e.options.keepSourceTokens&&d&&(u.srcToken=t),u}function Lr(e,t,n,r,{spaceBefore:o,comment:s,anchor:i,tag:c,end:a},u){let d={type:"scalar",offset:kl(t,n,r),indent:-1,source:""},l=ds(e,d,c,u);return i&&(l.anchor=i.source.substring(1),l.anchor===""&&u(i,"BAD_ALIAS","Anchor cannot be an empty string")),o&&(l.spaceBefore=!0),s&&(l.comment=s,l.range[2]=a),l}function Sm({options:e},{offset:t,source:n,end:r},o){let s=new Qe(n.substring(1));s.source===""&&o(t,"BAD_ALIAS","Alias cannot be an empty string"),s.source.endsWith(":")&&o(t+n.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let i=t+n.length,c=Ze(r,i,e.strict,o);return s.range=[t,i,c.offset],c.comment&&(s.comment=c.comment),s}function Al(e,t,{offset:n,start:r,value:o,end:s},i){let c=Object.assign({_directives:t},e),a=new at(void 0,c),u={atKey:!1,atRoot:!0,directives:a.directives,options:a.options,schema:a.schema},d=Me(r,{indicator:"doc-start",next:o??s?.[0],offset:n,onError:i,parentIndent:0,startOnNewline:!0});d.found&&(a.directives.docStart=!0,o&&(o.type==="block-map"||o.type==="block-seq")&&!d.hasNewline&&i(d.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),a.contents=o?ps(u,o,d,i):Lr(u,d.end,r,null,d,i);let l=a.contents.range[2],f=Ze(s,l,!1,i);return f.comment&&(a.comment=f.comment),a.range=[n,l,f.offset],a}function vn(e){if(typeof e=="number")return[e,e+1];if(Array.isArray(e))return e.length===2?e:[e[0],e[1]];let{offset:t,source:n}=e;return[t,t+(typeof n=="string"?n.length:1)]}function Dl(e){let t="",n=!1,r=!1;for(let o=0;o<e.length;++o){let s=e[o];switch(s[0]){case"#":t+=(t===""?"":r?`
+
+`:`
+`)+(s.substring(1)||" "),n=!0,r=!1;break;case"%":e[o+1]?.[0]!=="#"&&(o+=1),n=!1;break;default:n||(r=!0),n=!1}}return{comment:t,afterEmptyLine:r}}var kn=class{constructor(t={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(n,r,o,s)=>{let i=vn(n);s?this.warnings.push(new En(i,r,o)):this.errors.push(new ve(i,r,o))},this.directives=new Pe({version:t.version||"1.2"}),this.options=t}decorate(t,n){let{comment:r,afterEmptyLine:o}=Dl(this.prelude);if(r){let s=t.contents;if(n)t.comment=t.comment?`${t.comment}
+${r}`:r;else if(o||t.directives.docStart||!s)t.commentBefore=r;else if(L(s)&&!s.flow&&s.items.length>0){let i=s.items[0];N(i)&&(i=i.key);let c=i.commentBefore;i.commentBefore=c?`${r}
+${c}`:r}else{let i=s.commentBefore;s.commentBefore=i?`${r}
+${i}`:r}}if(n){for(let s=0;s<this.errors.length;++s)t.errors.push(this.errors[s]);for(let s=0;s<this.warnings.length;++s)t.warnings.push(this.warnings[s])}else t.errors=this.errors,t.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:Dl(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(t,n=!1,r=-1){for(let o of t)yield*this.next(o);yield*this.end(n,r)}*next(t){switch(t.type){case"directive":this.directives.add(t.source,(n,r,o)=>{let s=vn(t);s[0]+=n,this.onError(s,"BAD_DIRECTIVE",r,o)}),this.prelude.push(t.source),this.atDirectives=!0;break;case"document":{let n=Al(this.options,this.directives,t,this.onError);this.atDirectives&&!n.directives.docStart&&this.onError(t,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(n,!1),this.doc&&(yield this.doc),this.doc=n,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(t.source);break;case"error":{let n=t.source?`${t.message}: ${JSON.stringify(t.source)}`:t.message,r=new ve(vn(t),"UNEXPECTED_TOKEN",n);this.atDirectives||!this.doc?this.errors.push(r):this.doc.errors.push(r);break}case"doc-end":{if(!this.doc){let r="Unexpected doc-end without preceding document";this.errors.push(new ve(vn(t),"UNEXPECTED_TOKEN",r));break}this.doc.directives.docEnd=!0;let n=Ze(t.end,t.offset+t.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),n.comment){let r=this.doc.comment;this.doc.comment=r?`${r}
+${n.comment}`:n.comment}this.doc.range[2]=n.offset;break}default:this.errors.push(new ve(vn(t),"UNEXPECTED_TOKEN",`Unsupported token ${t.type}`))}}*end(t=!1,n=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(t){let r=Object.assign({_directives:this.directives},this.options),o=new at(void 0,r);this.atDirectives&&this.onError(n,"MISSING_CHAR","Missing directives-end indicator line"),o.range=[0,n,n],this.decorate(o,!1),yield o}}};var ms=Symbol("break visit"),vm=Symbol("skip children"),Il=Symbol("remove item");function gt(e,t){"type"in e&&e.type==="document"&&(e={start:e.start,value:e.value}),Ol(Object.freeze([]),e,t)}gt.BREAK=ms;gt.SKIP=vm;gt.REMOVE=Il;gt.itemAtPath=(e,t)=>{let n=e;for(let[r,o]of t){let s=n?.[r];if(s&&"items"in s)n=s.items[o];else return}return n};gt.parentCollection=(e,t)=>{let n=gt.itemAtPath(e,t.slice(0,-1)),r=t[t.length-1][0],o=n?.[r];if(o&&"items"in o)return o;throw new Error("Parent collection not found")};function Ol(e,t,n){let r=n(t,e);if(typeof r=="symbol")return r;for(let o of["key","value"]){let s=t[o];if(s&&"items"in s){for(let i=0;i<s.items.length;++i){let c=Ol(Object.freeze(e.concat([[o,i]])),s.items[i],n);if(typeof c=="number")i=c-1;else{if(c===ms)return ms;c===Il&&(s.items.splice(i,1),i-=1)}}typeof r=="function"&&o==="key"&&(r=r(t,e))}}return typeof r=="function"?r(t,e):r}var hs="\uFEFF",ys="",gs="",Mr="";function $l(e){switch(e){case hs:return"byte-order-mark";case ys:return"doc-mode";case gs:return"flow-error-end";case Mr:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case`
+`:case`\r
+`:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(e[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}function ke(e){switch(e){case void 0:case" ":case`
+`:case"\r":case" ":return!0;default:return!1}}var Rl=new Set("0123456789ABCDEFabcdef"),Am=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),Zr=new Set(",[]{}"),Dm=new Set(` ,[]{}
+\r `),bs=e=>!e||Dm.has(e),An=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(t,n=!1){if(t){if(typeof t!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+t:t,this.lineEndPos=null}this.atEnd=!n;let r=this.next??"stream";for(;r&&(n||this.hasChars(1));)r=yield*this.parseNext(r)}atLineEnd(){let t=this.pos,n=this.buffer[t];for(;n===" "||n===" ";)n=this.buffer[++t];return!n||n==="#"||n===`
+`?!0:n==="\r"?this.buffer[t+1]===`
+`:!1}charAt(t){return this.buffer[this.pos+t]}continueScalar(t){let n=this.buffer[t];if(this.indentNext>0){let r=0;for(;n===" ";)n=this.buffer[++r+t];if(n==="\r"){let o=this.buffer[r+t+1];if(o===`
+`||!o&&!this.atEnd)return t+r+1}return n===`
+`||r>=this.indentNext||!n&&!this.atEnd?t+r:-1}if(n==="-"||n==="."){let r=this.buffer.substr(t,3);if((r==="---"||r==="...")&&ke(this.buffer[t+3]))return-1}return t}getLine(){let t=this.lineEndPos;return(typeof t!="number"||t!==-1&&t<this.pos)&&(t=this.buffer.indexOf(`
+`,this.pos),this.lineEndPos=t),t===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[t-1]==="\r"&&(t-=1),this.buffer.substring(this.pos,t))}hasChars(t){return this.pos+t<=this.buffer.length}setNext(t){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=t,null}peek(t){return this.buffer.substr(this.pos,t)}*parseNext(t){switch(t){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let t=this.getLine();if(t===null)return this.setNext("stream");if(t[0]===hs&&(yield*this.pushCount(1),t=t.substring(1)),t[0]==="%"){let n=t.length,r=t.indexOf("#");for(;r!==-1;){let s=t[r-1];if(s===" "||s===" "){n=r-1;break}else r=t.indexOf("#",r+1)}for(;;){let s=t[n-1];if(s===" "||s===" ")n-=1;else break}let o=(yield*this.pushCount(n))+(yield*this.pushSpaces(!0));return yield*this.pushCount(t.length-o),this.pushNewline(),"stream"}if(this.atLineEnd()){let n=yield*this.pushSpaces(!0);return yield*this.pushCount(t.length-n),yield*this.pushNewline(),"stream"}return yield ys,yield*this.parseLineStart()}*parseLineStart(){let t=this.charAt(0);if(!t&&!this.atEnd)return this.setNext("line-start");if(t==="-"||t==="."){if(!this.atEnd&&!this.hasChars(4))return this.setNext("line-start");let n=this.peek(3);if((n==="---"||n==="...")&&ke(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,n==="---"?"doc":"stream"}return this.indentValue=yield*this.pushSpaces(!1),this.indentNext>this.indentValue&&!ke(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[t,n]=this.peek(2);if(!n&&!this.atEnd)return this.setNext("block-start");if((t==="-"||t==="?"||t===":")&&ke(n)){let r=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=r,"block-start"}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let t=this.getLine();if(t===null)return this.setNext("doc");let n=yield*this.pushIndicators();switch(t[n]){case"#":yield*this.pushCount(t.length-n);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil(bs),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return n+=yield*this.parseBlockScalarHeader(),n+=yield*this.pushSpaces(!0),yield*this.pushCount(t.length-n),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let t,n,r=-1;do t=yield*this.pushNewline(),t>0?(n=yield*this.pushSpaces(!1),this.indentValue=r=n):n=0,n+=yield*this.pushSpaces(!0);while(t+n>0);let o=this.getLine();if(o===null)return this.setNext("flow");if((r!==-1&&r<this.indentNext&&o[0]!=="#"||r===0&&(o.startsWith("---")||o.startsWith("..."))&&ke(o[3]))&&!(r===this.indentNext-1&&this.flowLevel===1&&(o[0]==="]"||o[0]==="}")))return this.flowLevel=0,yield gs,yield*this.parseLineStart();let s=0;for(;o[s]===",";)s+=yield*this.pushCount(1),s+=yield*this.pushSpaces(!0),this.flowKey=!1;switch(s+=yield*this.pushIndicators(),o[s]){case void 0:return"flow";case"#":return yield*this.pushCount(o.length-s),"flow";case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel+=1,"flow";case"}":case"]":return yield*this.pushCount(1),this.flowKey=!0,this.flowLevel-=1,this.flowLevel?"flow":"doc";case"*":return yield*this.pushUntil(bs),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let i=this.charAt(1);if(this.flowKey||ke(i)||i===",")return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),"flow"}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){let t=this.charAt(0),n=this.buffer.indexOf(t,this.pos+1);if(t==="'")for(;n!==-1&&this.buffer[n+1]==="'";)n=this.buffer.indexOf("'",n+2);else for(;n!==-1;){let s=0;for(;this.buffer[n-1-s]==="\\";)s+=1;if(s%2===0)break;n=this.buffer.indexOf('"',n+1)}let r=this.buffer.substring(0,n),o=r.indexOf(`
+`,this.pos);if(o!==-1){for(;o!==-1;){let s=this.continueScalar(o+1);if(s===-1)break;o=r.indexOf(`
+`,s)}o!==-1&&(n=o-(r[o-1]==="\r"?2:1))}if(n===-1){if(!this.atEnd)return this.setNext("quoted-scalar");n=this.buffer.length}return yield*this.pushToIndex(n+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let t=this.pos;for(;;){let n=this.buffer[++t];if(n==="+")this.blockScalarKeep=!0;else if(n>"0"&&n<="9")this.blockScalarIndent=Number(n)-1;else if(n!=="-")break}return yield*this.pushUntil(n=>ke(n)||n==="#")}*parseBlockScalar(){let t=this.pos-1,n=0,r;e:for(let s=this.pos;r=this.buffer[s];++s)switch(r){case" ":n+=1;break;case`
+`:t=s,n=0;break;case"\r":{let i=this.buffer[s+1];if(!i&&!this.atEnd)return this.setNext("block-scalar");if(i===`
+`)break}default:break e}if(!r&&!this.atEnd)return this.setNext("block-scalar");if(n>=this.indentNext){this.blockScalarIndent===-1?this.indentNext=n:this.indentNext=this.blockScalarIndent+(this.indentNext===0?1:this.indentNext);do{let s=this.continueScalar(t+1);if(s===-1)break;t=this.buffer.indexOf(`
+`,s)}while(t!==-1);if(t===-1){if(!this.atEnd)return this.setNext("block-scalar");t=this.buffer.length}}let o=t+1;for(r=this.buffer[o];r===" ";)r=this.buffer[++o];if(r===" "){for(;r===" "||r===" "||r==="\r"||r===`
+`;)r=this.buffer[++o];t=o-1}else if(!this.blockScalarKeep)do{let s=t-1,i=this.buffer[s];i==="\r"&&(i=this.buffer[--s]);let c=s;for(;i===" ";)i=this.buffer[--s];if(i===`
+`&&s>=this.pos&&s+1+n>c)t=s;else break}while(!0);return yield Mr,yield*this.pushToIndex(t+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let t=this.flowLevel>0,n=this.pos-1,r=this.pos-1,o;for(;o=this.buffer[++r];)if(o===":"){let s=this.buffer[r+1];if(ke(s)||t&&Zr.has(s))break;n=r}else if(ke(o)){let s=this.buffer[r+1];if(o==="\r"&&(s===`
+`?(r+=1,o=`
+`,s=this.buffer[r+1]):n=r),s==="#"||t&&Zr.has(s))break;if(o===`
+`){let i=this.continueScalar(r+1);if(i===-1)break;r=Math.max(r,i-2)}}else{if(t&&Zr.has(o))break;n=r}return!o&&!this.atEnd?this.setNext("plain-scalar"):(yield Mr,yield*this.pushToIndex(n+1,!0),t?"flow":"doc")}*pushCount(t){return t>0?(yield this.buffer.substr(this.pos,t),this.pos+=t,t):0}*pushToIndex(t,n){let r=this.buffer.slice(this.pos,t);return r?(yield r,this.pos+=r.length,r.length):(n&&(yield""),0)}*pushIndicators(){let t=0;e:for(;;){switch(this.charAt(0)){case"!":t+=yield*this.pushTag(),t+=yield*this.pushSpaces(!0);continue e;case"&":t+=yield*this.pushUntil(bs),t+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let n=this.flowLevel>0,r=this.charAt(1);if(ke(r)||n&&Zr.has(r)){n?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,t+=yield*this.pushCount(1),t+=yield*this.pushSpaces(!0);continue e}}}break e}return t}*pushTag(){if(this.charAt(1)==="<"){let t=this.pos+2,n=this.buffer[t];for(;!ke(n)&&n!==">";)n=this.buffer[++t];return yield*this.pushToIndex(n===">"?t+1:t,!1)}else{let t=this.pos+1,n=this.buffer[t];for(;n;)if(Am.has(n))n=this.buffer[++t];else if(n==="%"&&Rl.has(this.buffer[t+1])&&Rl.has(this.buffer[t+2]))n=this.buffer[t+=3];else break;return yield*this.pushToIndex(t,!1)}}*pushNewline(){let t=this.buffer[this.pos];return t===`
+`?yield*this.pushCount(1):t==="\r"&&this.charAt(1)===`
+`?yield*this.pushCount(2):0}*pushSpaces(t){let n=this.pos-1,r;do r=this.buffer[++n];while(r===" "||t&&r===" ");let o=n-this.pos;return o>0&&(yield this.buffer.substr(this.pos,o),this.pos=n),o}*pushUntil(t){let n=this.pos,r=this.buffer[n];for(;!t(r);)r=this.buffer[++n];return yield*this.pushToIndex(n,!1)}};var Dn=class{constructor(){this.lineStarts=[],this.addNewLine=t=>this.lineStarts.push(t),this.linePos=t=>{let n=0,r=this.lineStarts.length;for(;n<r;){let s=n+r>>1;this.lineStarts[s]<t?n=s+1:r=s}if(this.lineStarts[n]===t)return{line:n+1,col:1};if(n===0)return{line:0,col:t};let o=this.lineStarts[n-1];return{line:n,col:t-o+1}}}};function lt(e,t){for(let n=0;n<e.length;++n)if(e[n].type===t)return!0;return!1}function Nl(e){for(let t=0;t<e.length;++t)switch(e[t].type){case"space":case"comment":case"newline":break;default:return t}return-1}function Tl(e){switch(e?.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"flow-collection":return!0;default:return!1}}function Fr(e){switch(e.type){case"document":return e.start;case"block-map":{let t=e.items[e.items.length-1];return t.sep??t.start}case"block-seq":return e.items[e.items.length-1].start;default:return[]}}function Ut(e){if(e.length===0)return[];let t=e.length;e:for(;--t>=0;)switch(e[t].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}for(;e[++t]?.type==="space";);return e.splice(t,e.length)}function Br(e,t){if(t.length<1e5)Array.prototype.push.apply(e,t);else for(let n=0;n<t.length;++n)e.push(t[n])}function Cl(e){if(e.start.type==="flow-seq-start")for(let t of e.items)t.sep&&!t.value&&!lt(t.start,"explicit-key-ind")&&!lt(t.sep,"map-value-ind")&&(t.key&&(t.value=t.key),delete t.key,Tl(t.value)?t.value.end?Br(t.value.end,t.sep):t.value.end=t.sep:Br(t.start,t.sep),delete t.sep)}var In=class{constructor(t){this.atNewLine=!0,this.atScalar=!1,this.indent=0,this.offset=0,this.onKeyLine=!1,this.stack=[],this.source="",this.type="",this.lexer=new An,this.onNewLine=t}*parse(t,n=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(let r of this.lexer.lex(t,n))yield*this.next(r);n||(yield*this.end())}*next(t){if(this.source=t,this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=t.length;return}let n=$l(t);if(n)if(n==="scalar")this.atNewLine=!1,this.atScalar=!0,this.type="scalar";else{switch(this.type=n,yield*this.step(),n){case"newline":this.atNewLine=!0,this.indent=0,this.onNewLine&&this.onNewLine(this.offset+t.length);break;case"space":this.atNewLine&&t[0]===" "&&(this.indent+=t.length);break;case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":this.atNewLine&&(this.indent+=t.length);break;case"doc-mode":case"flow-error-end":return;default:this.atNewLine=!1}this.offset+=t.length}else{let r=`Not a YAML token: ${t}`;yield*this.pop({type:"error",offset:this.offset,message:r,source:t}),this.offset+=t.length}}*end(){for(;this.stack.length>0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let t=this.peek(1);if(this.type==="doc-end"&&t?.type!=="doc-end"){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!t)return yield*this.stream();switch(t.type){case"document":return yield*this.document(t);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(t);case"block-scalar":return yield*this.blockScalar(t);case"block-map":return yield*this.blockMap(t);case"block-seq":return yield*this.blockSequence(t);case"flow-collection":return yield*this.flowCollection(t);case"doc-end":return yield*this.documentEnd(t)}yield*this.pop()}peek(t){return this.stack[this.stack.length-t]}*pop(t){let n=t??this.stack.pop();if(!n)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield n;else{let r=this.peek(1);switch(n.type==="block-scalar"?n.indent="indent"in r?r.indent:0:n.type==="flow-collection"&&r.type==="document"&&(n.indent=0),n.type==="flow-collection"&&Cl(n),r.type){case"document":r.value=n;break;case"block-scalar":r.props.push(n);break;case"block-map":{let o=r.items[r.items.length-1];if(o.value){r.items.push({start:[],key:n,sep:[]}),this.onKeyLine=!0;return}else if(o.sep)o.value=n;else{Object.assign(o,{key:n,sep:[]}),this.onKeyLine=!o.explicitKey;return}break}case"block-seq":{let o=r.items[r.items.length-1];o.value?r.items.push({start:[],value:n}):o.value=n;break}case"flow-collection":{let o=r.items[r.items.length-1];!o||o.value?r.items.push({start:[],key:n,sep:[]}):o.sep?o.value=n:Object.assign(o,{key:n,sep:[]});return}default:yield*this.pop(),yield*this.pop(n)}if((r.type==="document"||r.type==="block-map"||r.type==="block-seq")&&(n.type==="block-map"||n.type==="block-seq")){let o=n.items[n.items.length-1];o&&!o.sep&&!o.value&&o.start.length>0&&Nl(o.start)===-1&&(n.indent===0||o.start.every(s=>s.type!=="comment"||s.indent<n.indent))&&(r.type==="document"?r.end=o.start:r.items.push({start:o.start}),n.items.splice(-1,1))}}}*stream(){switch(this.type){case"directive-line":yield{type:"directive",offset:this.offset,source:this.source};return;case"byte-order-mark":case"space":case"comment":case"newline":yield this.sourceToken;return;case"doc-mode":case"doc-start":{let t={type:"document",offset:this.offset,start:[]};this.type==="doc-start"&&t.start.push(this.sourceToken),this.stack.push(t);return}}yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(t){if(t.value)return yield*this.lineEnd(t);switch(this.type){case"doc-start":{Nl(t.start)!==-1?(yield*this.pop(),yield*this.step()):t.start.push(this.sourceToken);return}case"anchor":case"tag":case"space":case"comment":case"newline":t.start.push(this.sourceToken);return}let n=this.startBlockValue(t);n?this.stack.push(n):yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar(t){if(this.type==="map-value-ind"){let n=Fr(this.peek(2)),r=Ut(n),o;t.end?(o=t.end,o.push(this.sourceToken),delete t.end):o=[this.sourceToken];let s={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:r,key:t,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=s}else yield*this.lineEnd(t)}*blockScalar(t){switch(this.type){case"space":case"comment":case"newline":t.props.push(this.sourceToken);return;case"scalar":if(t.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let n=this.source.indexOf(`
+`)+1;for(;n!==0;)this.onNewLine(this.offset+n),n=this.source.indexOf(`
+`,n)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(t){let n=t.items[t.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,n.value){let r="end"in n.value?n.value.end:void 0;(Array.isArray(r)?r[r.length-1]:void 0)?.type==="comment"?r?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else n.sep?n.sep.push(this.sourceToken):n.start.push(this.sourceToken);return;case"space":case"comment":if(n.value)t.items.push({start:[this.sourceToken]});else if(n.sep)n.sep.push(this.sourceToken);else{if(this.atIndentedComment(n.start,t.indent)){let o=t.items[t.items.length-2]?.value?.end;if(Array.isArray(o)){Br(o,n.start),o.push(this.sourceToken),t.items.pop();return}}n.start.push(this.sourceToken)}return}if(this.indent>=t.indent){let r=!this.onKeyLine&&this.indent===t.indent,o=r&&(n.sep||n.explicitKey)&&this.type!=="seq-item-ind",s=[];if(o&&n.sep&&!n.value){let i=[];for(let c=0;c<n.sep.length;++c){let a=n.sep[c];switch(a.type){case"newline":i.push(c);break;case"space":break;case"comment":a.indent>t.indent&&(i.length=0);break;default:i.length=0}}i.length>=2&&(s=n.sep.splice(i[1]))}switch(this.type){case"anchor":case"tag":o||n.value?(s.push(this.sourceToken),t.items.push({start:s}),this.onKeyLine=!0):n.sep?n.sep.push(this.sourceToken):n.start.push(this.sourceToken);return;case"explicit-key-ind":!n.sep&&!n.explicitKey?(n.start.push(this.sourceToken),n.explicitKey=!0):o||n.value?(s.push(this.sourceToken),t.items.push({start:s,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(n.explicitKey)if(n.sep)if(n.value)t.items.push({start:[],key:null,sep:[this.sourceToken]});else if(lt(n.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:s,key:null,sep:[this.sourceToken]}]});else if(Tl(n.key)&&!lt(n.sep,"newline")){let i=Ut(n.start),c=n.key,a=n.sep;a.push(this.sourceToken),delete n.key,delete n.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:c,sep:a}]})}else s.length>0?n.sep=n.sep.concat(s,this.sourceToken):n.sep.push(this.sourceToken);else if(lt(n.start,"newline"))Object.assign(n,{key:null,sep:[this.sourceToken]});else{let i=Ut(n.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]})}else n.sep?n.value||o?t.items.push({start:s,key:null,sep:[this.sourceToken]}):lt(n.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):n.sep.push(this.sourceToken):Object.assign(n,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let i=this.flowScalar(this.type);o||n.value?(t.items.push({start:s,key:i,sep:[]}),this.onKeyLine=!0):n.sep?this.stack.push(i):(Object.assign(n,{key:i,sep:[]}),this.onKeyLine=!0);return}default:{let i=this.startBlockValue(t);if(i){if(i.type==="block-seq"){if(!n.explicitKey&&n.sep&&!lt(n.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else r&&t.items.push({start:s});this.stack.push(i);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(t){let n=t.items[t.items.length-1];switch(this.type){case"newline":if(n.value){let r="end"in n.value?n.value.end:void 0;(Array.isArray(r)?r[r.length-1]:void 0)?.type==="comment"?r?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else n.start.push(this.sourceToken);return;case"space":case"comment":if(n.value)t.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(n.start,t.indent)){let o=t.items[t.items.length-2]?.value?.end;if(Array.isArray(o)){Br(o,n.start),o.push(this.sourceToken),t.items.pop();return}}n.start.push(this.sourceToken)}return;case"anchor":case"tag":if(n.value||this.indent<=t.indent)break;n.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==t.indent)break;n.value||lt(n.start,"seq-item-ind")?t.items.push({start:[this.sourceToken]}):n.start.push(this.sourceToken);return}if(this.indent>t.indent){let r=this.startBlockValue(t);if(r){this.stack.push(r);return}}yield*this.pop(),yield*this.step()}*flowCollection(t){let n=t.items[t.items.length-1];if(this.type==="flow-error-end"){let r;do yield*this.pop(),r=this.peek(1);while(r?.type==="flow-collection")}else if(t.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!n||n.sep?t.items.push({start:[this.sourceToken]}):n.start.push(this.sourceToken);return;case"map-value-ind":!n||n.value?t.items.push({start:[],key:null,sep:[this.sourceToken]}):n.sep?n.sep.push(this.sourceToken):Object.assign(n,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!n||n.value?t.items.push({start:[this.sourceToken]}):n.sep?n.sep.push(this.sourceToken):n.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let o=this.flowScalar(this.type);!n||n.value?t.items.push({start:[],key:o,sep:[]}):n.sep?this.stack.push(o):Object.assign(n,{key:o,sep:[]});return}case"flow-map-end":case"flow-seq-end":t.end.push(this.sourceToken);return}let r=this.startBlockValue(t);r?this.stack.push(r):(yield*this.pop(),yield*this.step())}else{let r=this.peek(2);if(r.type==="block-map"&&(this.type==="map-value-ind"&&r.indent===t.indent||this.type==="newline"&&!r.items[r.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&r.type!=="flow-collection"){let o=Fr(r),s=Ut(o);Cl(t);let i=t.end.splice(1,t.end.length);i.push(this.sourceToken);let c={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:s,key:t,sep:i}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=c}else yield*this.lineEnd(t)}}flowScalar(t){if(this.onNewLine){let n=this.source.indexOf(`
+`)+1;for(;n!==0;)this.onNewLine(this.offset+n),n=this.source.indexOf(`
+`,n)+1}return{type:t,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(t){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let n=Fr(t),r=Ut(n);return r.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let n=Fr(t),r=Ut(n);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(t,n){return this.type!=="comment"||this.indent<=n?!1:t.every(r=>r.type==="newline"||r.type==="space")}*documentEnd(t){this.type!=="doc-mode"&&(t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(t){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;case"space":case"comment":default:t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};function Im(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new Dn||null,prettyErrors:t}}function ws(e,t={}){let{lineCounter:n,prettyErrors:r}=Im(t),o=new In(n?.addNewLine),s=new kn(t),i=null;for(let c of s.compose(o.parse(e),!0,e.length))if(!i)i=c;else if(i.options.logLevel!=="silent"){i.errors.push(new ve(c.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return r&&n&&(i.errors.forEach(is(e,n)),i.warnings.forEach(is(e,n))),i}var Ae=class extends Error{code;constructor(t){super(`Structured data failed validation: ${t}`),this.name="StructuredDataError",this.code=t}},$m=e=>Oe(JSON.stringify(e)),zl=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},Pl=(e,t)=>{if(zl(e)===!1)throw new Ae("INVALID");let n=0,r=(s,i)=>{if(i>t.depth)throw new Ae("DEPTH_EXCEEDED");if(typeof s=="string"){if(Oe(s)>t.stringBytes)throw new Ae("STRING_BYTES_EXCEEDED");return s}if(s===null||typeof s=="boolean"||typeof s=="number"&&Number.isFinite(s)&&(Number.isInteger(s)===!1||Number.isSafeInteger(s)))return s;if(Array.isArray(s))return s.map(c=>{if(n+=1,n>t.fields)throw new Ae("FIELDS_EXCEEDED");return r(c,i+1)});if(zl(s)){let c=Object.create(null);for(let[a,u]of Object.entries(s)){if(n+=1,n>t.fields)throw new Ae("FIELDS_EXCEEDED");c[a]=r(u,i+1)}return c}throw new Ae("INVALID")},o=r(e,1);if($m(o)>t.serializedBytes)throw new Ae("SERIALIZED_BYTES_EXCEEDED");return o};var W=class extends Error{code;constructor(t,n){super(n),this.name="MarkdownMetadataError",this.code=t}};var On=new Uint8Array([239,187,191]),Ll=On.byteLength+10,Rm=(e,t,n=0)=>e.byteLength-n<t.byteLength?!1:t.every((r,o)=>e[n+o]===r),$n=(e,t)=>{let n=0;if(Rm(e,On))n=On.byteLength;else if(e.byteLength<On.byteLength&&On.slice(0,e.byteLength).every((s,i)=>s===e[i]))return t?null:void 0;if(e.byteLength<n+4)return t?null:void 0;if(e[n]!==45||e[n+1]!==45||e[n+2]!==45)return null;let r=n+3;if(e[r]===10)r+=1;else if(e[r]===13){if(e.byteLength===r+1)return t?null:void 0;if(e[r+1]!==10)return null;r+=2}else return null;let o=r;for(let s=r;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:r,yamlEnd:o,blockEnd:i?s:s+1};o=s+1}};var Nm={bytes:D.frontmatterBytes,depth:D.frontmatterDepth,fields:D.frontmatterFields,stringBytes:D.frontmatterStringBytes,serializedBytes:D.indexedPropertiesBytes},Ml=e=>{try{return ae(e)}catch{throw new W("FRONTMATTER_DECODING_FAILED","Markdown frontmatter is not valid UTF-8")}},Zl=(e,t)=>{let n=ws(e,{schema:"core",uniqueKeys:!0});if(n.errors.length>0)throw new W("FRONTMATTER_INVALID","Markdown frontmatter contains invalid YAML");let r;try{r=n.toJS({maxAliasCount:0})}catch{throw new W("FRONTMATTER_INVALID","Markdown frontmatter contains unsupported YAML aliases")}if(r===null)return{};try{return Pl(r,t)}catch(o){throw o instanceof Ae?o.code==="DEPTH_EXCEEDED"?new W("FRONTMATTER_DEPTH_EXCEEDED","Markdown frontmatter exceeds the nesting limit"):o.code==="FIELDS_EXCEEDED"?new W("FRONTMATTER_FIELDS_EXCEEDED","Markdown frontmatter exceeds the field limit"):o.code==="STRING_BYTES_EXCEEDED"?new W("FRONTMATTER_STRING_BYTES_EXCEEDED","Markdown frontmatter contains a string that exceeds the byte limit"):o.code==="SERIALIZED_BYTES_EXCEEDED"?new W("FRONTMATTER_BYTES_EXCEEDED","Markdown frontmatter properties exceed the indexed byte limit"):new W("FRONTMATTER_INVALID","Markdown frontmatter must contain a JSON-compatible object"):o}},Fl=async(e,t={})=>{let n={...Nm,...t},r=n.bytes+Ll,o=new Uint8Array(r),s=0;for await(let a of Ot(e)){let u=0;for(;u<a.byteLength;){let d=r-s;if(d<=0)break;let l=Math.max(0,6-s),f=Math.min(a.byteLength-u,l);if(l===0){let m=a.subarray(u,Math.min(a.byteLength,u+d)),h=m.indexOf(10);f=h===-1?m.byteLength:h+1}o.set(a.subarray(u,u+f),s),s+=f,u+=f;let p=o.subarray(0,s),y=$n(p,!1);if(y===null)return{properties:{},frontmatterBytes:0,consumedBytes:p.length};if(y!==void 0){let m=y.yamlEnd-y.yamlStart;if(m>n.bytes)throw new W("FRONTMATTER_BYTES_EXCEEDED","Markdown frontmatter exceeds the byte limit");let h=Ml(p.subarray(y.yamlStart,y.yamlEnd));return{properties:Zl(h,n),frontmatterBytes:m,consumedBytes:y.blockEnd}}}if(s>=r)break}let i=o.subarray(0,s),c=$n(i,!0);if(c===null)return{properties:{},frontmatterBytes:0,consumedBytes:i.length};if(c!==void 0){let a=c.yamlEnd-c.yamlStart;if(a<=n.bytes){let u=Ml(i.subarray(c.yamlStart,c.yamlEnd));return{properties:Zl(u,n),frontmatterBytes:a,consumedBytes:c.blockEnd}}}throw new W("FRONTMATTER_BYTES_EXCEEDED","Markdown frontmatter is not closed within the byte limit")};var jr=async(e,t=D.hydratedFileBytes)=>{if(Number.isInteger(t)===!1||t<=0||t>D.hydratedFileBytes)throw new W("MARKDOWN_BODY_BYTES_EXCEEDED","Markdown body byte limit is outside the supported range");let n;try{n=await pe(e,t)}catch(c){throw c instanceof te?new W("MARKDOWN_BODY_BYTES_EXCEEDED","Markdown content exceeds the byte limit"):c}let r;try{r=ae(n)}catch{throw new W("MARKDOWN_BODY_DECODING_FAILED","Markdown content is not valid UTF-8")}let s=$n(n,!0)?.blockEnd??0,i;try{i=s===0?$t(r):ae(n.subarray(s))}catch{throw new W("MARKDOWN_BODY_DECODING_FAILED","Markdown content is not valid UTF-8")}return{body:i,bodyBytes:Oe(i),sourceBytes:n.byteLength}};var ft=class extends Error{code;referenceId;constructor({code:t,message:n,referenceId:r,cause:o}){super(n,{cause:o}),this.name="MarkdownDocumentError",this.code=t,this.referenceId=r}},Cm=O({source:k(),body:k(),frontmatter:Ie(k(),tt())}),Qr=e=>{let t;try{t=Cm.parse(e)}catch(n){throw new ft({code:"INVALID_DOCUMENT",message:"Markdown document is invalid",cause:n})}return Object.freeze({source:t.source,body:t.body,frontmatter:nt(t.frontmatter)})},Ur="#frontmatter",Tm=e=>`${Ur}${e.slice(1)}`,zm=e=>{if(e!==Ur&&e.startsWith(`${Ur}/`)===!1)throw new ft({code:"UNUSED_REFERENCE",message:`Resolved Markdown reference ${e} is outside frontmatter`,referenceId:e});return`#${e.slice(Ur.length)}`},Pm=e=>{let t=e.referenceId===void 0?void 0:Tm(e.referenceId),n="INVALID_DOCUMENT";throw(e.code==="INVALID_REFERENCE_MARKER"||e.code==="INVALID_REFERENCE"||e.code==="REFERENCE_NOT_FOUND"||e.code==="INVALID_RESOLVED_VALUE"||e.code==="UNUSED_REFERENCE")&&(n=e.code),new ft({code:n,message:e.message,referenceId:t,cause:e})},Bl=async({source:e,maximumBytes:t=D.hydratedFileBytes})=>{let n;try{n=await pe(e,t)}catch(i){throw i instanceof te?new ft({code:"CONTENT_LIMIT_EXCEEDED",message:"Markdown document exceeds the byte limit",cause:i}):i}let r;try{r=$t(ae(n))}catch(i){throw new ft({code:"CONTENT_DECODING_FAILED",message:"Markdown document is not valid UTF-8",cause:i})}let[o,s]=await Promise.all([jr(n,t),Fl(n)]);return Qr({source:r,body:o.body,frontmatter:s.properties})};var jl=({document:e,references:t,allowUnresolvedReferences:n=!1})=>{let r=Qr(e),o=new Map;for(let[i,c]of t)o.set(zm(i),c);let s;try{s=ir({document:r.frontmatter,references:o,allowUnresolvedReferences:n})}catch(i){throw i instanceof ue&&Pm(i),i}return Qr({...r,frontmatter:s})},Ul=({document:e,representation:t})=>{let n=Qr(e);if(t.type==="document")return n.source;if(t.type==="markdown-body")return n.body;if(t.type==="markdown-frontmatter")return n.frontmatter;throw new ft({code:"UNSUPPORTED_REPRESENTATION",message:`Markdown documents do not support ${t.type}`})};var Ql=e=>{let t=e.format==="markdown"?e.value.frontmatter:e.value;return Nt(t)?t:void 0},Jr=e=>Object.freeze(e),Jl=async({format:e,source:t,maximumBytes:n=D.hydratedFileBytes})=>Jr(e==="json"?{format:e,value:await Qu({source:t,maximumBytes:n})}:{format:e,value:await Bl({source:t,maximumBytes:n})});var Vl=({document:e,references:t,allowUnresolvedReferences:n})=>e.format==="json"?Jr({format:e.format,value:ir({document:e.value,references:t,allowUnresolvedReferences:n})}):Jr({format:e.format,value:jl({document:e.value,references:t,allowUnresolvedReferences:n})}),Gl=({document:e,representation:t})=>e.format==="json"?Ju({document:e.value,representation:t}):Ul({document:e.value,representation:t});var Vr=class extends Error{code;documentId;expectedRevision;actualRevision;expectedFormat;actualFormat;constructor({code:t,documentId:n,expectedRevision:r,actualRevision:o,expectedFormat:s,actualFormat:i}){super(`Document ${n} source ${t==="REVISION_MISMATCH"?"revision":"format"} does not match its graph`),this.name="DocumentSourceError",this.code=t,this.documentId=n,this.expectedRevision=r,this.actualRevision=o,this.expectedFormat=s,this.actualFormat=i}},Qt=({node:e,source:t})=>{if(t.revision!==e.revision)throw new Vr({code:"REVISION_MISMATCH",documentId:e.id,expectedRevision:e.revision,actualRevision:t.revision});if(e.format!==void 0&&t.format!==e.format)throw new Vr({code:"FORMAT_MISMATCH",documentId:e.id,expectedFormat:e.format,actualFormat:t.format});return t};var Jt=e=>{if(typeof e=="object"&&e!==null){let t=Reflect.get(e,"code");if(typeof t=="string"&&t.length>0)return t;let n=Reflect.get(e,"name");if(typeof n=="string"&&n.length>0)return n}return"UNKNOWN"},re=(e,t)=>{try{e?.(t)}catch{}},ql=({load:e,onEvent:t})=>async(n,r)=>{let o={documentId:n.id,revision:n.revision};re(t,{type:"document-fetch-started",...o});try{let s=await e(n,r);return re(t,{type:"document-fetch-completed",...o}),s}catch(s){throw re(t,{type:"document-fetch-failed",...o,errorCode:Jt(s)}),s}};var Lm=O({format:ce(["json","markdown"]),revision:k().min(1)}),Vt=class extends Error{code;documentId;status;constructor({code:t,message:n,documentId:r,status:o,cause:s}){super(n,{cause:s}),this.name="HttpDocumentLoaderError",this.code=t,this.documentId=r,this.status=o}},Mm=e=>({async*[Symbol.asyncIterator](){let t=e.getReader(),n=!1;try{for(;;){let r=await t.read();if(r.done){n=!0;return}yield r.value}}finally{if(n===!1)try{await t.cancel()}catch{}t.releaseLock()}}}),Kl=({fetch:e,getRequest:t,getMetadata:n,onEvent:r})=>ql({load:async(s,{signal:i})=>{let c;try{c=await e(t(s),{signal:i})}catch(d){throw new Vt({code:"REQUEST_FAILED",message:`Document ${s.id} request failed`,documentId:s.id,cause:d})}if(c.ok===!1)throw new Vt({code:"HTTP_STATUS",message:`Document ${s.id} request returned status ${c.status}`,documentId:s.id,status:c.status});let a;try{a=Lm.parse(n({node:s,response:c}))}catch(d){throw new Vt({code:"INVALID_METADATA",message:`Document ${s.id} response metadata is invalid`,documentId:s.id,cause:d})}let u=c.body;if(u===null)throw new Vt({code:"BODY_MISSING",message:`Document ${s.id} response body is unavailable`,documentId:s.id});return Object.freeze({...a,source:Mm(u)})},onEvent:r});var Rn=class extends Error{code="CONTENT_LIMIT_EXCEEDED";documentId;contentByteLimit;constructor({message:t,documentId:n,contentByteLimit:r,cause:o}){super(t,{cause:o}),this.name="CachedDocumentLoaderError",this.documentId=n,this.contentByteLimit=r}},Zm=({contentRef:e,revision:t,format:n})=>$e([e,t,n??null]),Fm=e=>{if(typeof e!="object"||e===null)return!1;let t=e;return(t.format==="json"||t.format==="markdown")&&typeof t.revision=="string"&&t.revision.length>0&&t.bytes instanceof Uint8Array},Wl=e=>Object.freeze({format:e.format,revision:e.revision,source:e.bytes}),Yl=({load:e,cache:t,maximumBytes:n=D.hydratedFileBytes,onEvent:r})=>{let o=new Map;return async(s,i)=>{let c=Zm(s),a=o.get(c)??new Map;o.set(c,a);let u=a.get(i.signal);if(u!==void 0)return await u;let d=(async()=>{let l;try{l=await t.get(c)}catch(m){re(r,{type:"document-cache-read-failed",documentId:s.id,revision:s.revision,errorCode:Jt(m)})}if(Fm(l)&&l.revision===s.revision&&l.bytes.byteLength<=n&&(s.format===void 0||l.format===s.format))return re(r,{type:"document-cache-hit",documentId:s.id,revision:s.revision}),Wl(l);re(r,{type:"document-cache-miss",documentId:s.id,revision:s.revision});let f=Qt({node:s,source:await e(s,i)}),p;try{p=await pe(f.source,n)}catch(m){throw m instanceof te?new Rn({message:`Document ${s.id} exceeds the cache byte limit`,documentId:s.id,contentByteLimit:n,cause:m}):m}let y=Object.freeze({format:f.format,revision:f.revision,bytes:p});try{await t.set(c,y),re(r,{type:"document-cache-stored",documentId:s.id,revision:s.revision})}catch(m){re(r,{type:"document-cache-write-failed",documentId:s.id,revision:s.revision,errorCode:Jt(m)})}return Wl(y)})();a.set(i.signal,d);try{return await d}finally{a.delete(i.signal),a.size===0&&o.delete(c)}}};var Ge=class extends Error{code;documentId;referenceId;constructor({code:t,message:n,documentId:r,referenceId:o,cause:s}){super(n,{cause:s}),this.name="DocumentGraphResolutionError",this.code=t,this.documentId=r,this.referenceId=o}},Gr=e=>{if(e?.aborted)throw new Ge({code:"REQUEST_CANCELLED",message:"Document graph resolution was cancelled",cause:e.reason})},Xl=async({graph:e,rootIds:t,concurrency:n,signal:r,load:o,select:s,assemble:i})=>{Gr(r);let c=tr({graph:e,rootIds:t}),a=new Map(c.map(p=>[p.id,p])),u=new Map,d=new Map;for(let p of c){let y=d.get(p.contentRef);y===void 0?d.set(p.contentRef,{representative:p,nodes:[p]}):y.nodes.push(p)}await sr([...d.values()],n,async p=>{Gr(r);let y=p.representative;try{let m=await o(y,{signal:r});for(let h of p.nodes)u.set(h.id,m)}catch(m){throw r?.aborted&&Gr(r),new Ge({code:"DOCUMENT_LOAD_FAILED",message:`Document ${y.id} could not be loaded`,documentId:y.id,cause:m})}});let l=Rt(e.edges),f=new Map;for(let p of c){Gr(r);let y=new Map;for(let h of l.get(p.id)??[]){let b=a.get(h.reference.documentId);if(b===void 0||f.has(h.reference.documentId)===!1)throw new Ge({code:"DOCUMENT_ASSEMBLY_FAILED",message:`Document ${p.id} dependency ${h.reference.documentId} is unavailable`,documentId:p.id,referenceId:h.referenceId});let _=f.get(h.reference.documentId),x;if(s===void 0){if(h.reference.representation.type!=="document")throw new Ge({code:"REPRESENTATION_SELECTOR_REQUIRED",message:`Document ${p.id} reference ${h.referenceId} requires a representation selector`,documentId:p.id,referenceId:h.referenceId});x=_}else try{x=await s({reference:h.reference,value:_,sourceNode:p,targetNode:b})}catch(w){throw new Ge({code:"DOCUMENT_SELECTION_FAILED",message:`Document ${p.id} reference ${h.referenceId} could not be selected`,documentId:p.id,referenceId:h.referenceId,cause:w})}y.set(h.referenceId,x)}if(u.has(p.id)===!1)throw new Ge({code:"DOCUMENT_ASSEMBLY_FAILED",message:`Document ${p.id} source is unavailable`,documentId:p.id});let m=u.get(p.id);try{f.set(p.id,await i({node:p,source:m,references:y}))}catch(h){throw new Ge({code:"DOCUMENT_ASSEMBLY_FAILED",message:`Document ${p.id} could not be assembled`,documentId:p.id,cause:h})}}return Object.freeze({roots:Object.freeze(t.map(p=>f.get(p))),values:f})};var bt=class extends Error{code;documentId;documentCount;documentLimit;contentByteLimit;totalBytes;totalByteLimit;constructor({code:t,message:n,documentId:r,documentCount:o,documentLimit:s,contentByteLimit:i,totalBytes:c,totalByteLimit:a,cause:u}){super(n,{cause:u}),this.name="DocumentResolutionLimitError",this.code=t,this.documentId=r,this.documentCount=o,this.documentLimit=s,this.contentByteLimit=i,this.totalBytes=c,this.totalByteLimit=a}},Hl=async({graph:e,rootIds:t,concurrency:n,maximumBytes:r=D.hydratedFileBytes,maximumTotalBytes:o=D.hydratedTotalBytes,maximumDocuments:s=D.hydratedFileCount,signal:i,load:c,onEvent:a,allowUnresolvedReferences:u=!1})=>{let d=tr({graph:e,rootIds:t}).length,l={rootCount:t.length,documentCount:d};re(a,{type:"resolution-started",...l});try{if(d>s)throw new bt({code:"DOCUMENT_COUNT_EXCEEDED",message:"Document graph resolution exceeds the document limit",documentCount:d,documentLimit:s});let f=0,p=await Xl({graph:e,rootIds:t,concurrency:n,signal:i,load:async(y,m)=>{let h=Qt({node:y,source:await c(y,m)}),b;try{b=await pe(h.source,r)}catch(x){throw x instanceof te?new bt({code:"CONTENT_LIMIT_EXCEEDED",message:`Document ${y.id} exceeds the byte limit`,documentId:y.id,contentByteLimit:r,cause:x}):x}let _=f+b.byteLength;if(_>o)throw new bt({code:"TOTAL_BYTES_EXCEEDED",message:"Document graph resolution exceeds the total byte limit",documentId:y.id,totalBytes:_,totalByteLimit:o});return f=_,await Jl({format:h.format,source:b,maximumBytes:r})},select:({reference:y,value:m})=>Gl({document:m,representation:y.representation}),assemble:({source:y,references:m})=>Vl({document:y,references:m,allowUnresolvedReferences:u})});return re(a,{type:"resolution-completed",...l}),p}catch(f){throw re(a,{type:"resolution-failed",...l,errorCode:Jt(f)}),f}};var ef=e=>{if(e.output.mode==="all")return"all";let t=[];for(let{field:n}of Xn(e.where))n[0]==="properties"&&t.push(n);for(let{field:n}of e.sort)n[0]==="properties"&&t.push(n);if(e.output.mode==="fields")for(let n of e.output.fields)n[0]==="properties"&&t.push(n);return t},tf=e=>{let t;if(e==="#frontmatter")t="";else if(e.startsWith("#frontmatter/"))t=e.slice(12);else if(e==="#")t="";else if(e.startsWith("#/"))t=e.slice(1);else return;try{return["properties",...ju(t)]}catch{return}},nf=(e,t)=>{let n=Math.min(e.length,t.length);for(let r=0;r<n;r+=1)if(e[r]!==t[r])return!1;return!0},rf=({queryPaths:e,referenceId:t})=>{let n=tf(t);return n!==void 0&&(e==="all"||e.some(r=>nf(r,n)))},of=({graph:e,sourceId:t,field:n})=>n[0]!=="properties"?!1:e.edges.some(r=>{if(r.sourceId!==t)return!1;let o=tf(r.referenceId);return o!==void 0&&nf(n,o)}),sf=({graph:e,query:t})=>{let n=ef(t),r=new Set;for(let o of e.edges)rf({queryPaths:n,referenceId:o.referenceId})&&r.add(o.sourceId);return[...r]},cf=({graph:e,query:t,rootIds:n})=>{let r=ef(t),o=new Set(n),s=new Map(e.nodes.map(l=>[l.id,l])),i=Rt(e.edges),c=new Set(n),a=new Set,u=new Set,d=l=>{if(c.add(l),!u.has(l)){u.add(l);for(let f of i.get(l)??[])a.add(f),d(f.reference.documentId)}};for(let l of e.edges)o.has(l.sourceId)&&rf({queryPaths:r,referenceId:l.referenceId})&&(a.add(l),d(l.reference.documentId));return an({nodes:[...c].map(l=>{let f=s.get(l);if(f===void 0)throw new Error(`Document graph query root ${l} does not exist`);return f}),edges:[...a]})};var af=({artifact:e})=>{if(e.documentGraph===void 0)return;let t=new Map(e.documents.map(s=>[s._id,s])),n=new Map(e.documentGraph.nodes.map(s=>[s.id,s])),r=new Map;for(let{sourceId:s}of e.documentGraph.edges){if(n.has(s))continue;let i=t.get(s);if(i?.properties===void 0)throw new Error(`Runtime document graph source ${s} is unavailable`);r.set(s,i),n.set(s,{id:s,revision:s,contentRef:s,format:"json"})}return{graph:an({nodes:[...n.values()],edges:e.documentGraph.edges.map(({sourceId:s,referenceId:i,documentId:c,representation:a})=>{let u=n.get(c);if(u===void 0)throw new Error(`Runtime document graph target ${c} is unavailable`);return{sourceId:s,referenceId:i,reference:{documentId:c,revision:u.revision,representation:a}}})}),inlineDocuments:r}};var Bm=(e,t)=>{if(t===void 0||t.length===0)return e;let n=new URL("https://content.webstudio.invalid/__assets__/"),r=new URL(e,n),o=new URL(t,n);for(let[c,a]of o.searchParams)r.searchParams.append(c,a);if(o.hash!==""&&(r.hash=o.hash),URL.canParse(e))return r.href;if(e.startsWith("//"))return`//${r.host}${r.pathname}${r.search}${r.hash}`;if(e.startsWith("/"))return`${r.pathname}${r.search}${r.hash}`;let s=n.pathname;return`${r.pathname.startsWith(s)?r.pathname.slice(s.length):r.pathname}${r.search}${r.hash}`},uf=({markdown:e,references:t,assetUrls:n})=>{let r=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>r)throw new Error("Markdown asset reference range is invalid");r=s.start;let i=n[s.assetId];if(i===void 0)continue;let c=Bm(i,s.suffix);o=`${o.slice(0,s.start)}${c}${o.slice(s.end)}`}return o};var oe=class extends Error{code;details;constructor({code:t,message:n,details:r}){super(n),this.name="AssetResourceHydrationError",this.code=t,this.details=r}},jm=e=>{if(e===null)return[];let t=Array.isArray(e)?e:[e],n=new Map;for(let r of t){if(typeof r!="object"||r===null||!("_id"in r)||typeof r._id!="string"||!("revision"in r)||typeof r.revision!="string"||!("contentRef"in r)||typeof r.contentRef!="string")throw new oe({code:"CONTENT_IDENTITY_REQUIRED",message:"Hydrated query results must retain _id, revision, and contentRef"});let o=n.get(r._id);if(o!==void 0&&(o.revision!==r.revision||o.contentRef!==r.contentRef))throw new oe({code:"CONTENT_IDENTITY_REQUIRED",message:"A selected asset ID has conflicting content identity",details:{assetId:r._id}});n.set(r._id,{_id:r._id,revision:r.revision,contentRef:r.contentRef})}return Array.from(n.values())},Um=e=>typeof e.mimeType=="string"&&(e.mimeType.startsWith("text/")||["application/json","application/javascript","application/xml","image/svg+xml"].includes(e.mimeType)),Qm=async({read:e,contentRef:t,range:n,maximumBytes:r})=>{if(r===0)return new Uint8Array;let o=await e(t,n);try{return await pe(o.data,r)}catch(s){throw s instanceof te?new oe({code:"CONTENT_LIMIT_EXCEEDED",message:"Asset storage returned more content than requested"}):s}},Jm=e=>{try{return ae(e)}catch{throw new oe({code:"CONTENT_DECODING_FAILED",message:"Selected asset content is not valid UTF-8"})}},Vm=(e,t)=>{if(t.mode==="range")return Math.max(0,Math.min(t.length,e.size-t.offset));let n=t.maxBytes??D.hydratedFileBytes;if(e.size>n)throw new oe({code:"CONTENT_LIMIT_EXCEEDED",message:"Selected asset exceeds the per-file content limit",details:{assetId:e._id,assetBytes:e.size,fileByteLimit:n}});return e.size},lf=async({result:e,documents:t,options:n,read:r,assetReferences:o,assetUrls:s})=>{if(n.mode==="none")return{content:{},hydratedFileCount:0,hydratedBytes:0};let i=jm(e);if(i.length>D.hydratedFileCount)throw new oe({code:"CONTENT_LIMIT_EXCEEDED",message:"Too many selected assets requested content hydration",details:{fileCount:i.length,fileCountLimit:D.hydratedFileCount}});let c=new Map(t.map(l=>[l._id,l])),a=i.map(l=>{let f=c.get(l._id);if(f===void 0||f.revision!==l.revision||f.contentRef!==l.contentRef||typeof f.size!="number"||typeof f.mimeType!="string")throw new oe({code:"CONTENT_IDENTITY_REQUIRED",message:"Selected asset content identity is stale or unavailable",details:{assetId:l._id}});let p={...f,size:f.size,mimeType:f.mimeType};if(Um(p)===!1)throw new oe({code:"CONTENT_NOT_TEXT",message:"Selected binary asset cannot be embedded as text",details:{assetId:l._id,mimeType:p.mimeType}});return{identity:l,document:p,readLength:Vm(p,n)}}),u=a.reduce((l,f)=>l+f.readLength,0);if(u>D.hydratedTotalBytes)throw new oe({code:"CONTENT_LIMIT_EXCEEDED",message:"Selected assets exceed the total hydrated-content limit",details:{totalReadBytes:u,totalByteLimit:D.hydratedTotalBytes}});let d=await sr(a,D.concurrentContentReads,async l=>{let f=n.mode==="range"?{offset:n.offset,length:l.readLength}:l.readLength===0?void 0:{offset:0,length:l.readLength},p=await Qm({read:r,contentRef:l.identity.contentRef,range:f,maximumBytes:l.readLength});if(p.byteLength!==l.readLength)throw new oe({code:"CONTENT_IDENTITY_REQUIRED",message:"Selected asset bytes do not match canonical metadata",details:{assetId:l.identity._id}});let y;if(n.mode==="markdown-body")try{y=(await jr(p,l.readLength||1)).body;let h=o?.[l.identity.contentRef];h!==void 0&&s!==void 0&&(y=uf({markdown:y,references:h,assetUrls:s}))}catch{throw new oe({code:"CONTENT_DECODING_FAILED",message:"Selected Markdown body could not be decoded",details:{assetId:l.identity._id}})}else y=Jm(p);let m=Oe(y);return{id:l.identity._id,returnedBytes:m,content:{...l.identity,encoding:"utf-8",text:y,...n.mode==="range"?{range:{offset:n.offset,length:p.byteLength,total:l.document.size}}:{}}}});return{content:Object.fromEntries(d.map(({id:l,content:f})=>[l,f])),hydratedFileCount:a.length,hydratedBytes:d.reduce((l,{returnedBytes:f})=>l+f,0)}};var Hv=k().datetime({offset:!0}).transform(e=>new Date(e).toISOString());var Gm=/^[A-Za-z_][A-Za-z0-9_]*$/,ff=(e,t)=>Gm.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`;var df=({document:e,includes:t})=>{let n={};for(let r of Pu){let o=e[r];o!==void 0&&t(r)&&(n[r]=o)}return n},pf=({source:e,target:t,path:n})=>{let[r,...o]=n;if(r===void 0||Object.hasOwn(e,r)===!1)return;let s=e[r];if(o.length===0){Object.defineProperty(t,r,{value:s,enumerable:!0,configurable:!0,writable:!0});return}if(typeof s!="object"||s===null||Array.isArray(s))return;let i={};if(pf({source:s,target:i,path:o}),Object.keys(i).length===0)return;let c=t[r];Object.defineProperty(t,r,{value:{...typeof c=="object"&&c!==null&&Array.isArray(c)===!1?c:{},...i},enumerable:!0,configurable:!0,writable:!0})},mf=({properties:e,fields:t})=>{let n={};for(let r of t)r[0]==="properties"&&pf({source:e,target:n,path:r.slice(1)});return n};var qe=class extends Error{constructor(t,n){super(t,n),this.name="AssetQueryExecutionError"}},qt=class extends Error{constructor(){super("The requested asset index revision is stale"),this.name="AssetIndexRevisionError"}},hf=e=>{if(e[0]!=="properties")return e[0];let t="properties";for(let n of e.slice(1))t=ff(t,n);return t},yf=({filter:e,fieldTypes:t})=>Zu(t).includes(e.operator),gf=(e,t)=>e!==void 0&&Object.hasOwn(e.fields,t)?e.fields[t]:void 0,qm=({query:e,catalog:t})=>{let n=rt.parse(e),r=new Map,o=[];for(let s of Xn(n.where)){let i=hf(s.field);if(r.set(i,s.field),s.field[0]==="properties"){let c=gf(t,i);t!==void 0&&c===void 0?o.push(`Asset field ${i} is not currently observed`):c!==void 0&&yf({filter:s,fieldTypes:c.types})===!1&&o.push(`Operator ${s.operator} is not compatible with the currently observed types of ${i}`)}else if(yf({filter:s,fieldTypes:Bo[s.field[0]]})===!1)throw new qe(`Operator ${s.operator} is incompatible with ${i}`)}for(let s of n.sort){let i=hf(s.field);if(r.set(i,s.field),s.field[0]==="properties"){let c=gf(t,i);t!==void 0&&c===void 0?o.push(`Asset field ${i} is not currently observed`):c!==void 0&&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:n,referencedFieldPaths:[...r.values()],warnings:[...new Set(o)]}},_s=(e,t,n)=>{let r=t[0]==="id"?e._id:rr(t[0])?n?.[t[0]]:e[t[0]];for(let o of t.slice(1)){if(typeof r!="object"||r===null||Object.hasOwn(r,o)===!1)return;r=r[o]}return r},qr=(e,t)=>e===void 0||t===void 0?e===t:$e(e)===$e(t),Km=e=>typeof e=="string"||Array.isArray(e)?e.length===0:typeof e=="object"&&e!==null&&Object.keys(e).length===0,Wm=(e,t)=>{if(typeof e=="number"&&typeof t=="number")return e-t;if(typeof e=="string"&&typeof t=="string")return Re(e,t)},xs=(e,t,n)=>{let r=_s(e,t.field,n);if(t.operator==="exists")return r!=null===t.value;if(t.operator==="isEmpty")return Km(r)===t.value;if(t.operator==="eq")return qr(r,t.value);if(t.operator==="ne")return qr(r,t.value)===!1;if(t.operator==="in")return t.value.some(s=>qr(r,s));if(t.operator==="contains")return typeof r=="string"&&typeof t.value=="string"?r.includes(t.value):Array.isArray(r)&&r.some(s=>qr(s,t.value));if(t.operator==="startsWith")return typeof r=="string"&&typeof t.value=="string"&&r.startsWith(t.value);if(t.operator==="endsWith")return typeof r=="string"&&typeof t.value=="string"&&r.endsWith(t.value);let o=Wm(r,t.value);return o===void 0?!1:t.operator==="gt"?o>0:t.operator==="gte"?o>=0:t.operator==="lt"?o<0:o<=0},Ym=(e,t,n)=>Dt(t,r=>xs(e,r,n))===!0,Xm=(e,t)=>{let n=e==null,r=t==null;return n||r?n===r?0:n?1:-1:typeof e=="number"&&typeof t=="number"?e-t:(typeof e=="string"||typeof e=="boolean")&&(typeof t=="string"||typeof t=="boolean")?Re(String(e),String(t)):Re($e(e),$e(t))},Hm=({left:e,right:t,sort:n,runtimeAssets:r})=>{for(let o of n){let s=Xm(_s(e,o.field,r?.[e._id]),_s(t,o.field,r?.[t._id]));if(s!==0)return o.direction==="asc"?s:-s}return Re(e._id,t._id)};var eh=(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(r=>r[0]==="properties")===!1)return;let n=mf({properties:e.properties,fields:t.fields});return Object.keys(n).length===0?void 0:n},Gt=(e,t)=>e.includeMetadata&&Lu(t)||e.mode==="fields"&&e.fields.some(n=>n.length===1&&n[0]===t),th=e=>e.mode==="all"||e.mode==="fields"&&e.fields.some(t=>t.length===1&&t[0]==="excerpt"),nh=(e,t,n)=>{if(Gt(t,"url")&&n===void 0)throw new Error(`Asset URL is unavailable for ${e._id}`);let r=eh(e,t),o=n?.width!==void 0&&n.height!==void 0;return{...n!==void 0&&Gt(t,"url")?{url:n.url}:{},...o&&Gt(t,"width")?{width:n.width}:{},...o&&Gt(t,"height")?{height:n.height}:{},...df({document:e,includes:s=>Gt(t,s)}),...r===void 0?{}:{properties:r},...e.excerpt===void 0||th(t)===!1?{}:{excerpt:e.excerpt},...e.metadataError===void 0||t.includeMetadata===!1?{}:{metadataError:e.metadataError}}},rh=e=>{if(Oe($e(e))>D.resultBytes)throw new qe("Asset query result exceeds the byte limit")},bf=async({query:e,catalog:t,documents:n,read:r,runtimeAssets:o,assetReferences:s})=>{let{query:i}=qm({query:e,catalog:t});if(n.length>D.candidateDocuments)throw new qe("Asset query document limit was exceeded");let c=n.flatMap(p=>{let y=o?.[p._id];if(Ym(p,i.where,y)===!1)return[];let m=nh(p,i.output,y);return i.content.mode==="none"&&Object.keys(m).length===0&&Gt(i.output,"id")===!1?[]:[{document:p,item:{id:p._id,...m}}]}),u=[...c].sort((p,y)=>Hm({left:p.document,right:y.document,sort:i.sort,runtimeAssets:o})).slice(i.offset,i.offset+i.limit),d=u.map(({document:p})=>p),l=u.map(({item:p})=>p);if(i.content.mode!=="none"){let p=i.content;if(r===void 0)throw new qe("Asset content reader is unavailable");let y=await lf({result:d,documents:d,options:p,read:r,assetReferences:s,assetUrls:s===void 0?void 0:Object.fromEntries(Object.entries(o??{}).map(([m,h])=>[m,h.url]))});l=d.map((m,h)=>{let b=y.content[m._id];if(b===void 0)throw new qe("Selected asset content could not be read");return{...l[h],content:{encoding:b.encoding,text:b.text,...b.range===void 0?{}:{range:b.range}}}})}let f={items:l,totalCount:c.length,hasMore:i.offset+u.length<c.length};return rh(f),f};var oh=async e=>await ku($e(rt.parse(e)));var sh=({item:e,field:t,value:n})=>{let r=e;for(let[o,s]of t.entries()){if(o===t.length-1){Object.defineProperty(r,s,{value:n,enumerable:!0,configurable:!0,writable:!0});return}let i=Object.hasOwn(r,s)?r[s]:void 0;if(typeof i=="object"&&i!==null){r=i;continue}let c={};Object.defineProperty(r,s,{value:c,enumerable:!0,configurable:!0,writable:!0}),r=c}},ih=e=>or.parse({items:e.rows.map(t=>{let n={};for(let[r,o]of e.fields.entries())sh({item:n,field:o,value:t[r]});return n}),totalCount:e.totalCount,hasMore:e.hasMore}),wf=async({queries:e,query:t})=>{if(e===void 0)return;let n=e[await oh(rt.parse(t))];return n===void 0?void 0:ih(n)};var ch=(e,t)=>t===void 0?Ot(e):{async*[Symbol.asyncIterator](){let n=0,r=0;for await(let o of Ot(e)){if(r===t.length)return;if(n+o.byteLength<=t.offset){n+=o.byteLength;continue}let s=Math.max(0,t.offset-n),i=Math.min(o.byteLength-s,t.length-r);i>0&&(yield o.subarray(s,s+i),r+=i),n+=o.byteLength}}},ah=({graph:e,load:t,signal:n})=>{let r=new Map(e.nodes.map(o=>[o.contentRef,o]));return async(o,s)=>{let i=r.get(o);if(i===void 0)throw new Error(`Document content reference ${o} is unavailable`);let c=Qt({node:i,source:await t(i,{signal:n})});return{data:ch(c.source,s),...s===void 0?{}:{contentLength:s.length}}}},uh=({artifact:e,revision:t,catalog:n,documentGraph:r,inlineDocuments:o,readContent:s})=>{let i=async(a,u,d,l)=>{if(a.indexRevision!==void 0&&a.indexRevision!==t)throw new qt;let f=l?.skipMaterialized===!0?void 0:await wf({queries:e.queries,query:a.query});if(f!==void 0)return f;let p=async(m,h)=>{let b=e.contents?.[m];if(b===void 0){let w=u??s;if(w===void 0)throw new Error("Content is not embedded in this database");return await w(m,h)}let _=It(b),x=h===void 0?_:_.slice(h.offset,h.offset+h.length);return{data:async function*(){yield x}(),contentLength:x.byteLength}};return await bf({query:a.query,catalog:n,documents:l?.documents??e.documents,read:p,runtimeAssets:d,assetReferences:e.assetReferences})};return{query:async(...a)=>await i(...a),queryWithDocumentGraph:async({request:a,load:u,readContent:d,runtimeAssets:l,signal:f,onEvent:p})=>{if(r===void 0)return await i(a,d,l);let y=d??ah({graph:r,load:u,signal:f}),m=rt.parse(a.query),h=new Map(e.documents.map(v=>[v._id,v])),b=sf({graph:r,query:m}).filter(v=>{let R=h.get(v);return R===void 0?!1:Dt(m.where,E=>{if(!of({graph:r,sourceId:v,field:E.field}))return xs(R,E,l?.[v])})!==!1});if(b.length===0)return await i(a,y,l);let _=cf({graph:r,query:m,rootIds:b});re(p,{type:"roots-selected",rootCount:b.length});let x=await Hl({graph:_,rootIds:b,load:async(v,R)=>{let E=o?.get(v.id);return E!==void 0?{format:"json",revision:v.revision,source:JSON.stringify(E.properties)}:await u(v,R)},concurrency:D.concurrentContentReads,signal:f,onEvent:p,allowUnresolvedReferences:!0}),w=new Map(b.flatMap((v,R)=>{let E=Ql(x.roots[R]);return E===void 0?[]:[[v,E]]})),S=e.documents.map(v=>{let R=w.get(v._id);return R===void 0?v:Fo.parse({...v,properties:R})});return await i(a,y,l,{documents:S,skipMaterialized:!0})}}};var Es=({artifact:e,readContent:t})=>{let n=af({artifact:e});return uh({artifact:e,revision:e.revision,documentGraph:n?.graph,inlineDocuments:n?.inlineDocuments,readContent:t})};var Kr=class extends Error{constructor(t,n){super(t,n),this.name="AssetQueryRequestError"}},Nn=class extends Error{},lh=async(e,t)=>{if(Number.isSafeInteger(t)===!1||t<0)throw new TypeError("Request byte limit must be a non-negative integer");let n=Number(e.headers.get("content-length"));if(Number.isFinite(n)&&n>t)throw new Nn("Request exceeds the byte limit");let r=e.body?.getReader(),o=[],s=0;if(r!==void 0)for(;;){let{done:a,value:u}=await r.read();if(a)break;if(s+=u.byteLength,s>t){try{await r.cancel()}catch{}throw new Nn("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},_f=async e=>{let t;try{t=await lh(e,D.requestBytes)}catch(n){throw n instanceof Nn?new Kr("Asset query request exceeds the byte limit",{cause:n}):n}try{return Fu.parse(JSON.parse(ae(t)))}catch(n){throw new Kr("Asset query request is invalid",{cause:n})}};var xf=e=>{if(e instanceof qt)return{code:"STALE_INDEX",message:e.message,retryable:!1,status:409};if(e instanceof qe)return{code:"INVALID_REQUEST",message:e.message,retryable:!1,status:400};if(e instanceof oe)return{code:e.code,message:e.message,retryable:!1,details:e.details,status:400};let t=new Set,n=e;for(;n!==void 0&&t.has(n)===!1;){if(n instanceof bt){let r={};for(let[o,s]of Object.entries({assetId:n.documentId,documentCount:n.documentCount,documentLimit:n.documentLimit,contentByteLimit:n.contentByteLimit,totalBytes:n.totalBytes,totalByteLimit:n.totalByteLimit}))s!==void 0&&(r[o]=s);return{code:"CONTENT_LIMIT_EXCEEDED",message:n.message,retryable:!1,details:r,status:400}}if(n instanceof Rn)return{code:"CONTENT_LIMIT_EXCEEDED",message:n.message,retryable:!1,details:{assetId:n.documentId,contentByteLimit:n.contentByteLimit},status:400};t.add(n),n=n instanceof Error?n.cause:void 0}};var fh="/$resources/assets",Ef=(e,t=200)=>new Response(JSON.stringify(e),{status:t,headers:{"content-type":"application/json; charset=utf-8"}}),Cn=({code:e,message:t,status:n,retryable:r=!1,details:o})=>Ef(Bu({code:e,message:t,retryable:r,details:o}),n),dh=(e,t,n)=>typeof e=="string"||e instanceof URL?new Request(new URL(e,t),n):new Request(e,n),ph=async({deploymentId:e,artifact:t,request:n})=>{let r=await n.clone().text(),o=n.headers.get("cache-control"),s=await Lo(JSON.stringify([e,t.revision,r,o])),i=new URL(n.url);return i.searchParams.set("ws-asset-resource",s),new Request(i,{method:"GET"})},Fk=({deploymentId:e,artifact:t,runtimeAssets:n,cache:r,baseUrl:o,fetchDocument:s=globalThis.fetch,onDocumentGraphEvent:i})=>{vf({artifact:t,runtimeAssets:n});let c=Sf();return kf({deploymentId:e,artifact:t,runtimeAssets:n,cache:r,baseUrl:o,database:Es({artifact:t}),fetchDocument:s,documentCache:c,onDocumentGraphEvent:i})},Sf=()=>{let e=new Map,t=D.hydratedTotalBytes*4,n=0;return{get:async r=>{let o=e.get(r);return o!==void 0&&(e.delete(r),e.set(r,o)),o},set:async(r,o)=>{if(o.bytes.byteLength>t)return;let s=e.get(r);for(s!==void 0&&(n-=s.bytes.byteLength,e.delete(r)),e.set(r,o),n+=o.bytes.byteLength;n>t;){let i=e.entries().next().value;if(i===void 0)break;e.delete(i[0]),n-=i[1].bytes.byteLength}}}},mh=({baseUrl:e,runtimeAssets:t,fetchDocument:n,cache:r,onEvent:o})=>Yl({cache:r,onEvent:o,load:Kl({fetch:n,getRequest:s=>{let i=t[s.id];if(i===void 0)throw new Error(`Published document URL is unavailable for ${s.id}`);return new URL(i.url,e)},getMetadata:({node:s})=>({format:s.format,revision:s.revision}),onEvent:o})}),vf=({artifact:e,runtimeAssets:t})=>{let n=Object.values(e.assetReferences??{}).flat().map(({assetId:s})=>s).find(s=>t[s]===void 0);if(n!==void 0)throw new Error(`Published referenced asset URL is unavailable for ${n}`);let r=e.documentGraph?.nodes.find(({id:s})=>t[s]===void 0)?.id;if(r!==void 0)throw new Error(`Published document URL is unavailable for ${r}`);let o=e.documentGraph?.nodes.find(({id:s,contentRef:i})=>t[s]?.contentRef!==i)?.id;if(o!==void 0)throw new Error(`Published document identity does not match graph node ${o}`)},kf=({deploymentId:e,artifact:t,runtimeAssets:n,cache:r,baseUrl:o,database:s,fetchDocument:i,documentCache:c,onDocumentGraphEvent:a})=>{let u=new URL(o).origin,d=mh({baseUrl:o,runtimeAssets:n,fetchDocument:i,cache:c,onEvent:a});return async(l,f)=>{let p=dh(l,o,f),y=new URL(p.url);if(y.origin!==u||y.pathname!==fh||p.method.toUpperCase()!=="POST")return;let m;try{m=await _f(p.clone())}catch{return Cn({code:"INVALID_REQUEST",message:"Asset resource request is invalid",status:400})}let h=r===void 0||p.headers.has("cache-control")===!1?void 0:await ph({deploymentId:e,artifact:t,request:p});if(h!==void 0&&r!==void 0){let b=await r.match(h).catch(()=>{});if(b!==void 0)return new Response(b.body,b)}try{if(p.signal.aborted)return Cn({code:"REQUEST_CANCELLED",message:"Published asset query was cancelled",status:499});let b=Ef(await s.queryWithDocumentGraph({request:m,load:d,runtimeAssets:n,signal:p.signal,onEvent:a}));return h!==void 0&&r!==void 0&&p.signal.aborted===!1&&(b.headers.set("cache-control",p.headers.get("cache-control")),await r.put(h,b.clone()).catch(()=>{})),b}catch(b){if(p.signal.aborted)return Cn({code:"REQUEST_CANCELLED",message:"Published asset query was cancelled",status:499});let _=xf(b);return Cn(_!==void 0?_:{code:"INTERNAL_ERROR",message:"Published asset query failed",status:500,retryable:!0})}}},Bk=({deploymentId:e,artifact:t,runtimeAssets:n,onDocumentGraphEvent:r=void 0})=>{let o=globalThis.caches,s,i=()=>(s??=o.open(`webstudio-assets-${e}`),s),c=o===void 0?void 0:{match:async d=>(await i()).match(d),put:async(d,l)=>(await i()).put(d,l)};vf({artifact:t,runtimeAssets:n});let a=Es({artifact:t}),u=Sf();return async({request:d,fallback:l})=>{let f=new URL(d.url).origin,p=kf({deploymentId:e,artifact:t,runtimeAssets:n,cache:c,baseUrl:f,database:a,fetchDocument:l,documentCache:u,onDocumentGraphEvent:r});return async(y,m)=>await p(y,m)??l(y,m)}};export{Bk as createGeneratedAssetResourceRuntime,Fk as createPublishedAssetResourceFetch};
diff --git a/fixtures/webstudio-features/app/__generated__/$resources.assets.ts b/fixtures/webstudio-features/app/__generated__/$resources.assets.ts
index 82986429f6..aaac82aeb9 100644
--- a/fixtures/webstudio-features/app/__generated__/$resources.assets.ts
+++ b/fixtures/webstudio-features/app/__generated__/$resources.assets.ts
@@ -1,34 +1,41 @@
export const assets = {
"2b151fc7b4b0324e6ab78c40f72c7f59273f81fb1be3d08b3f9976428601b95e": {
- "url": "/assets/e-mail-39993_vrxyjxQv3j67Krs62Vz7Y.mp3"
+ "url": "/assets/e-mail-39993_vrxyjxQv3j67Krs62Vz7Y.mp3",
+ "contentRef": "e-mail-39993_vrxyjxQv3j67Krs62Vz7Y.mp3"
},
"42e55b0464790758b9352d675cf28fadfcf8a3259fc1e890100617d3e731be88": {
"url": "/assets/cabinsketch-bold_TLCbytfxf8ENHwZ6ze3Jj.ttf",
"family": "CabinSketch",
"style": "normal",
- "weight": 700
+ "weight": 700,
+ "contentRef": "cabinsketch-bold_TLCbytfxf8ENHwZ6ze3Jj.ttf"
},
"4afe692f78ec0530e355a551a3860302c4478037db7b25a3bdae82c32c78634d": {
- "url": "/assets/webm-example_2r_6VmRBjhAy3ldaqz0gk.webm"
+ "url": "/assets/webm-example_2r_6VmRBjhAy3ldaqz0gk.webm",
+ "contentRef": "webm-example_2r_6VmRBjhAy3ldaqz0gk.webm"
},
"7cf5892080fa66b5e6175ffd2d27c304ee6b09ce1f21847a95000225ad1afa59": {
"url": "/assets/cat_silhouette_BDpTbUFSpVbfUWQZNxbBG.png",
"width": 790,
- "height": 786
+ "height": 786,
+ "contentRef": "cat_silhouette_BDpTbUFSpVbfUWQZNxbBG.png"
},
"9a8bc926-7804-4d3f-af81-69196b1d2ed8": {
"url": "/assets/small-avif-kitty_FnabJsioMWpBtXZSGf4DR.webp",
"width": 100,
- "height": 100
+ "height": 100,
+ "contentRef": "small-avif-kitty_FnabJsioMWpBtXZSGf4DR.webp"
},
"cbf6b1b052e52b256cef54a032a546bf43bf3f5441be4d1c5eeaabce26903d78": {
- "url": "/assets/video_QamtUWsD-ShifhzZLoNIv_ald_1xtyEb3uHhFb7nCQa.mp4"
+ "url": "/assets/video_QamtUWsD-ShifhzZLoNIv_ald_1xtyEb3uHhFb7nCQa.mp4",
+ "contentRef": "video_QamtUWsD-ShifhzZLoNIv_ald_1xtyEb3uHhFb7nCQa.mp4"
},
"cd939c56-bcdd-4e64-bd9c-567a9bccd3da": {
"url": "/assets/_937084ed-a798-49fe-8664-df93a2af605e_uiBk3o6UWdqolyakMvQJ9.jpeg",
"width": 1024,
- "height": 1024
+ "height": 1024,
+ "contentRef": "_937084ed-a798-49fe-8664-df93a2af605e_uiBk3o6UWdqolyakMvQJ9.jpeg"
}
};
\ No newline at end of file
diff --git a/packages/asset-uploader/src/asset-repository.test.ts b/packages/asset-uploader/src/asset-repository.test.ts
index d7108c0225..5e24626d4a 100644
--- a/packages/asset-uploader/src/asset-repository.test.ts
+++ b/packages/asset-uploader/src/asset-repository.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test, vi } from "vitest";
+import { beforeEach, describe, expect, test, vi } from "vitest";
import type { AppContext } from "@webstudio-is/trpc-interface/index.server";
import type { AssetObjectStore } from "./client";
import { createUploadTicket, uploadFile } from "./upload";
@@ -9,8 +9,10 @@ import {
import { loadCanonicalAssetFileEntries } from "./canonical-metadata-persistence";
import {
createContentCompilationPlan,
+ createContentRuntimeArtifact,
createLiteralContentCompilationQuery,
assetQuery,
+ serializeContentArtifact,
type AssetQueryInput,
type AssetFileDocument,
} from "@webstudio-is/content-engine";
@@ -44,6 +46,23 @@ const assetClient: AssetObjectStore = {
uploadFile: vi.fn(),
};
+beforeEach(() => {
+ vi.mocked(assetClient.readFile)
+ .mockReset()
+ .mockImplementation(async (name, range) => {
+ const length = range?.length ?? 2;
+ const content = name.endsWith(".json")
+ ? length === 1
+ ? "0"
+ : "{}".padEnd(length)
+ : " ".repeat(length);
+ return {
+ data: new Blob([content]).stream(),
+ contentLength: length,
+ };
+ });
+});
+
const createCompilationPlan = (query: AssetQueryInput) => {
const plan = createContentCompilationPlan([
createLiteralContentCompilationQuery({
@@ -496,6 +515,7 @@ describe("PostgresAssetRepository", () => {
projectId: "project-1",
entries,
assetReferences: {},
+ documentGraph: undefined,
maxBytes: 500 * 1024,
});
});
@@ -1263,10 +1283,13 @@ describe("PostgresAssetRepository", () => {
},
},
},
- createCompilationPlan({
- where: { all: [] },
- output: { mode: "all", includeMetadata: true },
- })
+ {
+ databasePlan: createCompilationPlan({
+ where: { all: [] },
+ output: { mode: "all", includeMetadata: true },
+ }),
+ includeUnresolvedDiagnostics: true,
+ }
);
expect(dependencies.synchronizeCanonicalAssets).toHaveBeenCalledWith({
@@ -1283,6 +1306,7 @@ describe("PostgresAssetRepository", () => {
]);
expect(result.__diagnostics__).toMatchObject({
scope: "query-preview",
+ unresolved: result.data,
query: {
includedDocumentCount: 1,
omittedDocumentCount: 0,
@@ -1316,6 +1340,7 @@ describe("PostgresAssetRepository", () => {
expect(urlResult.data.items).toEqual([
{ id: "asset-1", url: "/cgi/asset/post.md?format=raw" },
]);
+ expect(urlResult.__diagnostics__.unresolved).toBeUndefined();
expect(dependencies.loadAssetsByProjectWithClient).toHaveBeenCalledWith(
"project-1",
context.postgrest.client,
@@ -1346,10 +1371,10 @@ describe("PostgresAssetRepository", () => {
);
expect(dependencies.loadAssetsByProjectWithClient).not.toHaveBeenCalled();
- vi.mocked(assetClient.readFile).mockResolvedValue({
+ vi.mocked(assetClient.readFile).mockImplementation(async () => ({
data: new Blob(["# New post"]).stream(),
contentLength: 10,
- });
+ }));
const publishedIndex = await repository.prepareIndex(
createCompilationPlan({
where: {
@@ -1367,7 +1392,7 @@ describe("PostgresAssetRepository", () => {
const publishedFetch = createPublishedAssetResourceFetch({
baseUrl: "https://blog.example",
deploymentId: "deployment-1",
- artifact: publishedIndex,
+ artifact: createContentRuntimeArtifact(publishedIndex),
runtimeAssets: { "asset-1": { url: "/assets/post.md" } },
});
const publishedResponse = await publishedFetch("/$resources/assets", {
@@ -1396,4 +1421,223 @@ describe("PostgresAssetRepository", () => {
],
});
});
+
+ test("assembles document graph references in local query preview", async () => {
+ const dependencies = createDependencies();
+ const postSource =
+ '{"title":"Hello","author":{"$ref":"./author.md#frontmatter"}}';
+ const authorSource = "---\nname: Ada\nrole: Writer\n---\nBio\n";
+ const createEntry = ({
+ id,
+ name,
+ source,
+ properties,
+ }: {
+ id: string;
+ name: string;
+ source: string;
+ properties: AssetFileDocument["properties"];
+ }): CanonicalAssetFileEntry => ({
+ projectId: "project-1",
+ assetId: id,
+ revision: `${id}-r1`,
+ document: {
+ _id: id,
+ _type: "asset.file",
+ name,
+ path: `content/${name}`,
+ key: name.slice(0, name.lastIndexOf(".")),
+ extension: name.endsWith(".json") ? "json" : "md",
+ mimeType: name.endsWith(".json")
+ ? "application/json"
+ : "text/markdown; charset=utf-8",
+ size: new TextEncoder().encode(source).byteLength,
+ revision: `${id}-r1`,
+ contentRef: `storage:${id}`,
+ properties,
+ },
+ });
+ const entries = [
+ createEntry({
+ id: "post",
+ name: "post.json",
+ source: postSource,
+ properties: {
+ title: "Hello",
+ author: { $ref: "./author.md#frontmatter" },
+ },
+ }),
+ createEntry({
+ id: "author",
+ name: "author.md",
+ source: authorSource,
+ properties: { name: "Ada", role: "Writer" },
+ }),
+ ];
+ dependencies.loadCanonicalAssetBaseEntries.mockResolvedValue(entries);
+ dependencies.loadCanonicalAssetFileEntries.mockResolvedValue(entries);
+ dependencies.createAssetIndex.mockImplementation(createAssetIndex);
+ const readFile = vi.fn(async (contentRef: string) => {
+ const source = contentRef === "storage:post" ? postSource : authorSource;
+ return {
+ data: new Blob([source]).stream(),
+ contentLength: new TextEncoder().encode(source).byteLength,
+ };
+ });
+ const events: unknown[] = [];
+ const repository = new PostgresAssetRepository({
+ projectId: "project-1",
+ context,
+ assetStore: { readFile },
+ dependencies,
+ onDocumentGraphEvent: (event) => events.push(event),
+ });
+
+ const result = await repository.query(
+ {
+ query: {
+ where: { all: [{ field: ["id"], operator: "eq", value: "post" }] },
+ limit: 1,
+ output: {
+ mode: "fields",
+ includeMetadata: false,
+ fields: [
+ ["properties", "title"],
+ ["properties", "author"],
+ ],
+ },
+ },
+ },
+ { includeUnresolvedDiagnostics: true }
+ );
+
+ expect(result.data.items).toEqual([
+ {
+ id: "post",
+ properties: {
+ title: "Hello",
+ author: { name: "Ada", role: "Writer" },
+ },
+ },
+ ]);
+ expect(result.__diagnostics__.unresolved?.items).toEqual([
+ {
+ id: "post",
+ properties: {
+ title: "Hello",
+ author: { $ref: "./author.md#frontmatter" },
+ },
+ },
+ ]);
+ expect(result.__diagnostics__.artifacts).toEqual({
+ query: expect.objectContaining({ format: "webstudio-content-database" }),
+ database: expect.objectContaining({
+ format: "webstudio-content-database",
+ }),
+ });
+ const artifacts = result.__diagnostics__.artifacts;
+ if (artifacts === undefined) {
+ throw new Error("Expected database artifacts in diagnostics");
+ }
+ expect(
+ new TextEncoder().encode(serializeContentArtifact(artifacts.query))
+ .byteLength
+ ).toBe(result.__diagnostics__.query.unboundedBytes);
+ expect(
+ new TextEncoder().encode(serializeContentArtifact(artifacts.database))
+ .byteLength
+ ).toBe(result.__diagnostics__.database.unboundedBytes);
+ expect(events).toEqual(
+ expect.arrayContaining([
+ { type: "roots-selected", rootCount: 1 },
+ { type: "resolution-started", rootCount: 1, documentCount: 2 },
+ {
+ type: "document-fetch-started",
+ documentId: "post",
+ revision: "post-r1",
+ },
+ {
+ type: "document-fetch-completed",
+ documentId: "author",
+ revision: "author-r1",
+ },
+ { type: "resolution-completed", rootCount: 1, documentCount: 2 },
+ ])
+ );
+ });
+
+ test("keeps deferred Markdown out of unresolved query diagnostics", async () => {
+ const dependencies = createDependencies();
+ const source = "---\nslug: post\ntitle: Post\n---\nStored body\n";
+ const entry: CanonicalAssetFileEntry = {
+ projectId: "project-1",
+ assetId: "post",
+ revision: "post-r1",
+ document: {
+ _id: "post",
+ _type: "asset.file",
+ name: "post.md",
+ path: "content/post.md",
+ key: "post",
+ extension: "md",
+ mimeType: "text/markdown; charset=utf-8",
+ size: new TextEncoder().encode(source).byteLength,
+ revision: "post-r1",
+ contentRef: "storage:post",
+ properties: { slug: "post", title: "Post" },
+ },
+ };
+ dependencies.loadCanonicalAssetBaseEntries.mockResolvedValue([entry]);
+ dependencies.loadCanonicalAssetFileEntries.mockResolvedValue([entry]);
+ dependencies.createAssetIndex.mockImplementation(createAssetIndex);
+ const readFile = vi.fn(async () => ({
+ data: new Blob([source]).stream(),
+ contentLength: entry.document.size,
+ }));
+ const repository = new PostgresAssetRepository({
+ projectId: "project-1",
+ context,
+ assetStore: { readFile },
+ dependencies,
+ });
+
+ const result = await repository.query(
+ {
+ query: {
+ where: {
+ all: [
+ {
+ field: ["properties", "slug"],
+ operator: "eq",
+ value: "post",
+ },
+ ],
+ },
+ limit: 1,
+ output: {
+ mode: "fields",
+ includeMetadata: false,
+ fields: [["properties", "title"]],
+ },
+ content: { mode: "markdown-body" },
+ },
+ },
+ { includeUnresolvedDiagnostics: true }
+ );
+
+ expect(result.data.items).toEqual([
+ {
+ id: "post",
+ properties: { title: "Post" },
+ content: { encoding: "utf-8", text: "Stored body\n" },
+ },
+ ]);
+ expect(result.__diagnostics__.unresolved?.items).toEqual([
+ { id: "post", properties: { title: "Post" } },
+ ]);
+ expect(result.__diagnostics__.artifacts?.query.contents).toBeUndefined();
+ expect(result.__diagnostics__.artifacts?.query.documentGraph).toMatchObject(
+ { nodes: [{ id: "post", format: "markdown" }], edges: [] }
+ );
+ });
});
diff --git a/packages/asset-uploader/src/asset-repository.ts b/packages/asset-uploader/src/asset-repository.ts
index 6b5adaf214..be8282fe54 100644
--- a/packages/asset-uploader/src/asset-repository.ts
+++ b/packages/asset-uploader/src/asset-repository.ts
@@ -5,6 +5,7 @@ import {
createContentFieldCatalogCompilationPlan,
createLiteralContentCompilationQuery,
getContentArtifactRuntimeAssetIds,
+ getDocumentFormatByContentType,
isContentDocumentCandidate,
prepareContentCompilerEntries,
requiresRuntimeDocumentData,
@@ -13,6 +14,8 @@ import {
type AssetQueryPreviewResult,
type BuilderAssetFieldCatalog,
type ContentCompilationPlan,
+ type DocumentGraphRuntimeObserver,
+ observeDocumentSourceLoader,
} from "@webstudio-is/content-engine";
import {
createAssetIndex,
@@ -129,6 +132,11 @@ export type AssetContentRead = {
contentLength?: number;
};
+type AssetQueryPreviewOptions = {
+ databasePlan?: ContentCompilationPlan;
+ includeUnresolvedDiagnostics?: boolean;
+};
+
export interface AssetRepository {
list(): Promise<Asset[]>;
get(assetId: Asset["id"]): Promise<Asset>;
@@ -172,7 +180,7 @@ export interface AssetRepository {
readFieldCatalog(): Promise<BuilderAssetFieldCatalog>;
query(
request: AssetQueryRequestInput,
- databasePlan?: ContentCompilationPlan
+ options?: AssetQueryPreviewOptions
): Promise<AssetQueryPreviewResult>;
}
@@ -192,6 +200,7 @@ export class PostgresAssetRepository implements AssetRepository {
private readonly dependencies: AssetRepositoryDependencies;
private readonly contentDatabaseMaxBytes: number;
private readonly compilationCache: ContentCompilationCache | undefined;
+ private readonly onDocumentGraphEvent?: DocumentGraphRuntimeObserver;
constructor({
projectId,
@@ -200,6 +209,7 @@ export class PostgresAssetRepository implements AssetRepository {
dependencies,
contentDatabaseMaxBytes = contentEngineLimits.databaseBytes,
compilationCache,
+ onDocumentGraphEvent,
}: {
projectId: string;
context: AppContext;
@@ -207,6 +217,7 @@ export class PostgresAssetRepository implements AssetRepository {
dependencies?: Partial<AssetRepositoryDependencies>;
contentDatabaseMaxBytes?: number;
compilationCache?: ContentCompilationCache;
+ onDocumentGraphEvent?: DocumentGraphRuntimeObserver;
}) {
this.projectId = projectId;
this.context = context;
@@ -216,6 +227,7 @@ export class PostgresAssetRepository implements AssetRepository {
this.compilationCache =
compilationCache ??
(dependencies === undefined ? sharedContentCompilationCache : undefined);
+ this.onDocumentGraphEvent = onDocumentGraphEvent;
}
static async forUpload({
@@ -547,22 +559,27 @@ export class PostgresAssetRepository implements AssetRepository {
const source = this.createContentSource(strict);
const compile = async (
entries: Parameters<typeof createAssetIndex>[0]["entries"],
- assetReferences: Parameters<typeof createAssetIndex>[0]["assetReferences"]
+ assetReferences: Parameters<
+ typeof createAssetIndex
+ >[0]["assetReferences"],
+ documentGraph: Parameters<typeof createAssetIndex>[0]["documentGraph"]
) =>
await this.dependencies.createAssetIndex({
projectId: this.projectId,
entries,
assetReferences,
+ documentGraph,
maxBytes: this.contentDatabaseMaxBytes,
...(requirements === undefined ? {} : { plan: requirements }),
});
if (this.compilationCache === undefined) {
- const { entries, assetReferences } = await materializeContentSource({
- source,
- plan: requirements,
- maximumContentBytes: this.contentDatabaseMaxBytes,
- });
- return await compile(entries, assetReferences);
+ const { entries, assetReferences, documentGraph } =
+ await materializeContentSource({
+ source,
+ plan: requirements,
+ maximumContentBytes: this.contentDatabaseMaxBytes,
+ });
+ return await compile(entries, assetReferences, documentGraph);
}
for (let attempt = 0; attempt < 2; attempt += 1) {
const snapshot = await source.openSnapshot();
@@ -575,14 +592,13 @@ export class PostgresAssetRepository implements AssetRepository {
});
try {
return await this.compilationCache.getOrCreate(key, async () => {
- const { entries, assetReferences } = await materializeContentSnapshot(
- {
+ const { entries, assetReferences, documentGraph } =
+ await materializeContentSnapshot({
snapshot,
plan: requirements,
maximumContentBytes: this.contentDatabaseMaxBytes,
- }
- );
- return await compile(entries, assetReferences);
+ });
+ return await compile(entries, assetReferences, documentGraph);
});
} catch (error) {
if (error instanceof ContentSourceChangedError === false) {
@@ -594,6 +610,7 @@ export class PostgresAssetRepository implements AssetRepository {
}
private createContentSource(strict: boolean): ContentSource {
+ const readFile = this.assetStore.readFile;
const loadBaseEntries = () =>
this.dependencies.loadCanonicalAssetBaseEntries({
client: this.context.postgrest.client,
@@ -606,6 +623,40 @@ export class PostgresAssetRepository implements AssetRepository {
return {
revision,
files: baseEntries.map(createContentSourceFile),
+ loadDocumentSources: async () =>
+ baseEntries.flatMap((entry) => {
+ if (
+ getDocumentFormatByContentType(entry.document.mimeType) ===
+ undefined
+ ) {
+ return [];
+ }
+ return [
+ {
+ id: entry.assetId,
+ source: {
+ [Symbol.asyncIterator]: async function* () {
+ const response = await readFile(
+ entry.document.contentRef,
+ entry.document.size === 0
+ ? undefined
+ : { offset: 0, length: entry.document.size }
+ );
+ let readBytes = 0;
+ for await (const chunk of response.data) {
+ readBytes += chunk.byteLength;
+ yield chunk;
+ }
+ if (readBytes !== entry.document.size) {
+ throw new Error(
+ "Asset content does not match its canonical size"
+ );
+ }
+ },
+ },
+ },
+ ];
+ }),
loadEntries: (plan, options) =>
this.loadCompilerEntries({
baseEntries,
@@ -713,7 +764,10 @@ export class PostgresAssetRepository implements AssetRepository {
async query(
request: AssetQueryRequestInput,
- databasePlan?: ContentCompilationPlan
+ {
+ databasePlan,
+ includeUnresolvedDiagnostics = false,
+ }: AssetQueryPreviewOptions = {}
): Promise<AssetQueryPreviewResult> {
await this.assertCanView();
const query = assetQuery.parse(request.query);
@@ -722,15 +776,15 @@ export class PostgresAssetRepository implements AssetRepository {
]);
const index = await this.prepareIndexAfterAuthorization(plan, false);
const database = getContentDatabaseForArtifact(index);
- const publishedDatabase =
+ const publishedIndex =
databasePlan === undefined
- ? database
- : getContentDatabaseForArtifact(
- await this.prepareIndexAfterAuthorization(databasePlan, false)
- );
+ ? index
+ : await this.prepareIndexAfterAuthorization(databasePlan, false);
+ const publishedDatabase = getContentDatabaseForArtifact(publishedIndex);
const runtimeAssetIds = getContentArtifactRuntimeAssetIds({
artifact: index,
includeDocuments: plan !== undefined && requiresRuntimeDocumentData(plan),
+ includeDocumentGraph: false,
});
const runtimeAssets =
runtimeAssetIds.length > 0
@@ -747,11 +801,35 @@ export class PostgresAssetRepository implements AssetRepository {
])
)
: undefined;
- const data = await database.query(
+ const unresolved = includeUnresolvedDiagnostics
+ ? await database.query(
+ query.content.mode === "none"
+ ? request
+ : { ...request, query: { ...query, content: { mode: "none" } } },
+ undefined,
+ runtimeAssets
+ )
+ : undefined;
+ const data = await database.queryWithDocumentGraph({
request,
- this.assetStore.readFile,
- runtimeAssets
- );
+ readContent: this.assetStore.readFile,
+ runtimeAssets,
+ load: observeDocumentSourceLoader({
+ onEvent: this.onDocumentGraphEvent,
+ load: async (node) => {
+ if (node.format === undefined) {
+ throw new Error(`Document ${node.id} format is unavailable`);
+ }
+ const response = await this.assetStore.readFile(node.contentRef);
+ return {
+ format: node.format,
+ revision: node.revision,
+ source: response.data,
+ };
+ },
+ }),
+ onEvent: this.onDocumentGraphEvent,
+ });
const toCapacityStats = ({
usedBytes,
maxBytes,
@@ -773,6 +851,10 @@ export class PostgresAssetRepository implements AssetRepository {
scope: "query-preview",
query: toCapacityStats(database.getStats()),
database: toCapacityStats(publishedDatabase.getStats()),
+ ...(includeUnresolvedDiagnostics
+ ? { artifacts: { query: index, database: publishedIndex } }
+ : {}),
+ ...(unresolved === undefined ? {} : { unresolved }),
},
};
}
diff --git a/packages/asset-uploader/src/query-preview.ts b/packages/asset-uploader/src/query-preview.ts
index 4e07e20ae7..6de4588d2b 100644
--- a/packages/asset-uploader/src/query-preview.ts
+++ b/packages/asset-uploader/src/query-preview.ts
@@ -1,6 +1,7 @@
import {
type AssetQueryRequestInput,
type ContentCompilationPlan,
+ type DocumentGraphRuntimeObserver,
} from "@webstudio-is/content-engine";
import type { AssetObjectStore } from "./client";
import type { AppContext } from "@webstudio-is/trpc-interface/index.server";
@@ -13,6 +14,8 @@ export const previewAssetResourceQuery = async ({
assetClient,
contentDatabaseMaxBytes,
databasePlan,
+ includeUnresolvedDiagnostics,
+ onDocumentGraphEvent,
}: {
projectId: string;
request: AssetQueryRequestInput;
@@ -20,12 +23,18 @@ export const previewAssetResourceQuery = async ({
assetClient: Pick<AssetObjectStore, "readFile">;
contentDatabaseMaxBytes?: number;
databasePlan?: ContentCompilationPlan;
+ includeUnresolvedDiagnostics?: boolean;
+ onDocumentGraphEvent?: DocumentGraphRuntimeObserver;
}) => {
const repository = new PostgresAssetRepository({
projectId,
context,
assetStore: assetClient,
contentDatabaseMaxBytes,
+ onDocumentGraphEvent,
+ });
+ return await repository.query(request, {
+ databasePlan,
+ includeUnresolvedDiagnostics,
});
- return await repository.query(request, databasePlan);
};
diff --git a/packages/cli/evaluations/high-impact/agent-runner.test.ts b/packages/cli/evaluations/high-impact/agent-runner.test.ts
index 80baaf15ce..7ffcfcfbc2 100644
--- a/packages/cli/evaluations/high-impact/agent-runner.test.ts
+++ b/packages/cli/evaluations/high-impact/agent-runner.test.ts
@@ -4,7 +4,11 @@ import { join, resolve } from "node:path";
import { describe, expect, test } from "vitest";
import { authenticatedPageFixture } from "./fixtures";
import { designInputFixture } from "./fixtures";
-import { fontAssetsFixture, markdownBlogFixture } from "./fixtures";
+import {
+ fontAssetsFixture,
+ markdownBlogFixture,
+ markdownReferencesDiscoveryFixture,
+} from "./fixtures";
import {
createMinimalAgentTask,
getFixtureToolNames,
@@ -112,6 +116,9 @@ describe("high-impact agent runner", () => {
expect.stringContaining("exactly one upload-assets call"),
expect.stringContaining("parallel tool-call batch"),
expect.stringContaining("verify-font-assets exactly once"),
+ expect.stringContaining(
+ 'audit exactly once with {"scopes":["assets"],"limit":10}'
+ ),
expect.stringContaining("Do not call refresh or get-asset separately"),
])
);
@@ -123,16 +130,33 @@ describe("high-impact agent runner", () => {
expect(blogConstraints).toContain("one upload-assets call");
expect(blogConstraints).toContain("aurora-trails.md");
expect(blogConstraints).toContain("city-walks.md");
+ expect(blogConstraints).toContain("Do not create or upload companion JSON");
+ expect(blogConstraints).toContain('"format":"md"');
expect(blogConstraints).toContain("/blog/:slug");
expect(blogConstraints).toContain(
'"field":["properties","draft"],"operator":"ne"'
);
- expect(blogConstraints).toContain('"value":"true"');
+ expect(blogConstraints).toContain(
+ '"value":{"type":"literal","value":true}'
+ );
+ expect(blogConstraints).toContain('"limit":{"type":"literal","value":20}');
+ expect(blogConstraints).toContain('"offset":{"type":"literal","value":0}');
expect(blogConstraints).toContain("Never call update-assets-resource");
+ expect(blogConstraints).toContain(
+ "Database size is part of the evaluated outcome"
+ );
+ expect(blogConstraints).toContain("one materialized overview");
+ expect(blogConstraints).toContain("zero embedded Markdown body bytes");
+ expect(blogConstraints).toContain("stale resource");
expect(blogConstraints).toContain(
'"fields":[["properties","title"],["properties","slug"]'
);
+ expect(blogConstraints).toContain('"mode":"none"');
expect(blogConstraints).toContain('"mode":"markdown-body"');
+ expect(blogConstraints).not.toContain('["properties","body"]');
+ expect(blogConstraints).toContain('["properties","author"]');
+ expect(blogConstraints).toContain("collectionItem.properties.author.name");
+ expect(blogConstraints).toContain("collectionItem.content.text");
expect(blogConstraints).toContain("$.MarkdownEmbed");
expect(blogConstraints).toContain(
"call verify-page-responsive exactly twice"
@@ -154,6 +178,34 @@ describe("high-impact agent runner", () => {
expect(getFixtureToolNames(markdownBlogFixture)).not.toContain(
"update-assets-resource"
);
+
+ const discoveryTask = createMinimalAgentTask(
+ markdownReferencesDiscoveryFixture,
+ {
+ kind: "source",
+ repositoryRoot: root,
+ }
+ );
+ const discoveryPrompt = JSON.stringify(discoveryTask);
+ expect(discoveryPrompt).not.toContain("$ref");
+ expect(discoveryPrompt).not.toContain('"where"');
+ expect(discoveryPrompt).not.toContain("markdown-body");
+ expect(discoveryPrompt).not.toContain("collectionItem");
+ expect(discoveryPrompt).toContain("Do not dry-run or plan mutations");
+ expect(discoveryPrompt).toContain("without reshaping its fields");
+ expect(discoveryPrompt).toContain(
+ 'exactly once with {\\"tools\\":[\\"create-assets-resource\\"]}'
+ );
+ expect(getFixtureToolNames(markdownReferencesDiscoveryFixture)).toEqual([
+ "meta.guide",
+ "meta.get_more_tools",
+ "create-asset-folder",
+ "upload-assets",
+ "create-page",
+ "create-assets-resource",
+ "insert-collection",
+ "verify-page-responsive",
+ ]);
});
test("retains only a bounded privacy-safe result from a real process", async () => {
diff --git a/packages/cli/evaluations/high-impact/agent-runner.ts b/packages/cli/evaluations/high-impact/agent-runner.ts
index 3f71df7c0d..5dde66e7c2 100644
--- a/packages/cli/evaluations/high-impact/agent-runner.ts
+++ b/packages/cli/evaluations/high-impact/agent-runner.ts
@@ -2,7 +2,7 @@ import { createHash } from "node:crypto";
import { mkdir, readFile, writeFile } from "node:fs/promises";
import { dirname, resolve } from "node:path";
import type { HighImpactFixture } from "./fixtures";
-import { markdownBlogFixtureArticles } from "./markdown-blog-fixture";
+import { markdownBlogFixtureDocuments } from "./markdown-blog-fixture";
import type {
EvaluationToolCall,
HighImpactEvaluationResult,
@@ -80,13 +80,23 @@ const fixtureToolNames = {
"insert-collection",
"verify-page-responsive",
],
+ "markdown-references-discovery-v1": [
+ "meta.guide",
+ "meta.get_more_tools",
+ "create-asset-folder",
+ "upload-assets",
+ "create-page",
+ "create-assets-resource",
+ "insert-collection",
+ "verify-page-responsive",
+ ],
} as const satisfies Record<HighImpactFixture["id"], readonly string[]>;
const markdownBlogUploadInput = JSON.stringify({
- assets: markdownBlogFixtureArticles.map(({ name }) => ({
+ assets: markdownBlogFixtureDocuments.map(({ name, format }) => ({
name,
type: "file",
- format: "md",
+ format,
folderId: "<blog-folder-id>",
meta: {},
})),
@@ -147,6 +157,13 @@ export const createMinimalAgentTask = (
'Then call verify-page-responsive exactly once with {"path":"/account","viewports":[{"width":1440,"height":900},{"width":390,"height":844}],"source":"session"}. It captures both required screenshots and runs the terminal static audit. Do not call preview.start, screenshot, screenshot.responsive, or audit separately.',
]
: []),
+ ...(fixture.id === "markdown-references-discovery-v1"
+ ? [
+ 'Follow the structured recipe returned by meta.guide. Pass each complete recipe object without reshaping its fields, changing only documented id placeholders. Call meta.get_more_tools exactly once with {"tools":["create-assets-resource"]}; do not search by brief or rediscover tools later.',
+ "Call each mutation in the documented workflow once as a committed mutation. Do not dry-run or plan mutations. If any tool fails, stop immediately and report the failure; never retry it, repair it with repeated mutations, or continue to verification.",
+ "Do not call verify-page-responsive until both Collections succeed. Then call it exactly once for /blog and exactly once for /blog/aurora-trails. Stop without retrying if either verification fails.",
+ ]
+ : []),
...(fixture.id === "design-input-v1"
? [
"For this fixture, do not call list-instances because the project has no representative existing page pattern. Do not call meta.index, meta.get_more_tools, or any other tool discovery operation because meta.guide and the MCP handshake already provide the required schemas.",
@@ -162,19 +179,20 @@ export const createMinimalAgentTask = (
? [
"Do not call meta.index, meta.get_more_tools, or any other tool discovery operation because meta.guide and the MCP handshake already provide the required schemas. Upload both supplied fonts together with exactly one upload-assets call; do not use upload-asset.",
'After upload, update both font assets together in one parallel tool-call batch. For each returned asset id, use exactly {"assetId":"<returned-asset-id>","values":{"meta":{"family":"Rajdhani","style":"normal","weight":600}}}. Keep family, style, and weight inside values.meta; do not send an empty values object. Make exactly two update-asset calls total and stop instead of retrying if either fails.',
- "After both updates, call verify-font-assets exactly once with both returned asset ids, then audit. Do not call refresh or get-asset separately.",
+ 'After both updates, call verify-font-assets exactly once with both returned asset ids, then call audit exactly once with {"scopes":["assets"],"limit":10}. Do not call refresh or get-asset separately.',
]
: []),
...(fixture.id === "markdown-blog-v1"
? [
- 'For this fixture, call meta.get_more_tools exactly once immediately after meta.guide with {"brief":"create-assets-resource"} to load the complete schema for its complex query input. Do not call meta.index, list/get/preview asset tools, list pages, or any other discovery operation. Then create one asset folder named Blog and upload all five supplied .md files together with exactly one upload-assets call using type file, format md, that returned folder id, empty metadata, and assetsDir .webstudio/assets.',
+ 'For this fixture, call meta.get_more_tools exactly once immediately after meta.guide with {"brief":"create-assets-resource"} to load the complete schema for its complex query input. Do not call meta.index, list/get/preview asset tools, list pages, or any other discovery operation. Then create one asset folder named Blog and upload all supplied Markdown files together with exactly one upload-assets call using type file, format md, that returned folder id, empty metadata, and assetsDir .webstudio/assets. Do not create or upload companion JSON descriptors.',
`Use this exact upload-assets input, substituting only the returned Blog folder id for <blog-folder-id>: ${markdownBlogUploadInput}.`,
"For this fixture, the exact sequence below supersedes every workflow and mutation meta.next suggestion. After a listed call succeeds, continue immediately to the next listed call without inspecting, repairing, updating, or repeating its result. If any call fails, stop immediately; retries and repair mutations fail this evaluation. Never call update-assets-resource or any tool not explicitly listed in these fixture constraints.",
"Create exactly two pages: first /blog, then /blog/:slug. Do not call create-assets-resource while creating either page. Never call create-assets-resource without a query. After both page calls succeed, make exactly two create-assets-resource calls total using the complete inputs below; any omitted query or additional resource fails this evaluation.",
- 'First call create-assets-resource exactly once with this complete overview input, substituting only the returned overview root id for scopeInstanceId: {"name":"Published posts","scopeInstanceId":"<overview-root-id>","dataSourceName":"posts","query":{"where":{"all":[{"field":["extension"],"operator":"eq","value":{"type":"literal","value":"md"}},{"field":["properties","draft"],"operator":"ne","value":"true"}]},"sort":[{"field":["properties","publishedAt"],"direction":"desc"},{"field":["id"],"direction":"asc"}],"limit":"20","output":{"mode":"fields","includeMetadata":false,"fields":[["properties","title"],["properties","slug"],["properties","publishedAt"],["excerpt"]]},"content":{"mode":"none"}}}. Do not convert expression strings to booleans or field paths to dotted strings.',
- 'Then call create-assets-resource exactly once with this complete detail input, substituting only the returned detail root id for scopeInstanceId: {"name":"Post by slug","scopeInstanceId":"<detail-root-id>","dataSourceName":"post","query":{"where":{"all":[{"field":["extension"],"operator":"eq","value":{"type":"literal","value":"md"}},{"field":["properties","slug"],"operator":"eq","value":"system.params.slug"}]},"limit":"1","output":{"mode":"fields","includeMetadata":false,"fields":[["properties","title"]]},"content":{"mode":"markdown-body","maxBytes":1048576}}}. Do not call create-assets-resource again.',
- 'After both resources succeed, call insert-collection exactly once on the overview root with {"parentInstanceId":"<overview-root-id>","data":{"type":"expression","value":"posts.data"},"itemFragment":"<ws.element ws:tag=\"article\"><ws.element ws:tag=\"h2\">{expression`collectionItem.properties.title ?? \\"Untitled\\"`}</ws.element><ws.element ws:tag=\"p\">{expression`collectionItem.excerpt ?? \\"\\"`}</ws.element><ws.element ws:tag=\"time\">{expression`collectionItem.properties.publishedAt ?? \\"\\"`}</ws.element><ws.element ws:tag=\"a\" href={expression`\\"/blog/\\" + collectionItem.properties.slug`}>Read article</ws.element></ws.element>"}, substituting only the returned overview root id.',
- 'Then call insert-collection exactly once on the detail root with {"parentInstanceId":"<detail-root-id>","data":{"type":"expression","value":"post.data"},"itemFragment":"<ws.element ws:tag=\"article\"><ws.element ws:tag=\"h1\">{expression`collectionItem.properties.title ?? \\"Untitled\\"`}</ws.element><$.MarkdownEmbed code={expression`collectionItem.content.text`} /></ws.element>"}, substituting only the returned detail root id. insert-collection validates and persists its bindings atomically, so do not call verify-bindings or perform any repair afterward.',
+ "Database size is part of the evaluated outcome. The final project must have exactly the two intended reachable Assets queries, one materialized overview, all five source documents included without truncation, and zero embedded Markdown body bytes. Do not leave a placeholder, preview copy, stale resource, or replacement data source in the project.",
+ 'First call create-assets-resource exactly once with this complete overview input, substituting the returned overview root id and Blog folder id: {"name":"Published posts","scopeInstanceId":"<overview-root-id>","dataSourceName":"posts","query":{"where":{"all":[{"field":["extension"],"operator":"eq","value":{"type":"literal","value":"md"}},{"field":["folderId"],"operator":"eq","value":{"type":"literal","value":"<blog-folder-id>"}},{"field":["properties","draft"],"operator":"ne","value":{"type":"literal","value":true}}]},"sort":[{"field":["properties","publishedAt"],"direction":"desc"},{"field":["id"],"direction":"asc"}],"limit":{"type":"literal","value":20},"offset":{"type":"literal","value":0},"output":{"mode":"fields","includeMetadata":false,"fields":[["properties","title"],["properties","slug"],["properties","publishedAt"],["properties","author"],["properties","excerpt"]]},"content":{"mode":"none"}}}. Keep literal wrappers and field-path arrays unchanged.',
+ 'Then call create-assets-resource exactly once with this complete detail input, substituting the returned detail root id and the same Blog folder id: {"name":"Post by slug","scopeInstanceId":"<detail-root-id>","dataSourceName":"post","query":{"where":{"all":[{"field":["extension"],"operator":"eq","value":{"type":"literal","value":"md"}},{"field":["folderId"],"operator":"eq","value":{"type":"literal","value":"<blog-folder-id>"}},{"field":["properties","slug"],"operator":"eq","value":"system.params.slug"}]},"limit":{"type":"literal","value":1},"offset":{"type":"literal","value":0},"output":{"mode":"fields","includeMetadata":false,"fields":[["properties","title"],["properties","author"]]},"content":{"mode":"markdown-body"}}}. Do not call create-assets-resource again.',
+ 'After both resources succeed, call insert-collection exactly once on the overview root with {"parentInstanceId":"<overview-root-id>","data":{"type":"expression","value":"posts.data"},"itemFragment":"<ws.element ws:tag=\"article\"><ws.element ws:tag=\"h2\">{expression`collectionItem.properties.title ?? \\"Untitled\\"`}</ws.element><ws.element ws:tag=\"p\">{expression`collectionItem.properties.excerpt ?? \\"\\"`}</ws.element><ws.element ws:tag=\"p\">By {expression`collectionItem.properties.author.name`}</ws.element><ws.element ws:tag=\"time\">{expression`collectionItem.properties.publishedAt ?? \\"\\"`}</ws.element><ws.element ws:tag=\"a\" href={expression`\\"/blog/\\" + collectionItem.properties.slug`}>Read article</ws.element></ws.element>"}, substituting only the returned overview root id.',
+ 'Then call insert-collection exactly once on the detail root with {"parentInstanceId":"<detail-root-id>","data":{"type":"expression","value":"post.data"},"itemFragment":"<ws.element ws:tag=\"article\"><ws.element ws:tag=\"h1\">{expression`collectionItem.properties.title ?? \\"Untitled\\"`}</ws.element><ws.element ws:tag=\"p\">By {expression`collectionItem.properties.author.name`}</ws.element><$.MarkdownEmbed code={expression`collectionItem.content.text`} /></ws.element>"}, substituting only the returned detail root id. insert-collection validates and persists its bindings atomically, so do not call verify-bindings or perform any repair afterward.',
'After both Collections succeed, call verify-page-responsive exactly twice: first with {"path":"/blog","viewports":[{"width":1440,"height":900},{"width":390,"height":844}],"source":"session"}, then with {"path":"/blog/aurora-trails","viewports":[{"width":1440,"height":900},{"width":390,"height":844}],"source":"session"}. Do not mutate, rediscover, restart preview, or capture separate screenshots or audits after verification begins. If either verification fails, stop immediately without retrying or changing the project.',
]
: []),
diff --git a/packages/cli/evaluations/high-impact/evaluation-metrics.ts b/packages/cli/evaluations/high-impact/evaluation-metrics.ts
index d382de92b7..b2ca6a14fb 100644
--- a/packages/cli/evaluations/high-impact/evaluation-metrics.ts
+++ b/packages/cli/evaluations/high-impact/evaluation-metrics.ts
@@ -256,6 +256,9 @@ const countRetries = (calls: readonly EvaluationToolCall[]) => {
return retries;
};
+export const hasMcpToolCallRetries = (calls: readonly EvaluationToolCall[]) =>
+ countRetries(calls) > 0;
+
const countValues = (values: readonly string[]) =>
Object.fromEntries(
[...new Set(values)]
diff --git a/packages/cli/evaluations/high-impact/fixture-api.test.ts b/packages/cli/evaluations/high-impact/fixture-api.test.ts
index 18113cd612..b7abdc0b2f 100644
--- a/packages/cli/evaluations/high-impact/fixture-api.test.ts
+++ b/packages/cli/evaluations/high-impact/fixture-api.test.ts
@@ -1,5 +1,5 @@
import { execFile } from "node:child_process";
-import { mkdir, mkdtemp, rm } from "node:fs/promises";
+import { mkdir, mkdtemp, readFile, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join, resolve } from "node:path";
import { promisify } from "node:util";
@@ -20,7 +20,7 @@ import {
writeFontAssetFixtureFiles,
} from "./font-assets-fixture";
import {
- markdownBlogFixtureArticles,
+ markdownBlogFixtureDocuments,
writeMarkdownBlogFixtureFiles,
} from "./markdown-blog-fixture";
@@ -178,10 +178,10 @@ describe("high-impact fixture API", () => {
expect(folder.ok).toBe(true);
const folderId = String(folder.data.folderId);
const upload = await run("upload-assets", {
- assets: markdownBlogFixtureArticles.map(({ name }) => ({
+ assets: markdownBlogFixtureDocuments.map(({ name, format }) => ({
name,
type: "file",
- format: "md",
+ format,
folderId,
meta: {},
})),
@@ -190,15 +190,22 @@ describe("high-impact fixture API", () => {
expect(upload.ok).toBe(true);
expect(fixtureApi.getProject()).toMatchObject({
assetFolders: [expect.objectContaining({ id: folderId, name: "Blog" })],
- assets: markdownBlogFixtureArticles.map(({ name }) =>
+ assets: markdownBlogFixtureDocuments.map(({ name, format }) =>
expect.objectContaining({
name,
+ filename: name.slice(0, name.lastIndexOf(".")),
type: "file",
- format: "md",
+ format,
folderId,
})
),
});
+ await expect(
+ readFile(
+ join(projectDirectory, ".webstudio/assets/aurora-trails.md"),
+ "utf8"
+ )
+ ).resolves.toContain("name: Mira Chen");
} finally {
await fixtureApi.close();
await rm(directory, { recursive: true, force: true });
diff --git a/packages/cli/evaluations/high-impact/fixture-api.ts b/packages/cli/evaluations/high-impact/fixture-api.ts
index 2eea497344..45d2fd4c87 100644
--- a/packages/cli/evaluations/high-impact/fixture-api.ts
+++ b/packages/cli/evaluations/high-impact/fixture-api.ts
@@ -1,6 +1,6 @@
import type { Server } from "node:http";
import { fontFormat, fontMeta } from "@webstudio-is/fonts";
-import type { Asset } from "@webstudio-is/sdk";
+import { getFileNameParts, type Asset } from "@webstudio-is/sdk";
import { assetsUploadsApiUrl } from "@webstudio-is/sdk/runtime";
import { migratePages } from "@webstudio-is/project-migrations/pages";
import React from "react";
@@ -154,7 +154,7 @@ export const startHighImpactFixtureApi = async (
id: `evaluation-asset-${generatedId++}`,
projectId,
name,
- filename: name,
+ filename: getFileNameParts(name).basename,
description: typeof description === "string" ? description : null,
size: body.byteLength,
...(folderId === undefined ? {} : { folderId }),
diff --git a/packages/cli/evaluations/high-impact/fixtures.ts b/packages/cli/evaluations/high-impact/fixtures.ts
index eb8cf541b2..bc21c48284 100644
--- a/packages/cli/evaluations/high-impact/fixtures.ts
+++ b/packages/cli/evaluations/high-impact/fixtures.ts
@@ -62,7 +62,8 @@ export type HighImpactFixture = {
| "authenticated-page-v1"
| "design-input-v1"
| "font-assets-v1"
- | "markdown-blog-v1";
+ | "markdown-blog-v1"
+ | "markdown-references-discovery-v1";
objective: string;
project: EvaluationProject;
};
@@ -219,7 +220,13 @@ export const fontAssetsFixture: HighImpactFixture = {
export const markdownBlogFixture: HighImpactFixture = {
id: "markdown-blog-v1",
- objective: `Upload the ${markdownBlogFixtureArticles.length} provided Markdown articles from .webstudio/assets into one Blog asset folder. Build an editable blog overview at /blog and a dynamic detail page at /blog/:slug using exactly one fully configured scoped Assets resource per page, Collections, and Markdown Embed. Include the complete structured query in each initial resource creation; never create a default or placeholder resource and never repair one by creating another. The overview query must exclude drafts, sort newest first, select the article title, slug, excerpt, and publication date, and avoid loading file content. The detail query must select one article from system.params.slug and load its Markdown body. Verify both /blog and /blog/aurora-trails at desktop and mobile sizes.`,
+ objective: `Upload the ${markdownBlogFixtureArticles.length} provided Markdown articles from .webstudio/assets into one Blog asset folder. Build an editable, size-optimal blog overview at /blog and a dynamic detail page at /blog/:slug using exactly one fully configured scoped Assets resource per page, Collections, and Markdown Embed. Include the complete structured query in each initial resource creation; never create a default, placeholder, duplicate, preview copy, or repair replacement. Both queries must read the Markdown files directly. The overview query must be fully static and bounded, exclude drafts, sort newest first with a deterministic ID tie-breaker, select only the rendered title, slug, excerpt, publication date, and author frontmatter, and load no bodies so it can be materialized. The detail query must use only the dynamic slug, select only rendered metadata, and return one Markdown body without embedding it in the published database. The compiled database must include all articles without truncation, no embedded bodies, and only the intended materialized overview. Render the author name on both pages. Verify both /blog and /blog/aurora-trails at desktop and mobile sizes.`,
+ project: emptyProject(),
+};
+
+export const markdownReferencesDiscoveryFixture: HighImpactFixture = {
+ id: "markdown-references-discovery-v1",
+ objective: `Upload the supplied ${markdownBlogFixtureArticles.map(({ name }) => name).join(", ")} Markdown articles from .webstudio/assets. Build an editable blog overview at /blog and one dynamic article page at /blog/:slug. Query the Markdown files directly so draft articles are excluded, posts are ordered newest first, each post displays its frontmatter author, and only the selected Markdown body is fetched from Asset storage without being embedded in the published database. Verify the overview and /blog/aurora-trails at desktop and mobile sizes. Discover the supported workflow and data shapes from Webstudio MCP guidance.`,
project: emptyProject(),
};
@@ -228,6 +235,7 @@ export const highImpactFixtures = [
designInputFixture,
fontAssetsFixture,
markdownBlogFixture,
+ markdownReferencesDiscoveryFixture,
] as const;
export const validateHighImpactFixture = (fixture: HighImpactFixture) => {
diff --git a/packages/cli/evaluations/high-impact/markdown-blog-fixture.ts b/packages/cli/evaluations/high-impact/markdown-blog-fixture.ts
index 7926065423..95b58a72b0 100644
--- a/packages/cli/evaluations/high-impact/markdown-blog-fixture.ts
+++ b/packages/cli/evaluations/high-impact/markdown-blog-fixture.ts
@@ -39,6 +39,10 @@ export const markdownBlogFixtureArticles = [
},
] as const;
+export const markdownBlogFixtureDocuments = markdownBlogFixtureArticles.map(
+ ({ name }) => ({ name, format: "md" as const })
+);
+
const articleSource = (
article: (typeof markdownBlogFixtureArticles)[number]
) => `---
@@ -47,6 +51,9 @@ slug: ${article.slug}
publishedAt: ${article.publishedAt}
draft: false
excerpt: ${article.excerpt}
+author:
+ name: Mira Chen
+ role: Northstar editor
---
# ${article.title}
@@ -62,9 +69,9 @@ export const writeMarkdownBlogFixtureFiles = async (
) => {
const assetsDirectory = join(projectDirectory, ".webstudio/assets");
await mkdir(assetsDirectory, { recursive: true });
- await Promise.all(
- markdownBlogFixtureArticles.map((article) =>
+ await Promise.all([
+ ...markdownBlogFixtureArticles.map((article) =>
writeFile(join(assetsDirectory, article.name), articleSource(article))
- )
- );
+ ),
+ ]);
};
diff --git a/packages/cli/evaluations/high-impact/results/markdown-references-discovery-v1.json b/packages/cli/evaluations/high-impact/results/markdown-references-discovery-v1.json
new file mode 100644
index 0000000000..c2c50160a5
--- /dev/null
+++ b/packages/cli/evaluations/high-impact/results/markdown-references-discovery-v1.json
@@ -0,0 +1,192 @@
+{
+ "schemaVersion": 2,
+ "kind": "high-impact-minimal-context-agent-evaluation-result",
+ "fixtureId": "markdown-references-discovery-v1",
+ "outcome": "passed",
+ "cli": "source",
+ "provider": "openai",
+ "model": "gpt-5.4-mini",
+ "commandSha256": "129c4beeb0730eadd324419a95969b599a39bb2776e0d1d93920d61bbc9e182a",
+ "exitCode": 0,
+ "metrics": {
+ "durationMs": 162261,
+ "tokens": {
+ "input": 335174,
+ "cachedInput": 299776,
+ "uncachedInput": 35398,
+ "cacheWriteInput": 0,
+ "output": 8397,
+ "reasoningOutput": 5497,
+ "total": 343571,
+ "cachedInputRate": 0.8944
+ },
+ "mcpCatalog": {
+ "responses": 1,
+ "totalResponseBytes": 54701,
+ "maxResponseBytes": 54701,
+ "latestToolCount": 185,
+ "latestResponseBytes": 54701,
+ "latestInputSchemaBytes": 30201,
+ "latestDescriptionBytes": 5708
+ },
+ "toolCalls": {
+ "total": 12,
+ "succeeded": 12,
+ "failed": 0,
+ "failuresByTool": {},
+ "failuresByCode": {},
+ "issuesByCode": {},
+ "issuesByPath": {},
+ "durationsByTool": {
+ "create-asset-folder": {
+ "count": 1,
+ "totalMs": 48,
+ "p95Ms": 48,
+ "maxMs": 48
+ },
+ "create-assets-resource": {
+ "count": 2,
+ "totalMs": 61,
+ "p95Ms": 42,
+ "maxMs": 42
+ },
+ "create-page": {
+ "count": 2,
+ "totalMs": 40,
+ "p95Ms": 27,
+ "maxMs": 27
+ },
+ "insert-collection": {
+ "count": 2,
+ "totalMs": 119,
+ "p95Ms": 103,
+ "maxMs": 103
+ },
+ "meta.get_more_tools": {
+ "count": 1,
+ "totalMs": 14,
+ "p95Ms": 14,
+ "maxMs": 14
+ },
+ "meta.guide": {
+ "count": 1,
+ "totalMs": 21,
+ "p95Ms": 21,
+ "maxMs": 21
+ },
+ "upload-assets": {
+ "count": 1,
+ "totalMs": 22,
+ "p95Ms": 22,
+ "maxMs": 22
+ },
+ "verify-page-responsive": {
+ "count": 2,
+ "totalMs": 14517,
+ "p95Ms": 12878,
+ "maxMs": 12878
+ }
+ },
+ "responseBytesByTool": {
+ "create-asset-folder": {
+ "count": 1,
+ "totalBytes": 884,
+ "p95Bytes": 884,
+ "maxBytes": 884
+ },
+ "create-assets-resource": {
+ "count": 2,
+ "totalBytes": 3324,
+ "p95Bytes": 1662,
+ "maxBytes": 1662
+ },
+ "create-page": {
+ "count": 2,
+ "totalBytes": 2684,
+ "p95Bytes": 1342,
+ "maxBytes": 1342
+ },
+ "insert-collection": {
+ "count": 2,
+ "totalBytes": 4518,
+ "p95Bytes": 2293,
+ "maxBytes": 2293
+ },
+ "meta.get_more_tools": {
+ "count": 1,
+ "totalBytes": 19474,
+ "p95Bytes": 19474,
+ "maxBytes": 19474
+ },
+ "meta.guide": {
+ "count": 1,
+ "totalBytes": 15748,
+ "p95Bytes": 15748,
+ "maxBytes": 15748
+ },
+ "upload-assets": {
+ "count": 1,
+ "totalBytes": 4200,
+ "p95Bytes": 4200,
+ "maxBytes": 4200
+ },
+ "verify-page-responsive": {
+ "count": 2,
+ "totalBytes": 29404,
+ "p95Bytes": 14825,
+ "maxBytes": 14825
+ }
+ },
+ "retries": 0,
+ "focusedReads": 0,
+ "broadReads": 0,
+ "dryRuns": 0,
+ "plannedMutations": 0,
+ "committedMutations": 8,
+ "verifications": 2,
+ "totalDurationMs": 14842,
+ "p50DurationMs": 22,
+ "p95DurationMs": 12878,
+ "totalResponseBytes": 80236,
+ "p50ResponseBytes": 2225,
+ "p95ResponseBytes": 19474,
+ "maxResponseBytes": 19474,
+ "timeToFirstMutationMs": 65003,
+ "timeToFirstVerificationMs": 122016
+ }
+ },
+ "callSequence": [
+ "meta.guide",
+ "meta.get_more_tools",
+ "create-asset-folder",
+ "create-page",
+ "create-page",
+ "upload-assets",
+ "create-assets-resource",
+ "create-assets-resource",
+ "insert-collection",
+ "insert-collection",
+ "verify-page-responsive",
+ "verify-page-responsive"
+ ],
+ "checks": {
+ "guidance": "passed",
+ "privacy": "passed",
+ "expressions": "passed",
+ "boundedReads": "passed",
+ "referenceDocumentationDiscovery": "passed",
+ "retryFreeExecution": "passed",
+ "markdownUploads": "passed",
+ "documentGraphSources": "passed",
+ "blogAssetFolder": "passed",
+ "blogRoutes": "passed",
+ "scopedBlogResources": "passed",
+ "listingQuery": "passed",
+ "detailQuery": "passed",
+ "documentGraphQueries": "passed",
+ "editableBlogBindings": "passed",
+ "bindingVerification": "passed",
+ "blogRouteEvidence": "passed",
+ "usageCaptured": "passed"
+ }
+}
diff --git a/packages/cli/evaluations/high-impact/run-local-agent.ts b/packages/cli/evaluations/high-impact/run-local-agent.ts
index b3644869b0..7e5f23da8c 100644
--- a/packages/cli/evaluations/high-impact/run-local-agent.ts
+++ b/packages/cli/evaluations/high-impact/run-local-agent.ts
@@ -7,10 +7,14 @@ import { pathToFileURL } from "node:url";
import { promisify } from "node:util";
import yargs from "yargs";
import { hideBin } from "yargs/helpers";
+import { createContentDatabase } from "@webstudio-is/content-engine";
+import { compileContentSource } from "@webstudio-is/content-engine/compiler";
+import { createReachableAssetContentCompilationPlan } from "@webstudio-is/sdk";
import {
fontAssetsFixture,
highImpactFixtures,
markdownBlogFixture,
+ markdownReferencesDiscoveryFixture,
type HighImpactFixture,
} from "./fixtures";
import { startHighImpactFixtureApi } from "./fixture-api";
@@ -25,6 +29,11 @@ import type { EvaluationToolCall } from "./validate";
import type { McpCatalogObservation } from "./evaluation-metrics";
import { writeFontAssetFixtureFiles } from "./font-assets-fixture";
import { writeMarkdownBlogFixtureFiles } from "./markdown-blog-fixture";
+import {
+ createCliProjectSessionStorage,
+ getCliProjectSessionFile,
+} from "../../src/project-session";
+import { createFileSystemContentSource } from "../../src/filesystem-content-source";
import {
compareEvaluationResult,
isAggregateTokenBaselineNonRegressed,
@@ -65,6 +74,50 @@ const selectFixtures = (fixtureId: string | undefined) => {
return [fixture];
};
+const compileEvaluationContentDatabase = async (projectDirectory: string) => {
+ const snapshot = await createCliProjectSessionStorage(
+ getCliProjectSessionFile(projectDirectory)
+ ).load();
+ if (snapshot === undefined) {
+ throw new Error("Evaluation project session is unavailable");
+ }
+ const plan = createReachableAssetContentCompilationPlan({
+ props: snapshot.state.props?.values() ?? [],
+ dataSources: snapshot.state.dataSources?.values() ?? [],
+ resources: snapshot.state.resources?.values() ?? [],
+ });
+ if (plan === undefined) {
+ throw new Error("Evaluation blog has no reachable Assets resources");
+ }
+ const { artifact } = await compileContentSource({
+ source: createFileSystemContentSource({
+ projectId: snapshot.projectId,
+ assets: Array.from(snapshot.state.assets?.values() ?? []),
+ folders: snapshot.state.assetFolders ?? new Map(),
+ assetsDirectory: join(projectDirectory, ".webstudio/assets"),
+ }),
+ projectId: snapshot.projectId,
+ plan,
+ });
+ const stats = createContentDatabase({ artifact }).getStats();
+ return {
+ usedBytes: stats.usedBytes,
+ maxBytes: stats.maxBytes,
+ unboundedBytes: stats.unboundedBytes,
+ sourceDocumentCount:
+ stats.includedDocumentCount + stats.omittedDocumentCount,
+ includedDocumentCount: stats.includedDocumentCount,
+ omittedDocumentCount: stats.omittedDocumentCount,
+ materializedQueryCount: Object.keys(artifact.queries ?? {}).length,
+ documentGraphNodeCount: artifact.documentGraph?.nodes.length ?? 0,
+ documentGraphEdgeCount: artifact.documentGraph?.edges.length ?? 0,
+ embeddedContentBytes: Object.values(artifact.contents ?? {}).reduce(
+ (total, content) => total + Buffer.byteLength(content),
+ 0
+ ),
+ };
+};
+
const runFixture = async ({
fixture,
repositoryRoot,
@@ -91,7 +144,10 @@ const runFixture = async ({
await mkdir(projectDirectory, { recursive: true });
if (fixture.id === fontAssetsFixture.id) {
await writeFontAssetFixtureFiles(projectDirectory);
- } else if (fixture.id === markdownBlogFixture.id) {
+ } else if (
+ fixture.id === markdownBlogFixture.id ||
+ fixture.id === markdownReferencesDiscoveryFixture.id
+ ) {
await writeMarkdownBlogFixtureFiles(projectDirectory);
}
const env = { ...process.env, WEBSTUDIO_CONFIG_DIR: configDirectory };
@@ -163,6 +219,13 @@ const runFixture = async ({
project: fixtureApi.getProject(),
toolCalls,
artifacts: await collectHighImpactArtifacts(projectDirectory),
+ ...(fixture.id === markdownBlogFixture.id ||
+ fixture.id === markdownReferencesDiscoveryFixture.id
+ ? {
+ contentDatabase:
+ await compileEvaluationContentDatabase(projectDirectory),
+ }
+ : {}),
});
},
});
diff --git a/packages/cli/evaluations/high-impact/validate.test.ts b/packages/cli/evaluations/high-impact/validate.test.ts
index c4bfa4b588..40d0d460e8 100644
--- a/packages/cli/evaluations/high-impact/validate.test.ts
+++ b/packages/cli/evaluations/high-impact/validate.test.ts
@@ -7,6 +7,7 @@ import {
fontAssetsFixture,
highImpactFixtures,
markdownBlogFixture,
+ markdownReferencesDiscoveryFixture,
validateHighImpactFixture,
type EvaluationProject,
} from "./fixtures";
@@ -14,7 +15,7 @@ import {
fontAssetFixtureFiles,
fontAssetFixtureMeta,
} from "./font-assets-fixture";
-import { markdownBlogFixtureArticles } from "./markdown-blog-fixture";
+import { markdownBlogFixtureDocuments } from "./markdown-blog-fixture";
import { evaluateHighImpactOutcome, type EvaluationToolCall } from "./validate";
const clone = <Value>(value: Value): Value => structuredClone(value);
@@ -142,7 +143,7 @@ const addMarkdownBlog = (): EvaluationProject => {
createdAt: "2026-01-01T00:00:00.000Z",
});
project.assets.push(
- ...markdownBlogFixtureArticles.map(({ name }) => ({
+ ...markdownBlogFixtureDocuments.map(({ name, format }) => ({
id: name,
projectId: "project",
name,
@@ -151,7 +152,7 @@ const addMarkdownBlog = (): EvaluationProject => {
folderId: "blog-folder",
size: 100,
type: "file" as const,
- format: "md",
+ format,
meta: {},
createdAt: "2026-01-01T00:00:00.000Z",
}))
@@ -186,12 +187,16 @@ const addMarkdownBlog = (): EvaluationProject => {
component: "Box",
children: [
{ type: "expression", value: "collectionItem.properties.title" },
- { type: "expression", value: "collectionItem.excerpt" },
+ { type: "expression", value: "collectionItem.properties.excerpt" },
{
type: "expression",
value: "collectionItem.properties.publishedAt",
},
{ type: "expression", value: "collectionItem.properties.slug" },
+ {
+ type: "expression",
+ value: "collectionItem.properties.author.name",
+ },
],
},
{
@@ -202,7 +207,20 @@ const addMarkdownBlog = (): EvaluationProject => {
{
id: "detail-collection",
component: "Collection",
- children: [{ type: "id", value: "markdown" }],
+ children: [
+ { type: "id", value: "detail-author" },
+ { type: "id", value: "markdown" },
+ ],
+ },
+ {
+ id: "detail-author",
+ component: "Text",
+ children: [
+ {
+ type: "expression",
+ value: "collectionItem.properties.author.name",
+ },
+ ],
},
{
id: "markdown",
@@ -238,10 +256,11 @@ const addMarkdownBlog = (): EvaluationProject => {
where: {
all: [
{ field: ["extension"], operator: "eq", value: '"md"' },
+ { field: ["folderId"], operator: "eq", value: '"blog-folder"' },
{
field: ["properties", "draft"],
operator: "ne",
- value: '"true"',
+ value: "true",
},
],
},
@@ -258,7 +277,8 @@ const addMarkdownBlog = (): EvaluationProject => {
["properties", "title"],
["properties", "slug"],
["properties", "publishedAt"],
- ["excerpt"],
+ ["properties", "author"],
+ ["properties", "excerpt"],
],
},
content: { mode: "none" },
@@ -271,6 +291,7 @@ const addMarkdownBlog = (): EvaluationProject => {
where: {
all: [
{ field: ["extension"], operator: "eq", value: '"md"' },
+ { field: ["folderId"], operator: "eq", value: '"blog-folder"' },
{
field: ["properties", "slug"],
operator: "eq",
@@ -284,9 +305,12 @@ const addMarkdownBlog = (): EvaluationProject => {
output: {
mode: "fields",
includeMetadata: false,
- fields: [["properties", "title"]],
+ fields: [
+ ["properties", "title"],
+ ["properties", "author"],
+ ],
},
- content: { mode: "markdown-body", maxBytes: 1_048_576 },
+ content: { mode: "markdown-body" },
})
)
);
@@ -327,6 +351,7 @@ describe("high-impact fixture validation", () => {
{ valid: true, failures: [] },
{ valid: true, failures: [] },
{ valid: true, failures: [] },
+ { valid: true, failures: [] },
]);
expect(JSON.stringify(highImpactFixtures)).toBe(
JSON.stringify(highImpactFixtures)
@@ -381,6 +406,18 @@ describe("font-assets evaluation", () => {
});
describe("Markdown blog evaluation", () => {
+ const optimalContentDatabase = {
+ usedBytes: 6_000,
+ maxBytes: 500 * 1024,
+ unboundedBytes: 6_000,
+ sourceDocumentCount: markdownBlogFixtureDocuments.length,
+ includedDocumentCount: markdownBlogFixtureDocuments.length,
+ omittedDocumentCount: 0,
+ materializedQueryCount: 1,
+ documentGraphNodeCount: markdownBlogFixtureDocuments.length,
+ documentGraphEdgeCount: 0,
+ embeddedContentBytes: 0,
+ };
const successfulCalls: EvaluationToolCall[] = [
{ name: "meta.guide" },
{ name: "verify-bindings" },
@@ -400,14 +437,140 @@ describe("Markdown blog evaluation", () => {
},
];
- test("accepts a bounded two-route Markdown blog", () => {
- expect(
- evaluateHighImpactOutcome({
- fixture: markdownBlogFixture,
- project: addMarkdownBlog(),
- toolCalls: successfulCalls,
- })
- ).toMatchObject({ passed: true, failures: [] });
+ test("accepts a bounded two-route Markdown blog with a resolved JSON author", () => {
+ const result = evaluateHighImpactOutcome({
+ fixture: markdownBlogFixture,
+ project: addMarkdownBlog(),
+ toolCalls: successfulCalls,
+ contentDatabase: optimalContentDatabase,
+ });
+ expect(result).toMatchObject({ passed: true, failures: [] });
+ expect(result.checks).toMatchObject({
+ documentGraphSources: "passed",
+ documentGraphQueries: "passed",
+ optimalBlogDatabase: "passed",
+ });
+ });
+
+ test("accepts persisted MCP expressions and boolean query operands", () => {
+ const project = addMarkdownBlog();
+ project.dataSources.push({
+ id: "collection-item",
+ type: "parameter",
+ name: "collectionItem",
+ scopeInstanceId: "blog-collection",
+ });
+ project.resources = project.resources.map((resource, index) => ({
+ ...resource,
+ body:
+ index === 0
+ ? resource.body
+ : String(resource.body).replace(
+ "value: system.params.slug",
+ "value: $ws$system.params.slug"
+ ),
+ }));
+ project.instances = project.instances.map((instance) => ({
+ ...instance,
+ children: instance.children.map((child) =>
+ child.type === "expression"
+ ? {
+ ...child,
+ value: child.value.replace(
+ "collectionItem",
+ "$ws$dataSource$collection__DASH__item?"
+ ),
+ }
+ : child
+ ),
+ }));
+ project.props = project.props.map((prop) =>
+ prop.type === "expression"
+ ? {
+ ...prop,
+ value: String(prop.value).replace(
+ "collectionItem",
+ "$ws$dataSource$collection__DASH__item?"
+ ),
+ }
+ : prop
+ );
+
+ const result = evaluateHighImpactOutcome({
+ fixture: markdownBlogFixture,
+ project,
+ toolCalls: successfulCalls,
+ contentDatabase: optimalContentDatabase,
+ });
+
+ expect(result).toMatchObject({ passed: true, failures: [] });
+ });
+
+ test("rejects blog resources that do not select the referenced author", () => {
+ const project = addMarkdownBlog();
+ project.resources = project.resources.map((resource) => ({
+ ...resource,
+ body: String(resource.body).replaceAll("author", "omitted"),
+ }));
+ const result = evaluateHighImpactOutcome({
+ fixture: markdownBlogFixture,
+ project,
+ toolCalls: successfulCalls,
+ });
+ expect(result.checks.documentGraphQueries).toBe("failed");
+ });
+
+ test("matches required query fields structurally instead of by substring", () => {
+ const project = addMarkdownBlog();
+ project.resources[0] = {
+ ...project.resources[0],
+ body: String(project.resources[0]?.body)
+ .replace('["properties", "title"]', '["properties", "title-slug"]')
+ .replace('["properties", "slug"]', '["properties", "excerpt-slug"]'),
+ };
+ const result = evaluateHighImpactOutcome({
+ fixture: markdownBlogFixture,
+ project,
+ toolCalls: successfulCalls,
+ });
+ expect(result.checks.listingQuery).toBe("failed");
+ });
+
+ test("does not treat dynamic computed members as static bindings", () => {
+ const project = addMarkdownBlog();
+ project.instances = project.instances.map((instance) => ({
+ ...instance,
+ children: instance.children.map((child) =>
+ child.type === "expression"
+ ? {
+ ...child,
+ value: child.value.replace(
+ "collectionItem.properties",
+ "collectionItem[properties]"
+ ),
+ }
+ : child
+ ),
+ }));
+ project.props = project.props.map((prop) =>
+ prop.type === "expression"
+ ? {
+ ...prop,
+ value: String(prop.value).replace(
+ "collectionItem.properties",
+ "collectionItem[properties]"
+ ),
+ }
+ : prop
+ );
+
+ const result = evaluateHighImpactOutcome({
+ fixture: markdownBlogFixture,
+ project,
+ toolCalls: successfulCalls,
+ });
+
+ expect(result.checks.editableBlogBindings).toBe("failed");
});
test("rejects missing detail content and route evidence", () => {
@@ -423,6 +586,93 @@ describe("Markdown blog evaluation", () => {
blogRouteEvidence: "failed",
});
});
+
+ test("requires documentation discovery for the unprompted reference workflow", () => {
+ const project = addMarkdownBlog();
+ const withoutDiscovery = evaluateHighImpactOutcome({
+ fixture: markdownReferencesDiscoveryFixture,
+ project,
+ toolCalls: successfulCalls,
+ });
+ expect(withoutDiscovery.checks.referenceDocumentationDiscovery).toBe(
+ "failed"
+ );
+
+ const withDiscovery = evaluateHighImpactOutcome({
+ fixture: markdownReferencesDiscoveryFixture,
+ project,
+ contentDatabase: optimalContentDatabase,
+ toolCalls: [
+ { name: "meta.guide" },
+ { name: "meta.get_more_tools" },
+ ...successfulCalls.slice(1),
+ ],
+ });
+ expect(withDiscovery).toMatchObject({ passed: true, failures: [] });
+ expect(withDiscovery.checks.referenceDocumentationDiscovery).toBe("passed");
+ });
+
+ test("rejects a duplicated or oversized compiled blog database", () => {
+ const result = evaluateHighImpactOutcome({
+ fixture: markdownBlogFixture,
+ project: addMarkdownBlog(),
+ toolCalls: successfulCalls,
+ contentDatabase: {
+ ...optimalContentDatabase,
+ usedBytes: 6_501,
+ unboundedBytes: 6_501,
+ materializedQueryCount: 2,
+ },
+ });
+
+ expect(result.checks.optimalBlogDatabase).toBe("failed");
+ });
+
+ test("rejects a document-reference workflow that retries a failed tool", () => {
+ const result = evaluateHighImpactOutcome({
+ fixture: markdownReferencesDiscoveryFixture,
+ project: addMarkdownBlog(),
+ toolCalls: [
+ { name: "meta.guide" },
+ { name: "meta.get_more_tools" },
+ { name: "upload-assets", isError: true },
+ { name: "upload-assets" },
+ ...successfulCalls.slice(1),
+ ],
+ });
+
+ expect(result.checks.retryFreeExecution).toBe("failed");
+ });
+
+ test("rejects a document-reference workflow that plans mutations", () => {
+ const result = evaluateHighImpactOutcome({
+ fixture: markdownReferencesDiscoveryFixture,
+ project: addMarkdownBlog(),
+ toolCalls: [
+ { name: "meta.guide" },
+ { name: "meta.get_more_tools" },
+ { name: "create-page", planned: true },
+ ...successfulCalls,
+ ],
+ });
+
+ expect(result.checks.retryFreeExecution).toBe("failed");
+ });
+
+ test("rejects repeated document-reference tool discovery", () => {
+ const result = evaluateHighImpactOutcome({
+ fixture: markdownReferencesDiscoveryFixture,
+ project: addMarkdownBlog(),
+ toolCalls: [
+ { name: "meta.guide" },
+ { name: "meta.get_more_tools" },
+ { name: "meta.get_more_tools" },
+ ...successfulCalls,
+ ],
+ });
+
+ expect(result.checks.referenceDocumentationDiscovery).toBe("failed");
+ });
});
describe("authenticated-page evaluation", () => {
diff --git a/packages/cli/evaluations/high-impact/validate.ts b/packages/cli/evaluations/high-impact/validate.ts
index a6c520c6b3..0fabe4dd03 100644
--- a/packages/cli/evaluations/high-impact/validate.ts
+++ b/packages/cli/evaluations/high-impact/validate.ts
@@ -1,16 +1,21 @@
import { parseExpressionAt } from "acorn";
+import { transpileExpression } from "@webstudio-is/expression";
import { getFontFaces } from "@webstudio-is/fonts";
+import { getQueryConditions } from "@webstudio-is/query-builder/runtime";
import {
+ decodeDataSourceVariable,
isAssetsResource,
parseStructuredAssetQueryResourceBody,
type FontAsset,
type Resource,
+ type StructuredAssetQueryWhereBinding,
} from "@webstudio-is/sdk";
import {
authenticatedPageFixture,
designInputFixture,
fontAssetsFixture,
markdownBlogFixture,
+ markdownReferencesDiscoveryFixture,
type EvaluationInstance,
type EvaluationProject,
type HighImpactFixture,
@@ -20,8 +25,11 @@ import {
fontAssetFixtureMeta,
fontAssetFixtureSource,
} from "./font-assets-fixture";
-import { markdownBlogFixtureArticles } from "./markdown-blog-fixture";
-import { isBroadRead } from "./evaluation-metrics";
+import {
+ markdownBlogFixtureArticles,
+ markdownBlogFixtureDocuments,
+} from "./markdown-blog-fixture";
+import { hasMcpToolCallRetries, isBroadRead } from "./evaluation-metrics";
export type EvaluationToolCall = {
name: string;
@@ -48,6 +56,18 @@ export type HighImpactEvaluationInput = {
project: EvaluationProject;
toolCalls: EvaluationToolCall[];
artifacts?: EvaluationArtifact[];
+ contentDatabase?: {
+ usedBytes: number;
+ maxBytes: number;
+ unboundedBytes: number;
+ sourceDocumentCount: number;
+ includedDocumentCount: number;
+ omittedDocumentCount: number;
+ materializedQueryCount: number;
+ documentGraphNodeCount: number;
+ documentGraphEdgeCount: number;
+ embeddedContentBytes: number;
+ };
};
export type HighImpactEvaluationResult = {
@@ -556,23 +576,170 @@ const getAssetResourceConfigurations = (project: EvaluationProject) =>
return configuration === undefined ? [] : [{ resource, configuration }];
});
-const hasQueryFragment = (value: unknown, fragments: string[]) => {
- const source = JSON.stringify(value);
- return fragments.every((fragment) => source.includes(fragment));
+const pathsEqual = (left: unknown, right: readonly string[]) =>
+ Array.isArray(left) &&
+ left.length === right.length &&
+ left.every((segment, index) => segment === right[index]);
+
+const hasWhereCondition = ({
+ where,
+ field,
+ operator,
+ value,
+ normalizeExpression = (expression: string) => expression,
+}: {
+ where: StructuredAssetQueryWhereBinding;
+ field: readonly string[];
+ operator: string;
+ value: string;
+ normalizeExpression?: (expression: string) => string;
+}) =>
+ getQueryConditions(where).some(
+ (condition) =>
+ pathsEqual(condition.field, field) &&
+ condition.operator === operator &&
+ typeof condition.value === "string" &&
+ normalizeExpression(condition.value) === normalizeExpression(value)
+ );
+
+const getMemberPath = (value: unknown): string[] | undefined => {
+ if (typeof value !== "object" || value === null || !("type" in value)) {
+ return;
+ }
+ if (value.type === "ChainExpression" && "expression" in value) {
+ return getMemberPath(value.expression);
+ }
+ if (
+ value.type === "Identifier" &&
+ "name" in value &&
+ typeof value.name === "string"
+ ) {
+ return [value.name];
+ }
+ if (
+ value.type !== "MemberExpression" ||
+ !("object" in value) ||
+ !("property" in value)
+ ) {
+ return;
+ }
+ const objectPath = getMemberPath(value.object);
+ if (objectPath === undefined) {
+ return;
+ }
+ const property = value.property;
+ if (
+ typeof property !== "object" ||
+ property === null ||
+ !("type" in property)
+ ) {
+ return;
+ }
+ const computed = "computed" in value && value.computed === true;
+ if (
+ computed === false &&
+ property.type === "Identifier" &&
+ "name" in property &&
+ typeof property.name === "string"
+ ) {
+ return [...objectPath, property.name];
+ }
+ if (
+ property.type === "Literal" &&
+ "value" in property &&
+ (typeof property.value === "string" || typeof property.value === "number")
+ ) {
+ return [...objectPath, String(property.value)];
+ }
+};
+
+const getExpressionMemberPaths = (expression: string) => {
+ const paths = new Set<string>();
+ const visit = (value: unknown): void => {
+ if (typeof value !== "object" || value === null) {
+ return;
+ }
+ const path = getMemberPath(value);
+ if (path !== undefined) {
+ paths.add(path.join("."));
+ }
+ for (const child of Object.values(value)) {
+ visit(child);
+ }
+ };
+ try {
+ visit(parseExpressionAt(expression, 0, { ecmaVersion: "latest" }));
+ } catch {}
+ return paths;
};
+const hasOutputField = (output: unknown, field: string[]) =>
+ typeof output === "object" &&
+ output !== null &&
+ "fields" in output &&
+ Array.isArray(output.fields) &&
+ output.fields.some((candidate) => pathsEqual(candidate, field));
+
+const hasSort = (
+ sort: unknown,
+ expected: Array<{ field: string[]; direction: string }>
+) =>
+ Array.isArray(sort) &&
+ sort.length === expected.length &&
+ expected.every(
+ (item, index) =>
+ typeof sort[index] === "object" &&
+ sort[index] !== null &&
+ pathsEqual(sort[index].field, item.field) &&
+ sort[index].direction === item.direction
+ );
+
const validateMarkdownBlog = (
input: HighImpactEvaluationInput,
checks: Record<string, "passed" | "failed">,
failures: string[]
) => {
+ if (input.fixture.id === markdownReferencesDiscoveryFixture.id) {
+ const guidanceIndex = input.toolCalls.findIndex(
+ (call) => call.name === "meta.guide" && call.isError !== true
+ );
+ const toolDiscoveryIndex = input.toolCalls.findIndex(
+ (call) => call.name === "meta.get_more_tools" && call.isError !== true
+ );
+ const toolDiscoveryCount = input.toolCalls.filter(
+ (call) => call.name === "meta.get_more_tools"
+ ).length;
+ recordCheck(
+ checks,
+ failures,
+ "referenceDocumentationDiscovery",
+ guidanceIndex !== -1 &&
+ toolDiscoveryIndex > guidanceIndex &&
+ toolDiscoveryCount === 1,
+ "The reference workflow must use guidance followed by exactly one focused tool discovery call."
+ );
+ recordCheck(
+ checks,
+ failures,
+ "retryFreeExecution",
+ hasMcpToolCallRetries(input.toolCalls) === false &&
+ input.toolCalls.every((call) => call.planned !== true),
+ "The document-reference workflow retried or dry-ran a mutation."
+ );
+ }
const expectedNames = new Set<string>(
markdownBlogFixtureArticles.map((article) => article.name)
);
+ const expectedDocumentNames = new Set<string>(
+ markdownBlogFixtureDocuments.map((document) => document.name)
+ );
+ const documentAssets = input.project.assets.filter(
+ (asset) => asset.type === "file"
+ );
const markdownAssets = input.project.assets.filter(
(asset) => asset.type === "file" && asset.format === "md"
);
- const folderIds = new Set(markdownAssets.map((asset) => asset.folderId));
+ const folderIds = new Set(documentAssets.map((asset) => asset.folderId));
const blogFolder = input.project.assetFolders.find(
(folder) => folder.name === "Blog"
);
@@ -584,6 +751,17 @@ const validateMarkdownBlog = (
markdownAssets.every((asset) => expectedNames.has(asset.name)),
"The five supplied Markdown articles were not uploaded as distinct file assets."
);
+ recordCheck(
+ checks,
+ failures,
+ "documentGraphSources",
+ documentAssets.length === expectedDocumentNames.size &&
+ documentAssets.every(
+ (asset) =>
+ expectedDocumentNames.has(asset.name) && asset.format === "md"
+ ),
+ "Only the supplied Markdown source documents should be uploaded."
+ );
recordCheck(
checks,
failures,
@@ -605,6 +783,31 @@ const validateMarkdownBlog = (
);
const configurations = getAssetResourceConfigurations(input.project);
+ const dataSourceNameById = new Map(
+ input.project.dataSources.map((dataSource) => [
+ String(dataSource.id),
+ String(dataSource.name),
+ ])
+ );
+ const normalizeExpression = (expression: string) => {
+ try {
+ return transpileExpression({
+ expression,
+ replaceVariable: (identifier) => {
+ const dataSourceId = decodeDataSourceVariable(identifier);
+ if (dataSourceId === undefined) {
+ return identifier;
+ }
+ if (dataSourceId === ":system") {
+ return "system";
+ }
+ return dataSourceNameById.get(dataSourceId) ?? identifier;
+ },
+ });
+ } catch {
+ return expression;
+ }
+ };
const findConfigurationByDataSourceName = (name: string) => {
const resourceId = input.project.dataSources.find(
(dataSource) => dataSource.type === "resource" && dataSource.name === name
@@ -645,22 +848,35 @@ const validateMarkdownBlog = (
failures,
"listingQuery",
listing !== undefined &&
- hasQueryFragment(listing.where, [
- "extension",
- "md",
- "draft",
- "ne",
- "true",
- ]) &&
- hasQueryFragment(listing.sort, ["publishedAt", "desc", "id", "asc"]) &&
- hasQueryFragment(listing.limit, ["20"]) &&
- hasQueryFragment(listing.output, [
- "fields",
- "title",
- "slug",
- "publishedAt",
- "excerpt",
+ blogFolder !== undefined &&
+ hasWhereCondition({
+ where: listing.where,
+ field: ["extension"],
+ operator: "eq",
+ value: '"md"',
+ }) &&
+ hasWhereCondition({
+ where: listing.where,
+ field: ["folderId"],
+ operator: "eq",
+ value: JSON.stringify(blogFolder.id),
+ }) &&
+ hasWhereCondition({
+ where: listing.where,
+ field: ["properties", "draft"],
+ operator: "ne",
+ value: "true",
+ normalizeExpression,
+ }) &&
+ hasSort(listing.sort, [
+ { field: ["properties", "publishedAt"], direction: "desc" },
+ { field: ["id"], direction: "asc" },
]) &&
+ listing.limit === "20" &&
+ ["title", "slug", "publishedAt"].every((field) =>
+ hasOutputField(listing.output, ["properties", field])
+ ) &&
+ hasOutputField(listing.output, ["properties", "excerpt"]) &&
listing.output.includeMetadata === false,
"The overview Assets resource is not a bounded metadata-only published-post query."
);
@@ -669,43 +885,110 @@ const validateMarkdownBlog = (
failures,
"detailQuery",
article !== undefined &&
+ blogFolder !== undefined &&
article.content.mode === "markdown-body" &&
- hasQueryFragment(article.where, [
- "extension",
- "md",
- "slug",
- "system.params.slug",
- ]) &&
- hasQueryFragment(article.limit, ["1"]) &&
+ hasWhereCondition({
+ where: article.where,
+ field: ["extension"],
+ operator: "eq",
+ value: '"md"',
+ }) &&
+ hasWhereCondition({
+ where: article.where,
+ field: ["folderId"],
+ operator: "eq",
+ value: JSON.stringify(blogFolder.id),
+ }) &&
+ hasWhereCondition({
+ where: article.where,
+ field: ["properties", "slug"],
+ operator: "eq",
+ value: "system.params.slug",
+ normalizeExpression,
+ }) &&
+ article.limit === "1" &&
article.output.includeMetadata === false &&
- article.content.maxBytes === 1_048_576,
- "The detail Assets resource does not select one Markdown body by the dynamic slug parameter."
+ hasOutputField(article.output, ["properties", "body"]) === false,
+ "The detail Assets resource does not defer one Markdown body selected by the dynamic slug parameter."
+ );
+ recordCheck(
+ checks,
+ failures,
+ "documentGraphQueries",
+ listing !== undefined &&
+ article !== undefined &&
+ hasOutputField(listing.output, ["properties", "author"]) &&
+ hasOutputField(article.output, ["properties", "author"]),
+ "Both blog Assets resources must select the frontmatter author."
+ );
+ const contentDatabase = input.contentDatabase;
+ const maximumOptimalBytes = markdownBlogFixtureDocuments.length * 1_300;
+ recordCheck(
+ checks,
+ failures,
+ "optimalBlogDatabase",
+ contentDatabase !== undefined &&
+ contentDatabase.usedBytes <= maximumOptimalBytes &&
+ contentDatabase.usedBytes === contentDatabase.unboundedBytes &&
+ contentDatabase.maxBytes === 500 * 1024 &&
+ contentDatabase.sourceDocumentCount ===
+ markdownBlogFixtureDocuments.length &&
+ contentDatabase.includedDocumentCount ===
+ markdownBlogFixtureDocuments.length &&
+ contentDatabase.omittedDocumentCount === 0 &&
+ contentDatabase.materializedQueryCount === 1 &&
+ contentDatabase.documentGraphNodeCount <=
+ markdownBlogFixtureDocuments.length &&
+ contentDatabase.documentGraphEdgeCount === 0 &&
+ contentDatabase.embeddedContentBytes === 0,
+ "The compiled blog database is duplicated, truncated, embeds Markdown bodies, or exceeds the optimized size budget."
);
- const overviewSource = JSON.stringify({
- instances: overview.instances,
- props: input.project.props.filter((prop) =>
- overview.instances.some((instance) => instance.id === prop.instanceId)
- ),
- });
- const detailSource = JSON.stringify({
- instances: detail.instances,
- props: input.project.props.filter((prop) =>
- detail.instances.some((instance) => instance.id === prop.instanceId)
- ),
- });
+ const getPageExpressionPaths = (instances: EvaluationInstance[]) => {
+ const instanceIds = new Set(instances.map((instance) => instance.id));
+ const expressions = [
+ ...instances.flatMap((instance) =>
+ instance.children.flatMap((child) =>
+ child.type === "expression" ? [child.value] : []
+ )
+ ),
+ ...input.project.props.flatMap((prop) =>
+ instanceIds.has(prop.instanceId) && prop.type === "expression"
+ ? [String(prop.value)]
+ : []
+ ),
+ ];
+ return new Set(
+ expressions.flatMap((expression) => [
+ ...getExpressionMemberPaths(normalizeExpression(expression)),
+ ])
+ );
+ };
+ const overviewExpressionPaths = getPageExpressionPaths(overview.instances);
+ const detailExpressionPaths = getPageExpressionPaths(detail.instances);
recordCheck(
checks,
failures,
"editableBlogBindings",
- /Collection/i.test(overviewSource) &&
- ["title", "excerpt", "publishedAt", "slug"].every((field) =>
- overviewSource.includes(field)
+ overview.instances.some((instance) =>
+ instance.component.toLowerCase().endsWith("collection")
+ ) &&
+ [
+ "collectionItem.properties.title",
+ "collectionItem.properties.excerpt",
+ "collectionItem.properties.publishedAt",
+ "collectionItem.properties.slug",
+ "collectionItem.properties.author.name",
+ ].every((expression) => overviewExpressionPaths.has(expression)) &&
+ detail.instances.some((instance) =>
+ instance.component.toLowerCase().endsWith("collection")
+ ) &&
+ detail.instances.some((instance) =>
+ instance.component.toLowerCase().endsWith("markdownembed")
) &&
- /Collection/i.test(detailSource) &&
- /MarkdownEmbed/i.test(detailSource) &&
- hasQueryFragment(detailSource, ["content", "text"]),
- "The blog is not rendered through editable Collections and a Markdown Embed with the required bindings."
+ detailExpressionPaths.has("collectionItem.content.text") &&
+ detailExpressionPaths.has("collectionItem.properties.author.name"),
+ "The blog is not rendered through editable Collections, author bindings, and a Markdown Embed."
);
recordCheck(
checks,
@@ -764,7 +1047,10 @@ export const evaluateHighImpactOutcome = (
validateAuth(input, checks, failures);
} else if (input.fixture.id === fontAssetsFixture.id) {
validateFontAssets(input, checks, failures);
- } else if (input.fixture.id === markdownBlogFixture.id) {
+ } else if (
+ input.fixture.id === markdownBlogFixture.id ||
+ input.fixture.id === markdownReferencesDiscoveryFixture.id
+ ) {
validateMarkdownBlog(input, checks, failures);
} else {
validateDesign(input, checks, failures);
diff --git a/packages/cli/package.json b/packages/cli/package.json
index bcedeb6341..f77dc3ac63 100644
--- a/packages/cli/package.json
+++ b/packages/cli/package.json
@@ -21,7 +21,7 @@
"build:content-runtime": "esbuild @webstudio-is/content-engine/runtime --bundle --format=esm --platform=browser --target=es2022 --conditions=webstudio --minify --outfile=lib/content-runtime.js",
"build": "pnpm generate-docs && rm -rf lib && vite build && pnpm build:content-runtime",
"pretest": "mkdir -p lib && pnpm build:content-runtime",
- "evaluations": "tsx --conditions=webstudio evaluations/high-impact/run-local-agent.ts",
+ "evaluations": "tsx --import ../../scripts/register-react-global.ts --conditions=webstudio evaluations/high-impact/run-local-agent.ts",
"test": "vitest run",
"test:release-smoke": "pnpm build && tsx --conditions=webstudio scripts/release-smoke.ts",
"test:release-smoke:model": "WEBSTUDIO_RELEASE_SMOKE_MODEL_EVAL_REQUIRED=1 pnpm test:release-smoke",
diff --git a/packages/cli/src/commands/api-command-docs.test.ts b/packages/cli/src/commands/api-command-docs.test.ts
index 6bb6617ad8..7459943d49 100644
--- a/packages/cli/src/commands/api-command-docs.test.ts
+++ b/packages/cli/src/commands/api-command-docs.test.ts
@@ -221,6 +221,24 @@ test("documents storage-efficient Assets queries for agents", () => {
}
});
+test("directs agents to deferred Markdown bodies", () => {
+ for (const document of ["api-use-cases", "manual-llm"] as const) {
+ const contents = readCliDoc(document);
+ expect(contents).toContain('content.mode:"markdown-body"');
+ expect(contents).toContain("document reference");
+ expect(contents).toContain("selected Markdown");
+ expect(contents).toContain("content.text");
+ }
+
+ const tools = createMetadataOnlyMcpAdapter().listTools();
+ for (const name of ["create-assets-resource", "update-assets-resource"]) {
+ const description = tools.find((tool) => tool.name === name)?.description;
+ expect(description).toContain("markdown-body");
+ expect(description).toContain("document reference");
+ expect(description).toContain("item.content.text");
+ }
+});
+
test("documents MCP examples with current tool input fields", () => {
const adapter = createMetadataOnlyMcpAdapter();
const toolInputFields = new Map(
diff --git a/packages/cli/src/commands/preview.test.ts b/packages/cli/src/commands/preview.test.ts
index da5d7abddc..025e8eb229 100644
--- a/packages/cli/src/commands/preview.test.ts
+++ b/packages/cli/src/commands/preview.test.ts
@@ -171,6 +171,7 @@ test("prepares preview by syncing missing data and generating the app template",
assets: true,
template: ["react-router"],
previewIdentity: true,
+ sourceAssetsDirectory: join(cwd(), ".webstudio", "assets"),
});
expect(result.cwd).toBe(getPreviewProjectDir());
});
@@ -201,6 +202,7 @@ test("prepares local verification previews with draft routes", async () => {
template: ["react-router"],
includeDraftPages: true,
previewIdentity: true,
+ sourceAssetsDirectory: join(cwd(), ".webstudio", "assets"),
});
});
@@ -263,6 +265,7 @@ test("generates preview project in isolated directory", async () => {
assets: true,
template: ["react-router"],
previewIdentity: true,
+ sourceAssetsDirectory: join(expectedPreviewProjectDir, "..", "assets"),
});
expect(ensureDependencies).toHaveBeenCalledOnce();
});
@@ -319,6 +322,7 @@ test("regenerates a production cache before using it for iterative preview", asy
"cache-key"
);
chdir(projectDir);
+ const sourceAssetsDirectory = join(cwd(), ".webstudio", "assets");
try {
const result = await preparePreviewProject({
assets: true,
@@ -341,6 +345,7 @@ test("regenerates a production cache before using it for iterative preview", asy
template: ["react-router"],
preserveRouteTemplates: true,
previewIdentity: true,
+ sourceAssetsDirectory,
});
});
@@ -576,6 +581,7 @@ test("materializes session data before previewing from session source", async ()
assets: true,
template: ["react-router"],
previewIdentity: true,
+ sourceAssetsDirectory: join(expectedPreviewProjectDir, "..", "assets"),
});
});
@@ -657,6 +663,7 @@ test("keeps the standalone React Router preview template", async () => {
assets: true,
template: ["react-router"],
previewIdentity: true,
+ sourceAssetsDirectory: join(cwd(), ".webstudio", "assets"),
});
});
diff --git a/packages/cli/src/commands/preview.ts b/packages/cli/src/commands/preview.ts
index 7acec4bdef..c2878593a0 100644
--- a/packages/cli/src/commands/preview.ts
+++ b/packages/cli/src/commands/preview.ts
@@ -542,6 +542,7 @@ export const preparePreviewProject = async ({
assets,
template: getPreviewTemplates(template),
previewIdentity: true,
+ sourceAssetsDirectory: join(projectDir, LOCAL_ASSETS_DIR),
...(silent ? { silent: true } : {}),
...(includeDraftPages ? { includeDraftPages: true } : {}),
...(reuseGeneratedProject ? { incremental: true } : {}),
diff --git a/packages/cli/src/docs.generated.ts b/packages/cli/src/docs.generated.ts
index 3c437f1be4..4919153751 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## 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',
+ '# 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"],["properties","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"}},{"field":["properties","slug"],"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"}}}\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":["extension"],"operator":"eq","value":"md"},{"field":["properties","slug"],"operator":"eq","value":"hello-world"}]},"limit":1,"output":{"mode":"fields","includeMetadata":false,"fields":[["properties","title"]]},"content":{"mode":"markdown-body"}}}\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- Every reachable Assets data source contributes to the shared published database. Keep one final resource per rendered query. Update an existing scoped resource rather than creating a placeholder, preview copy, or repair replacement, and remove obsolete duplicates.\n- Keep bounded overview filters, limits, and offsets literal and add a deterministic ID tie-breaker to the sort. With `content.mode:"none"`, compilation can materialize the small overview result instead of retaining its output fields across every candidate document. Use runtime expressions only for genuinely dynamic values such as the detail slug.\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- Query Markdown files directly and use `content.mode:"markdown-body"` when rendering their bodies. The published database retains metadata and a document reference, then fetches only the selected Markdown files from Asset storage at runtime; it does not embed their bodies. Filter and paginate before content is loaded.\n- `full` and bounded `range` continue to request embedded file bytes. Use them only when the caller requires the complete source or a byte range.\n- In Markdown, reference sibling Assets with conventional relative URLs such as `../images/hero.png`. Deferred `markdown-body` content 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. A completed Markdown blog should include every source document without truncation, contain no embedded Markdown bodies, and retain only its intended materialized overview query. When merged usage approaches the limit, remove duplicate reachable resources first, then unused output fields, then narrow candidate files.\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`, and a resolved Markdown body 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, 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',
+ '# 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- Every reachable Assets data source contributes to the shared database. Keep one final resource per rendered query. Update an existing scoped resource instead of creating a placeholder, preview copy, or repair replacement, and remove obsolete duplicate resources and data sources.\n- Make a bounded overview fully static: use literal values for its filters, limit, and offset, add a deterministic ID tie-breaker to its sort, and use `content.mode:"none"`. This lets compilation materialize the small overview result instead of retaining overview-only fields across every candidate article. Reserve runtime expressions for values that are truly dynamic, such as `system.params.slug` on the detail route.\n- Query Markdown files directly and use `content.mode:"markdown-body"` when rendering their bodies. The published database keeps only metadata and document references, filters and paginates first, and fetches the selected Markdown bodies from Asset storage at runtime. Do not create companion JSON descriptors merely to avoid embedding Markdown.\n- `full` and bounded `range` request embedded file bytes. Use them only when the caller explicitly requires the complete source or a byte range.\n- Deferred Markdown bodies exclude frontmatter and resolve 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` and the resolved Markdown body 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. A finished Markdown blog must include every source document without truncation, contain no embedded Markdown bodies, and retain only the intended materialized overview query. When merged usage approaches the limit, remove duplicate reachable resources first, then unused output fields, then narrow candidate files. 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":
@@ -86,10 +86,13 @@ export const cliDocSections = {
"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, 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 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__.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.",
+ "Every reachable Assets data source contributes to the shared database. Keep one final resource per rendered query. Update an existing scoped resource instead of creating a placeholder, preview copy, or repair replacement, and remove obsolete duplicate resources and data sources.",
+ 'Make a bounded overview fully static: use literal values for its filters, limit, and offset, add a deterministic ID tie-breaker to its sort, and use content.mode:"none". This lets compilation materialize the small overview result instead of retaining overview-only fields across every candidate article. Reserve runtime expressions for values that are truly dynamic, such as system.params.slug on the detail route.',
+ 'Query Markdown files directly and use content.mode:"markdown-body" when rendering their bodies. The published database keeps only metadata and document references, filters and paginates first, and fetches the selected Markdown bodies from Asset storage at runtime. Do not create companion JSON descriptors merely to avoid embedding Markdown.',
+ "full and bounded range request embedded file bytes. Use them only when the caller explicitly requires the complete source or a byte range.",
+ "Deferred Markdown bodies exclude frontmatter and resolve 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 and the resolved Markdown body from item.content.text.",
+ "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. A finished Markdown blog must include every source document without truncation, contain no embedded Markdown bodies, and retain only the intended materialized overview query. When merged usage approaches the limit, remove duplicate reachable resources first, then unused output fields, then narrow candidate files. 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 511c13abd3..b44d49ef76 100644
--- a/packages/cli/src/docs/api-use-cases.md
+++ b/packages/cli/src/docs/api-use-cases.md
@@ -735,23 +735,26 @@ Commands:
- MCP tool: get-asset-field-catalog {}
- 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":{"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: 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"],["properties","excerpt"]]},"content":{"mode":"none"}}}
+- 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"}},{"field":["properties","slug"],"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"}}}
- MCP tool: list-assets-resources {}
- MCP tool: get-assets-resource {"resourceId":"<resourceId>"}
- MCP tool: update-assets-resource {"resourceId":"<resourceId>","values":{"query":null}}
-- MCP tool: preview-asset-query {"query":{"where":{"all":[{"field":["properties","slug"],"operator":"eq","value":"hello-world"}]},"limit":1,"content":{"mode":"markdown-body","maxBytes":1048576}}}
+- MCP tool: preview-asset-query {"query":{"where":{"all":[{"field":["extension"],"operator":"eq","value":"md"},{"field":["properties","slug"],"operator":"eq","value":"hello-world"}]},"limit":1,"output":{"mode":"fields","includeMetadata":false,"fields":[["properties","title"]]},"content":{"mode":"markdown-body"}}}
Notes:
- 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.
- 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.
+- Every reachable Assets data source contributes to the shared published database. Keep one final resource per rendered query. Update an existing scoped resource rather than creating a placeholder, preview copy, or repair replacement, and remove obsolete duplicates.
+- Keep bounded overview filters, limits, and offsets literal and add a deterministic ID tie-breaker to the sort. With `content.mode:"none"`, compilation can materialize the small overview result instead of retaining its output fields across every candidate document. Use runtime expressions only for genuinely dynamic values such as the detail slug.
- 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.
-- 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.
+- Query Markdown files directly and use `content.mode:"markdown-body"` when rendering their bodies. The published database retains metadata and a document reference, then fetches only the selected Markdown files from Asset storage at runtime; it does not embed their bodies. Filter and paginate before content is loaded.
+- `full` and bounded `range` continue to request embedded file bytes. Use them only when the caller requires the complete source or a byte range.
+- In Markdown, reference sibling Assets with conventional relative URLs such as `../images/hero.png`. Deferred `markdown-body` content 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__.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`.
+- 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. A completed Markdown blog should include every source document without truncation, contain no embedded Markdown bodies, and retain only its intended materialized overview query. When merged usage approaches the limit, remove duplicate reachable resources first, then unused output fields, then narrow candidate files.
+- 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`, and a resolved Markdown body 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.
- The shared metadata index is maintained automatically and is emitted only when a configured Assets resource is reachable.
diff --git a/packages/cli/src/docs/manual-llm.md b/packages/cli/src/docs/manual-llm.md
index 93d0dfdff2..96a94c3a2e 100644
--- a/packages/cli/src/docs/manual-llm.md
+++ b/packages/cli/src/docs/manual-llm.md
@@ -462,10 +462,13 @@ Before authoring unfamiliar expressions, read `webstudio://project/expressions`
- 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, 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 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__.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.
+- Every reachable Assets data source contributes to the shared database. Keep one final resource per rendered query. Update an existing scoped resource instead of creating a placeholder, preview copy, or repair replacement, and remove obsolete duplicate resources and data sources.
+- Make a bounded overview fully static: use literal values for its filters, limit, and offset, add a deterministic ID tie-breaker to its sort, and use `content.mode:"none"`. This lets compilation materialize the small overview result instead of retaining overview-only fields across every candidate article. Reserve runtime expressions for values that are truly dynamic, such as `system.params.slug` on the detail route.
+- Query Markdown files directly and use `content.mode:"markdown-body"` when rendering their bodies. The published database keeps only metadata and document references, filters and paginates first, and fetches the selected Markdown bodies from Asset storage at runtime. Do not create companion JSON descriptors merely to avoid embedding Markdown.
+- `full` and bounded `range` request embedded file bytes. Use them only when the caller explicitly requires the complete source or a byte range.
+- Deferred Markdown bodies exclude frontmatter and resolve 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` and the resolved Markdown body from `item.content.text`.
+- 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. A finished Markdown blog must include every source document without truncation, contain no embedded Markdown bodies, and retain only the intended materialized overview query. When merged usage approaches the limit, remove duplicate reachable resources first, then unused output fields, then narrow candidate files. 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/filesystem-content-source.test.ts b/packages/cli/src/filesystem-content-source.test.ts
index 09dfa9299d..141cd1e67f 100644
--- a/packages/cli/src/filesystem-content-source.test.ts
+++ b/packages/cli/src/filesystem-content-source.test.ts
@@ -5,6 +5,7 @@ import {
createContentCompilationPlan,
createLiteralContentCompilationQuery,
} from "@webstudio-is/content-engine";
+import { readBoundedBytes } from "@webstudio-is/content-engine/compiler";
import type { Asset, AssetFolders } from "@webstudio-is/sdk";
import { afterEach, describe, expect, test } from "vitest";
import { createFileSystemContentSource } from "./filesystem-content-source";
@@ -104,6 +105,12 @@ describe("filesystem content source", () => {
},
},
]);
+ const [documentSource] = (await snapshot.loadDocumentSources?.()) ?? [];
+ expect(documentSource?.id).toBe("post");
+ const documentText = new TextDecoder().decode(
+ await readBoundedBytes(documentSource?.source ?? "", content.length)
+ );
+ expect(documentText).toBe(content);
await expect(snapshot.isCurrent()).resolves.toBe(true);
});
diff --git a/packages/cli/src/filesystem-content-source.ts b/packages/cli/src/filesystem-content-source.ts
index efd1b343a9..9adb48e6d4 100644
--- a/packages/cli/src/filesystem-content-source.ts
+++ b/packages/cli/src/filesystem-content-source.ts
@@ -11,6 +11,7 @@ import {
type ContentSource,
} from "@webstudio-is/content-engine/compiler";
import {
+ getDocumentFormatByContentType,
isContentDocumentCandidate,
prepareContentCompilerEntries,
requiresStructuredProperties,
@@ -214,6 +215,29 @@ export const createFileSystemContentSource = ({
return {
revision,
files: captured.map(({ entry }) => createContentSourceFile(entry)),
+ loadDocumentSources: async () =>
+ captured
+ .filter(
+ ({ entry }) =>
+ getDocumentFormatByContentType(entry.document.mimeType) !==
+ undefined
+ )
+ .map(({ entry, filePath, identity }) => ({
+ id: entry.assetId,
+ source: {
+ async *[Symbol.asyncIterator]() {
+ const bytes = await readSnapshotFile({
+ path: filePath,
+ identity,
+ maximumBytes: entry.document.size,
+ });
+ if (bytes.byteLength !== entry.document.size) {
+ throw new Error("Content source file size changed");
+ }
+ yield bytes;
+ },
+ },
+ })),
loadEntries: async (
plan?: ContentCompilationPlan,
options?: { maximumContentBytes: number }
diff --git a/packages/cli/src/prebuild.test.ts b/packages/cli/src/prebuild.test.ts
index d6533685a1..34c86de519 100644
--- a/packages/cli/src/prebuild.test.ts
+++ b/packages/cli/src/prebuild.test.ts
@@ -17,10 +17,14 @@ import { execFile } from "node:child_process";
import { promisify } from "node:util";
import { bundleVersion } from "@webstudio-is/protocol";
import type { Asset } from "@webstudio-is/sdk";
-import type { AssetFileDocument } from "@webstudio-is/content-engine";
+import {
+ createDocumentGraph,
+ type AssetFileDocument,
+} from "@webstudio-is/content-engine";
import {
createAssetIndex,
createCanonicalAssetFileEntry,
+ createContentRuntimeArtifact,
} from "@webstudio-is/content-engine/compiler";
import { createPublishedAssetResourceFetch } from "@webstudio-is/content-engine/runtime";
import {
@@ -36,13 +40,14 @@ import {
const createSsgAssetResourceFetch = (options: {
deploymentId: string;
- artifact: Parameters<typeof createPublishedAssetResourceFetch>[0]["artifact"];
+ artifact: Parameters<typeof createContentRuntimeArtifact>[0];
runtimeAssets: Parameters<
typeof createPublishedAssetResourceFetch
>[0]["runtimeAssets"];
}) =>
createPublishedAssetResourceFetch({
...options,
+ artifact: createContentRuntimeArtifact(options.artifact),
baseUrl: "https://webstudio.local",
});
@@ -382,7 +387,9 @@ const createTestAssetIndex = (
),
});
-const createQueryResource = (content: "none" | "full" = "none"): Resource => ({
+const createQueryResource = (
+ content: "none" | "full" | "markdown-body" = "none"
+): Resource => ({
id: "posts",
name: "Posts",
control: "system",
@@ -422,6 +429,9 @@ test("embeds one shared content database in a server module", async () => {
expect(manifestModule).toContain('assetQueryDeploymentId = "build-1"');
expect(manifestModule).toContain('"documents"');
expect(manifestModule).toContain('"properties"');
+ expect(manifestModule).not.toContain('"fieldCatalog"');
+ expect(manifestModule).not.toContain('"database"');
+ expect(manifestModule).not.toContain('"integrity"');
const runtimeModule = await readFile(
"app/__generated__/$resources.asset-query-runtime.ts",
"utf8"
@@ -969,6 +979,9 @@ describe("prebuild", () => {
await expect(readFile("vite.config.ts", "utf8")).resolves.toContain(
'["webstudio"]'
);
+ await expect(readFile("vite.config.ts", "utf8")).resolves.toContain(
+ 'noExternal: ["nanoid"]'
+ );
await expect(
readFile("app/__generated__/$resources.redirects.ts", "utf8")
).resolves.toContain("/dl.php?filename=file.pdf");
@@ -1262,6 +1275,93 @@ describe("prebuild", () => {
).rejects.toThrow("ENOENT");
});
+ test("loads deferred SaaS document content from the asset proxy", async () => {
+ const index = await createAssetIndex({
+ projectId: "project-1",
+ entries: [
+ createCanonicalAssetFileEntry({
+ projectId: "project-1",
+ document: indexedDocument,
+ }),
+ ],
+ documentGraph: createDocumentGraph({
+ nodes: [
+ {
+ id: indexedDocument._id,
+ revision: indexedDocument.revision,
+ contentRef: indexedDocument.contentRef,
+ format: "markdown",
+ },
+ ],
+ edges: [],
+ }),
+ });
+ const baseSiteData = createSiteData({
+ assets: [createAssetForIndexedDocument(indexedDocument)],
+ });
+ const siteData = {
+ ...baseSiteData,
+ assetIndex: index,
+ build: {
+ ...baseSiteData.build,
+ deployment: {
+ destination: "saas" as const,
+ domains: ["example"],
+ assetsDomain: "example",
+ excludeWstdDomainFromSearch: false,
+ },
+ resources: [["posts", createQueryResource("markdown-body")]],
+ dataSources: [
+ [
+ "posts-data",
+ {
+ id: "posts-data",
+ type: "resource" as const,
+ name: "posts",
+ resourceId: "posts",
+ scopeInstanceId: "root",
+ },
+ ],
+ ],
+ },
+ };
+ await writeSiteData(
+ siteData as unknown as ReturnType<typeof createSiteData>
+ );
+
+ await prebuild({
+ assets: false,
+ template: ["react-router"],
+ preserveRouteTemplates: true,
+ });
+
+ const runtimeModule = await readFile(
+ "app/__generated__/$resources.asset-query-runtime.ts",
+ "utf8"
+ );
+ expect(runtimeModule).toContain(
+ '"url":"https://assets.example/cgi/asset/post.md?format=raw"'
+ );
+ expect(runtimeModule).not.toContain('"url":"/assets/post.md"');
+
+ await mkdir(".webstudio/assets", { recursive: true });
+ await writeFile(".webstudio/assets/post.md", "# Post\n", "utf8");
+ await prebuild({
+ assets: true,
+ template: ["react-router"],
+ preserveRouteTemplates: true,
+ });
+
+ const materializedRuntimeModule = await readFile(
+ "app/__generated__/$resources.asset-query-runtime.ts",
+ "utf8"
+ );
+ expect(materializedRuntimeModule).toContain('"url":"/assets/post.md"');
+ expect(materializedRuntimeModule).not.toContain(
+ '"url":"https://assets.example/cgi/asset/post.md?format=raw"'
+ );
+ });
+
test("uses pass-through images in the base react-router template", async () => {
await prebuild({ assets: false, template: ["react-router"] });
diff --git a/packages/cli/src/prebuild.ts b/packages/cli/src/prebuild.ts
index 4a7a8be830..ee93d814c0 100644
--- a/packages/cli/src/prebuild.ts
+++ b/packages/cli/src/prebuild.ts
@@ -60,13 +60,15 @@ import { collectFontFamiliesFromStyleDecls } from "@webstudio-is/project-build/r
import {
assetQueryFilter,
type AssetQueryFilter,
+ type ContentRuntimeArtifact,
type ContentDatabaseDocument,
+ createContentRuntimeArtifact,
getAssetQueryFieldValue,
getContentArtifactReferencedAssetIds,
- getContentArtifactRuntimeAssetIds,
+ getContentRuntimeArtifactRuntimeAssetIds,
matchesAssetQueryFilter,
requiresRuntimeDocumentData,
- serializeContentArtifact,
+ serializeContentRuntimeArtifact,
verifyContentArtifact,
} from "@webstudio-is/content-engine";
import { assetResourceLimits } from "@webstudio-is/sdk/asset-resource-limits";
@@ -505,8 +507,8 @@ const generateAssetQueryRuntimeModule = ({
runtimeAssets,
}: {
deploymentId: string;
- index: PublishedProjectBundle["assetIndex"];
- runtimeAssets: Readonly<Record<string, ReturnType<typeof toRuntimeAsset>>>;
+ index: ContentRuntimeArtifact | undefined;
+ runtimeAssets: Readonly<Record<string, ContentRuntimeAsset>>;
}) => {
const inputType = `{
request: Request;
@@ -532,6 +534,10 @@ export const createGeneratedAssetResourceFetch = ({ request, fallback }: ${input
`;
};
+type ContentRuntimeAsset = ReturnType<typeof toRuntimeAsset> & {
+ contentRef?: string;
+};
+
export const materializeAssetIndex = async ({
index,
runtimeAssets,
@@ -540,22 +546,26 @@ export const materializeAssetIndex = async ({
deploymentId,
}: {
index: PublishedProjectBundle["assetIndex"];
- runtimeAssets: Readonly<Record<string, ReturnType<typeof toRuntimeAsset>>>;
+ runtimeAssets: Readonly<Record<string, ContentRuntimeAsset>>;
includeDocumentRuntimeAssets: boolean;
generatedDirectory: string;
deploymentId: string;
}) => {
const verifiedIndex =
index === undefined ? undefined : await verifyContentArtifact(index);
- const serializedIndex =
+ const runtimeIndex =
verifiedIndex === undefined
? undefined
- : serializeContentArtifact(verifiedIndex);
+ : createContentRuntimeArtifact(verifiedIndex);
+ const serializedIndex =
+ runtimeIndex === undefined
+ ? undefined
+ : serializeContentRuntimeArtifact(runtimeIndex);
const runtimeAssetIds =
- verifiedIndex === undefined
+ runtimeIndex === undefined
? []
- : getContentArtifactRuntimeAssetIds({
- artifact: verifiedIndex,
+ : getContentRuntimeArtifactRuntimeAssetIds({
+ artifact: runtimeIndex,
includeDocuments: includeDocumentRuntimeAssets,
});
const referencedAssetIds = new Set(
@@ -563,6 +573,9 @@ export const materializeAssetIndex = async ({
? []
: getContentArtifactReferencedAssetIds(verifiedIndex)
);
+ const documentIds = new Set(
+ runtimeIndex?.documentGraph?.nodes.map(({ id }) => id) ?? []
+ );
const selectedRuntimeAssets = Object.fromEntries(
runtimeAssetIds.map((assetId) => {
const asset = runtimeAssets[assetId];
@@ -573,7 +586,11 @@ export const materializeAssetIndex = async ({
: `Published asset runtime data is unavailable for ${assetId}`
);
}
- return [assetId, asset];
+ if (documentIds.has(assetId)) {
+ return [assetId, asset];
+ }
+ const { contentRef: _contentRef, ...runtimeAsset } = asset;
+ return [assetId, runtimeAsset];
})
);
const runtimePath = join(generatedDirectory, contentRuntimeFile);
@@ -597,7 +614,7 @@ export const assetQueryDatabase = ${serializedIndex};
join(generatedDirectory, "$resources.asset-query-runtime.ts"),
generateAssetQueryRuntimeModule({
deploymentId,
- index: verifiedIndex,
+ index: runtimeIndex,
runtimeAssets: selectedRuntimeAssets,
}),
"utf8"
@@ -781,6 +798,8 @@ export const prebuild = async (options: {
preserveRouteTemplates?: boolean;
/** Emit a public identity marker used only by the local preview controller. */
previewIdentity?: boolean;
+ /** Read already-synced assets from this directory before downloading them. */
+ sourceAssetsDirectory?: string;
}) => {
const buildRoot = cwd();
const feedback = options.silent
@@ -1389,15 +1408,23 @@ export const prebuild = async (options: {
// Use a placeholder origin to preserve runtime metadata before overriding the
// builder-only URL with the generated project's local asset URL.
const assetsById = Object.fromEntries(
- siteData.assets.map((asset) => [
- asset.id,
- {
- ...toRuntimeAsset(asset, "https://placeholder.local"),
- // Generated projects serve materialized assets from the template's
- // asset base; the /cgi routes only exist in the live builder.
- url: `${assetBaseUrl}${asset.name}`,
- },
- ])
+ siteData.assets.map((asset) => {
+ const runtimeAsset = toRuntimeAsset(asset, "https://placeholder.local");
+ return [
+ asset.id,
+ {
+ ...runtimeAsset,
+ contentRef: asset.name,
+ // SaaS serves project assets through its storage-backed proxy.
+ // Generated projects with downloaded assets serve them locally.
+ url:
+ siteData.build.deployment?.destination === "saas" &&
+ options.assets === false
+ ? new URL(runtimeAsset.url, siteData.origin).href
+ : `${assetBaseUrl}${asset.name}`,
+ },
+ ];
+ })
);
const assetCompilationPlan = createReachableAssetContentCompilationPlan({
props: siteData.build.props.map(([, prop]) => prop),
@@ -1464,7 +1491,8 @@ export const prebuild = async (options: {
assets: siteData.assets,
continueOnError: true,
origin: siteData.origin || "",
- sourceAssetsDirectory: join(buildRoot, LOCAL_ASSETS_DIR),
+ sourceAssetsDirectory:
+ options.sourceAssetsDirectory ?? join(buildRoot, LOCAL_ASSETS_DIR),
targetAssetsDirectory: join(buildRoot, "public", assetBaseUrl),
});
downloading.stop("Downloaded assets");
diff --git a/packages/cli/templates/react-router/vite.config.ts b/packages/cli/templates/react-router/vite.config.ts
index f8a0782b3c..482f370c3a 100644
--- a/packages/cli/templates/react-router/vite.config.ts
+++ b/packages/cli/templates/react-router/vite.config.ts
@@ -13,6 +13,7 @@ export default defineConfig({
conditions: [...sourceConditions, "browser", "development|production"],
},
ssr: {
+ noExternal: ["nanoid"],
resolve: {
conditions: [...sourceConditions, "node", "development|production"],
},
diff --git a/packages/cli/templates/ssg/app/asset-resource-fetch.ts b/packages/cli/templates/ssg/app/asset-resource-fetch.ts
index ac9b4500dc..ec1b6c9a40 100644
--- a/packages/cli/templates/ssg/app/asset-resource-fetch.ts
+++ b/packages/cli/templates/ssg/app/asset-resource-fetch.ts
@@ -9,7 +9,10 @@ export const createSsgAssetResourceFetch = ({
}: {
deploymentId: string;
artifact: unknown;
- runtimeAssets: Record<string, { url: string; width?: number; height?: number }>;
+ runtimeAssets: Record<
+ string,
+ { url: string; contentRef?: string; width?: number; height?: number }
+ >;
}) =>
createPublishedAssetResourceFetch({
baseUrl: "https://webstudio.local",
diff --git a/packages/content-engine/README.md b/packages/content-engine/README.md
new file mode 100644
index 0000000000..741a057dbe
--- /dev/null
+++ b/packages/content-engine/README.md
@@ -0,0 +1,96 @@
+# Content engine
+
+The content engine compiles file-based Assets into a portable query database.
+JSON and Markdown documents can reference other Assets without embedding their
+complete source in that database.
+
+## Document references
+
+A reference is an object with exactly one `$ref` property whose value is a URI
+reference:
+
+```json
+{
+ "author": { "$ref": "./authors/ada.json" }
+}
+```
+
+References can appear at any depth in a JSON document. In Markdown, references
+can appear at any depth in YAML frontmatter:
+
+```markdown
+---
+title: Building with Markdown
+author:
+ $ref: ./authors/ada.json
+---
+
+Article body.
+```
+
+An object with additional properties is ordinary content, not a reference.
+The `$ref` spelling is familiar from JSON Schema, but this syntax does not
+implement JSON Schema resolution, identifiers, anchors, or schema evaluation.
+
+Reference paths use standard URI-reference resolution relative to the source
+document. The fragment selects which representation of the target to insert:
+
+| Reference | Selected target value |
+| ----------------------------- | ----------------------------------------------- |
+| `./author.json` | Complete JSON value |
+| `./author.json#/profile/name` | Value at the JSON Pointer `/profile/name` |
+| `./article.md` | Original Markdown source, including frontmatter |
+| `./article.md#body` | Markdown body without frontmatter |
+| `./article.md#frontmatter` | Markdown frontmatter as an object |
+
+JSON Pointer escaping follows RFC 6901. For example, `#/a~1b` selects the
+property named `a/b`. JSON Pointer fragments apply only to JSON documents;
+`#body` and `#frontmatter` apply only to Markdown documents.
+
+Authored URLs identify Assets during compilation. They do not permit arbitrary
+runtime network requests. Every target must match a document in the compiled
+Asset catalog.
+
+## Resolution behavior
+
+At build time, the content engine:
+
+1. Parses bounded JSON sources and Markdown frontmatter.
+2. Resolves each static URI reference to a document identity and revision.
+3. Rejects missing targets, duplicate identities, revision conflicts, and
+ dependency cycles.
+4. Stores the validated dependency graph with searchable metadata while source
+ payloads remain in Asset storage.
+
+At runtime, the server compares the query's filter, sort, and output property
+paths with the graph's reference locations. If a reference can affect the
+query, the server resolves the relevant source documents before executing the
+query; otherwise it uses the normal query path without loading graph sources.
+Non-reference filters first narrow the candidate sources. The server follows
+only root references that intersect the query, preserves unselected sibling
+markers, and computes the selected references' complete downstream dependency
+closure. It loads independent documents concurrently, loads shared storage
+content once, validates storage identities, revisions, formats, and payload
+limits, and assembles dependencies before their consumers. A resolved value
+replaces its exact `{ "$ref": "..." }` marker.
+
+Filtering, sorting, pagination, and projection therefore operate on resolved
+values when their property paths intersect a reference. Only properties
+selected by the Assets query are returned. Resolution cannot expose an
+unselected property merely because it exists in a fetched document.
+`markdown-body` content selection is also graph-backed. Compilation retains the
+Markdown document identity instead of its source bytes, and runtime hydration
+fetches only the documents selected after filtering, sorting, and pagination.
+The resolved query result continues to expose the body at `content.text`.
+Whole-document and range content modes retain their embedded-content behavior.
+
+Document source caches are keyed by storage reference, revision, and format, so
+content from one identity cannot be combined silently with different graph
+metadata. Published runtime assets must also point at the graph node's exact
+storage reference before the source is fetched. Resolution is bounded by
+document-count, per-document byte, aggregate-byte, and concurrency limits. A
+missing document, invalid representation, stale identity, limit violation, or
+cancellation fails the query instead of returning a partially assembled graph.
+
+Assets without a document graph keep the existing embedded-content behavior
+and do not require migration.
diff --git a/packages/content-engine/package.json b/packages/content-engine/package.json
index 6638454d6b..e8c9fbb636 100644
--- a/packages/content-engine/package.json
+++ b/packages/content-engine/package.json
@@ -16,6 +16,7 @@
"typecheck": "tsc --noEmit"
},
"dependencies": {
+ "@hyperjump/json-pointer": "1.1.2",
"@webstudio-is/expression": "workspace:*",
"@webstudio-is/query-builder": "workspace:*",
"canonicalize": "3.0.0",
diff --git a/packages/content-engine/src/asset-index.test.ts b/packages/content-engine/src/asset-index.test.ts
index 3d99db5c90..c3160e72b6 100644
--- a/packages/content-engine/src/asset-index.test.ts
+++ b/packages/content-engine/src/asset-index.test.ts
@@ -18,6 +18,7 @@ import {
serializeContentArtifact,
verifyContentArtifact,
} from "./content-artifact";
+import { createDocumentGraph } from "./document-graph";
const entry = ({
projectId = "project",
@@ -618,6 +619,67 @@ describe("shared asset index", () => {
).toBeGreaterThan(0);
});
+ test("keeps Markdown bodies embedded when no document graph is available", async () => {
+ const plan = createContentCompilationPlan([
+ createLiteralContentCompilationQuery({
+ id: "detail",
+ query: {
+ where: { all: [] },
+ sort: [],
+ limit: 1,
+ offset: 0,
+ output: {
+ mode: "fields",
+ includeMetadata: false,
+ fields: [["id"]],
+ },
+ content: { mode: "markdown-body" },
+ },
+ }),
+ ]);
+
+ const { artifact } = await compileContentArtifact({
+ projectId: "project",
+ entries: [{ ...entry({ id: "post" }), content: "Post body" }],
+ plan,
+ });
+
+ expect(artifact.contents).toEqual({
+ "files/post.md": "Post body",
+ });
+ });
+
+ test("keeps Markdown bodies embedded when their graph node is unavailable", async () => {
+ const plan = createContentCompilationPlan([
+ createLiteralContentCompilationQuery({
+ id: "detail",
+ query: {
+ where: { all: [] },
+ sort: [],
+ limit: 1,
+ offset: 0,
+ output: {
+ mode: "fields",
+ includeMetadata: false,
+ fields: [["id"]],
+ },
+ content: { mode: "markdown-body" },
+ },
+ }),
+ ]);
+
+ const { artifact } = await compileContentArtifact({
+ projectId: "project",
+ entries: [{ ...entry({ id: "post" }), content: "Post body" }],
+ plan,
+ documentGraph: createDocumentGraph({ nodes: [], edges: [] }),
+ });
+
+ expect(artifact.contents).toEqual({
+ "files/post.md": "Post body",
+ });
+ });
+
test("omits documents when their requested content was not materialized", async () => {
const plan = createContentCompilationPlan([
createLiteralContentCompilationQuery({
diff --git a/packages/content-engine/src/asset-index.ts b/packages/content-engine/src/asset-index.ts
index b6c3858e60..66833b862d 100644
--- a/packages/content-engine/src/asset-index.ts
+++ b/packages/content-engine/src/asset-index.ts
@@ -20,6 +20,7 @@ import {
isContentDocumentCandidate,
isContentCompilationFieldRequired,
projectContentDatabaseDocument,
+ selectContentHydrationCandidates,
type ContentCompilationPlan,
} from "./compilation-plan";
import { getUtf8ByteLength } from "./byte-stream";
@@ -28,6 +29,12 @@ import {
canMaterializeContentCompilationQuery,
materializeContentCompilationQueries,
} from "./materialized-query";
+import {
+ createDocumentGraphArtifact,
+ getDocumentGraphQueryRootIds,
+ type DocumentGraph,
+ type DocumentGraphArtifactV1,
+} from "./document-graph";
export type ContentCompilerDiagnostics = {
maxBytes: number;
@@ -60,6 +67,45 @@ export type ContentCompilerInput = CanonicalAssetFileEntry & {
contentRequired?: true;
};
+const excludeDeferredMarkdownBodies = ({
+ entries,
+ documentGraph,
+ plan,
+}: {
+ entries: readonly ContentCompilerInput[];
+ documentGraph: DocumentGraph;
+ plan?: ContentCompilationPlan;
+}) => {
+ if (plan === undefined) {
+ return entries;
+ }
+ const embeddedQueryPlan = {
+ ...plan,
+ queries: plan.queries.filter(
+ ({ content }) => content.mode !== "markdown-body"
+ ),
+ };
+ const embeddedIds = selectContentHydrationCandidates({
+ documents: entries.map(({ document }) => document),
+ plan: embeddedQueryPlan,
+ });
+ const graphNodeIds = new Set(documentGraph.nodes.map(({ id }) => id));
+ return entries.map((entry) => {
+ if (
+ embeddedIds.has(entry.assetId) ||
+ graphNodeIds.has(entry.assetId) === false
+ ) {
+ return entry;
+ }
+ const {
+ content: _content,
+ contentRequired: _contentRequired,
+ ...rest
+ } = entry;
+ return rest;
+ });
+};
+
const getEntryBytes = (
entry: ContentCompilerInput,
plan?: ContentCompilationPlan
@@ -137,6 +183,7 @@ const buildAssetIndex = async ({
maxBytes,
unboundedBytes,
assetReferences,
+ documentGraph,
plan,
finalize = true,
}: {
@@ -145,6 +192,7 @@ const buildAssetIndex = async ({
maxBytes: number;
unboundedBytes: number;
assetReferences?: MarkdownAssetReferences;
+ documentGraph?: DocumentGraphArtifactV1;
plan?: ContentCompilationPlan;
finalize?: boolean;
}) => {
@@ -152,6 +200,13 @@ const buildAssetIndex = async ({
const sourceCatalog = await createAssetFieldCatalog(entries);
const assetRevision = sourceCatalog.canonicalRevision;
const completeSourceFieldCatalog = toBuilderAssetFieldCatalog(sourceCatalog);
+ const materializableQueries =
+ plan?.queries.filter(
+ (query) =>
+ documentGraph === undefined ||
+ getDocumentGraphQueryRootIds({ graph: documentGraph, query }).length ===
+ 0
+ ) ?? [];
const materialized =
plan === undefined
? {
@@ -161,7 +216,7 @@ const buildAssetIndex = async ({
>(),
}
: await materializeContentCompilationQueries({
- queries: plan.queries,
+ queries: materializableQueries,
catalog: completeSourceFieldCatalog,
documents: sourceDocuments,
});
@@ -243,6 +298,7 @@ const buildAssetIndex = async ({
version: 1,
assetRevision,
documents,
+ ...(documentGraph === undefined ? {} : { documentGraph }),
...(Object.keys(contents).length === 0 ? {} : { contents }),
...(Object.keys(includedAssetReferences).length === 0
? {}
@@ -281,12 +337,14 @@ export const compileContentArtifact = async ({
entries,
maxBytes = contentEngineLimits.databaseBytes,
assetReferences,
+ documentGraph,
plan,
}: {
projectId: string;
entries: readonly ContentCompilerInput[];
maxBytes?: number;
assetReferences?: MarkdownAssetReferences;
+ documentGraph?: DocumentGraph;
plan?: ContentCompilationPlan;
}): Promise<{
artifact: ContentArtifactV1;
@@ -295,10 +353,23 @@ export const compileContentArtifact = async ({
if (Number.isSafeInteger(maxBytes) === false || maxBytes <= 0) {
throw new Error("Content database byte limit must be a positive integer");
}
+ if (documentGraph !== undefined) {
+ entries = excludeDeferredMarkdownBodies({ entries, documentGraph, plan });
+ }
validateEntries({ projectId, entries });
+ const documentGraphArtifact =
+ documentGraph === undefined
+ ? undefined
+ : await createDocumentGraphArtifact(documentGraph);
const sourceDocumentCount = entries.length;
const hasMaterializableQueries =
- plan?.queries.some(canMaterializeContentCompilationQuery) === true;
+ plan?.queries.some(
+ (query) =>
+ canMaterializeContentCompilationQuery(query) &&
+ (documentGraph === undefined ||
+ getDocumentGraphQueryRootIds({ graph: documentGraph, query })
+ .length === 0)
+ ) === true;
const unavailable = entries.filter(
(entry) => entry.contentRequired === true && entry.content === undefined
);
@@ -318,6 +389,7 @@ export const compileContentArtifact = async ({
maxBytes,
unboundedBytes,
assetReferences,
+ documentGraph: documentGraphArtifact,
plan,
finalize: false,
});
@@ -344,6 +416,7 @@ export const compileContentArtifact = async ({
maxBytes,
unboundedBytes,
assetReferences,
+ documentGraph: documentGraphArtifact,
plan,
finalize: false,
});
@@ -375,6 +448,7 @@ export const compileContentArtifact = async ({
maxBytes,
unboundedBytes,
assetReferences,
+ documentGraph: documentGraphArtifact,
plan,
finalize: false,
});
@@ -407,6 +481,7 @@ export const compileContentArtifact = async ({
maxBytes,
unboundedBytes,
assetReferences,
+ documentGraph: documentGraphArtifact,
plan,
});
const boundedBytes = getUtf8ByteLength(serializeContentArtifact(artifact));
@@ -457,6 +532,7 @@ export const createAssetIndex = async (input: {
entries: readonly ContentCompilerInput[];
maxBytes?: number;
assetReferences?: MarkdownAssetReferences;
+ documentGraph?: DocumentGraph;
plan?: ContentCompilationPlan;
}): Promise<ContentArtifactV1> =>
(await compileContentArtifact(input)).artifact;
diff --git a/packages/content-engine/src/blog-e2e.test.ts b/packages/content-engine/src/blog-e2e.test.ts
index 7bd317be56..7b413be729 100644
--- a/packages/content-engine/src/blog-e2e.test.ts
+++ b/packages/content-engine/src/blog-e2e.test.ts
@@ -2,6 +2,7 @@ import { describe, expect, test } from "vitest";
import type { AssetFileDocument } from "./schema";
import { createAssetIndex } from "./asset-index";
import { createCanonicalAssetFileEntry } from "./canonical";
+import { createContentRuntimeArtifact } from "./content-runtime-artifact";
import { createPublishedAssetResourceFetch } from "./published-runtime";
import { discoverMarkdownAssetReferenceRanges } from "./markdown-assets";
@@ -51,7 +52,7 @@ describe("published Markdown blog end-to-end", () => {
const runtimeFetch = createPublishedAssetResourceFetch({
baseUrl: "https://blog.example",
deploymentId: "blog-deployment",
- artifact: index,
+ artifact: createContentRuntimeArtifact(index),
runtimeAssets: {
"post-1": { url: "/assets/hello.md" },
"hero-image": { url: "/assets/hero.png", width: 1200, height: 630 },
diff --git a/packages/content-engine/src/compilation-plan.test.ts b/packages/content-engine/src/compilation-plan.test.ts
index d9120db254..d49082d20f 100644
--- a/packages/content-engine/src/compilation-plan.test.ts
+++ b/packages/content-engine/src/compilation-plan.test.ts
@@ -241,6 +241,62 @@ describe("content compilation plan", () => {
}
});
+ test("keeps candidates whose filter depends on a document reference", () => {
+ const plan = createContentCompilationPlan([
+ compilationQuery("referenced-author", {
+ ...query,
+ where: {
+ all: [
+ {
+ field: ["properties", "kind"],
+ operator: "eq",
+ value: "post",
+ },
+ {
+ field: ["properties", "author", "name"],
+ operator: "eq",
+ value: "Ada",
+ },
+ {
+ field: ["properties", "author"],
+ operator: "eq",
+ value: { name: "Ada" },
+ },
+ ],
+ },
+ }),
+ ]);
+ expect(plan).toBeDefined();
+ if (plan === undefined) {
+ return;
+ }
+ const referencedDocument = {
+ ...document,
+ properties: {
+ kind: "post",
+ author: { $ref: "../authors/ada.json" },
+ },
+ };
+
+ expect(
+ isContentDocumentCandidate({
+ document: referencedDocument,
+ plan,
+ available: "all",
+ })
+ ).toBe(true);
+ expect(
+ isContentDocumentCandidate({
+ document: {
+ ...referencedDocument,
+ properties: { ...referencedDocument.properties, kind: "page" },
+ },
+ plan,
+ available: "all",
+ })
+ ).toBe(false);
+ });
+
test("hydrates only the statically selected window and keeps dynamic windows conservative", () => {
const documents = ["alpha", "beta", "gamma"].map((id, index) => ({
...document,
diff --git a/packages/content-engine/src/compilation-plan.ts b/packages/content-engine/src/compilation-plan.ts
index a82ba9ebfb..9fdb2a22b3 100644
--- a/packages/content-engine/src/compilation-plan.ts
+++ b/packages/content-engine/src/compilation-plan.ts
@@ -23,7 +23,11 @@ import {
import { contentEngineLimits } from "./limits";
import { selectAssetDocumentFields, selectAssetProperties } from "./projection";
import type { CanonicalAssetFileEntry } from "./canonical";
-import { compareStrings } from "./canonical-json";
+import { compareStrings, type JsonValue } from "./canonical-json";
+import {
+ getJsonReferenceMarkerValue,
+ isJsonObject,
+} from "./document-graph/document-utils";
export const compareContentEntryPriority = (
left: CanonicalAssetFileEntry,
@@ -91,6 +95,51 @@ export const requiresStructuredProperties = (plan: ContentCompilationPlan) =>
export const requiresHydratedContent = (plan: ContentCompilationPlan) =>
plan.queries.some(({ content }) => content.mode !== "none");
+const containsDocumentReference = (value: JsonValue): boolean => {
+ if (typeof getJsonReferenceMarkerValue(value) === "string") {
+ return true;
+ }
+ if (Array.isArray(value)) {
+ return value.some(containsDocumentReference);
+ }
+ if (typeof value === "object" && value !== null) {
+ return Object.values(value).some(containsDocumentReference);
+ }
+ return false;
+};
+
+const isFieldAffectedByDocumentReference = (
+ document: AssetFileDocument,
+ field: AssetQueryFieldPath
+) => {
+ if (field[0] !== "properties") {
+ return false;
+ }
+ let value: JsonValue = document.properties;
+ for (const segment of field.slice(1)) {
+ if (typeof getJsonReferenceMarkerValue(value) === "string") {
+ return true;
+ }
+ if (
+ typeof value !== "object" ||
+ value === null ||
+ Object.hasOwn(value, segment) === false
+ ) {
+ return false;
+ }
+ if (isJsonObject(value)) {
+ value = value[segment];
+ } else {
+ const index = Number(segment);
+ if (Number.isSafeInteger(index) === false) {
+ return false;
+ }
+ value = value[index];
+ }
+ }
+ return containsDocumentReference(value);
+};
+
const evaluateWhere = ({
document,
where,
@@ -110,6 +159,9 @@ const evaluateWhere = ({
) {
return;
}
+ if (isFieldAffectedByDocumentReference(document, condition.field)) {
+ return;
+ }
const filter = assetQueryFilter.safeParse({
field: condition.field,
operator: condition.operator,
diff --git a/packages/content-engine/src/compiler.ts b/packages/content-engine/src/compiler.ts
index 040b4b5329..08a17457ed 100644
--- a/packages/content-engine/src/compiler.ts
+++ b/packages/content-engine/src/compiler.ts
@@ -3,6 +3,7 @@ export * from "./json";
export * from "./canonical";
export * from "./field-catalog";
export * from "./asset-index";
+export * from "./content-runtime-artifact";
export * from "./content-source";
export * from "./document-metadata";
export { serializeJsonDeterministically } from "./canonical-json";
diff --git a/packages/content-engine/src/content-artifact.test.ts b/packages/content-engine/src/content-artifact.test.ts
new file mode 100644
index 0000000000..ab6b0f0da8
--- /dev/null
+++ b/packages/content-engine/src/content-artifact.test.ts
@@ -0,0 +1,168 @@
+import { describe, expect, test } from "vitest";
+import { compileContentArtifact } from "./asset-index";
+import { createCanonicalAssetFileEntry } from "./canonical";
+import { contentArtifactV1 } from "./schema";
+import {
+ checksumContentArtifact,
+ getContentArtifactRuntimeAssetIds,
+ verifyContentArtifact,
+} from "./content-artifact";
+import {
+ createDocumentGraph,
+ createDocumentGraphArtifact,
+} from "./document-graph";
+
+const entry = createCanonicalAssetFileEntry({
+ projectId: "project",
+ document: {
+ _id: "post",
+ _type: "asset.file",
+ name: "post.json",
+ path: "posts/post.json",
+ key: "post",
+ extension: "json",
+ mimeType: "application/json",
+ size: 2,
+ revision: "post-r1",
+ contentRef: "content:post",
+ properties: {},
+ },
+});
+
+const graph = createDocumentGraph({
+ nodes: [{ id: "post", revision: "post-r1", contentRef: "content:post" }],
+ edges: [],
+});
+
+describe("content artifact document graph", () => {
+ test("retains runtime URLs for graph documents even when query documents are materialized", () => {
+ expect(
+ getContentArtifactRuntimeAssetIds({
+ artifact: {
+ documents: [],
+ documentGraph: {
+ nodes: graph.nodes,
+ },
+ },
+ includeDocuments: false,
+ })
+ ).toEqual(["post"]);
+ });
+
+ test("verifies nested graph integrity independently of the outer checksum", async () => {
+ const { artifact } = await compileContentArtifact({
+ projectId: "project",
+ entries: [entry],
+ documentGraph: graph,
+ });
+ const tampered = {
+ ...artifact,
+ documentGraph: {
+ ...artifact.documentGraph!,
+ nodes: artifact.documentGraph!.nodes.map((node) => ({
+ ...node,
+ contentRef: "content:tampered",
+ })),
+ },
+ };
+ const outerChecksum = await checksumContentArtifact(tampered);
+
+ await expect(
+ verifyContentArtifact({
+ ...tampered,
+ integrity: { algorithm: "sha256", checksum: outerChecksum },
+ })
+ ).rejects.toMatchObject({ code: "CHECKSUM_MISMATCH" });
+ });
+
+ test("rejects a graph identity that differs from its query document", async () => {
+ const { artifact } = await compileContentArtifact({
+ projectId: "project",
+ entries: [entry],
+ documentGraph: graph,
+ });
+ const documentGraph = await createDocumentGraphArtifact(
+ createDocumentGraph({
+ nodes: [
+ {
+ id: "post",
+ revision: "post-r2",
+ contentRef: "content:post-r2",
+ },
+ ],
+ edges: [],
+ })
+ );
+ const tampered = contentArtifactV1.parse({ ...artifact, documentGraph });
+
+ await expect(
+ verifyContentArtifact({
+ ...tampered,
+ integrity: {
+ algorithm: "sha256",
+ checksum: await checksumContentArtifact(tampered),
+ },
+ })
+ ).rejects.toThrow("document identity");
+ });
+
+ test("accepts graph identity fields omitted by query projection", async () => {
+ const { artifact } = await compileContentArtifact({
+ projectId: "project",
+ entries: [entry],
+ documentGraph: graph,
+ });
+ const projected = contentArtifactV1.parse({
+ ...artifact,
+ documents: artifact.documents.map(
+ ({ revision: _revision, contentRef: _contentRef, ...document }) =>
+ document
+ ),
+ });
+ const projectedWithChecksum = {
+ ...projected,
+ integrity: {
+ algorithm: "sha256" as const,
+ checksum: await checksumContentArtifact(projected),
+ },
+ };
+
+ await expect(verifyContentArtifact(projectedWithChecksum)).resolves.toEqual(
+ projectedWithChecksum
+ );
+ });
+
+ test("counts persisted graph bytes against the artifact limit", async () => {
+ const withoutGraph = await compileContentArtifact({
+ projectId: "project",
+ entries: [entry],
+ });
+ const withGraph = await compileContentArtifact({
+ projectId: "project",
+ entries: [entry],
+ documentGraph: graph,
+ });
+
+ expect(withGraph.diagnostics.boundedBytes).toBeGreaterThan(
+ withoutGraph.diagnostics.boundedBytes
+ );
+ const constrained = await compileContentArtifact({
+ projectId: "project",
+ entries: [entry],
+ documentGraph: graph,
+ maxBytes: withoutGraph.diagnostics.boundedBytes,
+ });
+ expect(constrained.artifact.documents).toEqual([]);
+ expect(constrained.diagnostics.boundedBytes).toBeLessThanOrEqual(
+ withoutGraph.diagnostics.boundedBytes
+ );
+ await expect(
+ compileContentArtifact({
+ projectId: "project",
+ entries: [entry],
+ documentGraph: graph,
+ maxBytes: Math.floor(constrained.diagnostics.boundedBytes / 2),
+ })
+ ).rejects.toThrow("Content database byte limit is too small");
+ });
+});
diff --git a/packages/content-engine/src/content-artifact.ts b/packages/content-engine/src/content-artifact.ts
index ab8b543a09..4656dc40d7 100644
--- a/packages/content-engine/src/content-artifact.ts
+++ b/packages/content-engine/src/content-artifact.ts
@@ -2,6 +2,7 @@ import { contentArtifactV1, type ContentArtifactV1 } from "./schema";
import { contentEngineLimits } from "./limits";
import { serializeJsonDeterministically, sha256 } from "./canonical-json";
import { getUtf8ByteLength } from "./byte-stream";
+import { verifyDocumentGraphArtifact } from "./document-graph";
export const checksumContentArtifact = async (index: ContentArtifactV1) => {
const { integrity: _integrity, ...payload } = index;
@@ -25,11 +26,14 @@ export const getContentArtifactReferencedAssetIds = (
export const getContentArtifactRuntimeAssetIds = ({
artifact,
includeDocuments,
+ includeDocumentGraph = true,
}: {
artifact: Pick<ContentArtifactV1, "assetReferences"> & {
documents: readonly { _id: string }[];
+ documentGraph?: { readonly nodes: readonly { id: string }[] };
};
includeDocuments: boolean;
+ includeDocumentGraph?: boolean;
}) => {
const ids = new Set(getContentArtifactReferencedAssetIds(artifact));
if (includeDocuments) {
@@ -37,6 +41,11 @@ export const getContentArtifactRuntimeAssetIds = ({
ids.add(_id);
}
}
+ if (includeDocumentGraph) {
+ for (const { id } of artifact.documentGraph?.nodes ?? []) {
+ ids.add(id);
+ }
+ }
return [...ids].sort();
};
@@ -54,5 +63,23 @@ export const verifyContentArtifact = async (value: unknown) => {
if (index.integrity.checksum !== (await checksumContentArtifact(index))) {
throw new Error("Content artifact checksum is invalid");
}
+ if (index.documentGraph !== undefined) {
+ const { graph } = await verifyDocumentGraphArtifact(index.documentGraph);
+ const nodesById = new Map(graph.nodes.map((node) => [node.id, node]));
+ for (const document of index.documents) {
+ const node = nodesById.get(document._id);
+ if (
+ node !== undefined &&
+ ((document.revision !== undefined &&
+ node.revision !== document.revision) ||
+ (document.contentRef !== undefined &&
+ node.contentRef !== document.contentRef))
+ ) {
+ throw new Error(
+ `Content artifact document identity does not match graph node ${document._id}`
+ );
+ }
+ }
+ }
return index;
};
diff --git a/packages/content-engine/src/content-database.ts b/packages/content-engine/src/content-database.ts
index 870effd3ec..a90643c2bb 100644
--- a/packages/content-engine/src/content-database.ts
+++ b/packages/content-engine/src/content-database.ts
@@ -1,30 +1,311 @@
+import { evaluateQueryWhere } from "@webstudio-is/query-builder/runtime";
import type {
ContentArtifactV1,
AssetQueryRequestInput,
AssetQueryResult,
BuilderAssetFieldCatalog,
ContentDatabaseStats,
+ ContentDatabaseDocument,
} from "./schema";
+import { assetQuery, contentDatabaseDocument } from "./schema";
import { serializeContentArtifact } from "./content-artifact";
+import {
+ restoreContentRuntimeDocumentGraph,
+ type ContentRuntimeArtifact,
+} from "./content-runtime-artifact";
import {
AssetIndexRevisionError,
executeAssetQuery,
+ matchesAssetQueryFilter,
type AssetRuntimeData,
} from "./structured-query";
-import { encodeUtf8, getUtf8ByteLength } from "./byte-stream";
+import { encodeUtf8, getUtf8ByteLength, toByteChunks } from "./byte-stream";
import type { AssetResourceContentReader } from "./hydration";
import { getMaterializedAssetQueryResult } from "./materialized-query";
+import {
+ createDocumentGraph,
+ getAdaptedDocumentProperties,
+ isDocumentGraphFieldAffected,
+ getDocumentGraphQueryRootIds,
+ resolveAdaptedDocumentGraph,
+ selectDocumentGraphForQuery,
+ type DocumentSourceLoader,
+ emitDocumentGraphRuntimeEvent,
+ type DocumentGraphRuntimeObserver,
+ assertDocumentSourceIdentity,
+} from "./document-graph";
+import { contentEngineLimits } from "./limits";
+
+type ContentDatabaseQueryArguments = [
+ request: AssetQueryRequestInput,
+ readContent?: AssetResourceContentReader,
+ runtimeAssets?: Readonly<Record<string, AssetRuntimeData>>,
+];
export type ContentDatabase = {
- query(
- request: AssetQueryRequestInput,
- readContent?: AssetResourceContentReader,
- runtimeAssets?: Readonly<Record<string, AssetRuntimeData>>
- ): Promise<AssetQueryResult>;
+ query(...args: ContentDatabaseQueryArguments): Promise<AssetQueryResult>;
+ queryWithDocumentGraph(input: {
+ request: AssetQueryRequestInput;
+ load: DocumentSourceLoader;
+ readContent?: AssetResourceContentReader;
+ runtimeAssets?: Readonly<Record<string, AssetRuntimeData>>;
+ signal?: AbortSignal;
+ onEvent?: DocumentGraphRuntimeObserver;
+ }): Promise<AssetQueryResult>;
getFieldCatalog(): BuilderAssetFieldCatalog;
getStats(): ContentDatabaseStats;
};
+export type RuntimeContentDatabase = Pick<
+ ContentDatabase,
+ "query" | "queryWithDocumentGraph"
+>;
+
+const selectByteRange = (
+ source: Parameters<typeof toByteChunks>[0],
+ range?: { offset: number; length: number }
+): AsyncIterable<Uint8Array> => {
+ if (range === undefined) {
+ return toByteChunks(source);
+ }
+ return {
+ async *[Symbol.asyncIterator]() {
+ let skipped = 0;
+ let emitted = 0;
+ for await (const chunk of toByteChunks(source)) {
+ if (emitted === range.length) {
+ return;
+ }
+ if (skipped + chunk.byteLength <= range.offset) {
+ skipped += chunk.byteLength;
+ continue;
+ }
+ const start = Math.max(0, range.offset - skipped);
+ const length = Math.min(
+ chunk.byteLength - start,
+ range.length - emitted
+ );
+ if (length > 0) {
+ yield chunk.subarray(start, start + length);
+ emitted += length;
+ }
+ skipped += chunk.byteLength;
+ }
+ },
+ };
+};
+
+const createDocumentContentReader = ({
+ graph,
+ load,
+ signal,
+}: {
+ graph: ReturnType<typeof createDocumentGraph>;
+ load: DocumentSourceLoader;
+ signal?: AbortSignal;
+}): AssetResourceContentReader => {
+ const nodesByContentRef = new Map(
+ graph.nodes.map((node) => [node.contentRef, node])
+ );
+ return async (contentRef, range) => {
+ const node = nodesByContentRef.get(contentRef);
+ if (node === undefined) {
+ throw new Error(
+ `Document content reference ${contentRef} is unavailable`
+ );
+ }
+ const loaded = assertDocumentSourceIdentity({
+ node,
+ source: await load(node, { signal }),
+ });
+ return {
+ data: selectByteRange(loaded.source, range),
+ ...(range === undefined ? {} : { contentLength: range.length }),
+ };
+ };
+};
+
+const createQueryableContentDatabase = ({
+ artifact,
+ revision,
+ catalog,
+ documentGraph,
+ inlineDocuments,
+ readContent,
+}: {
+ artifact: Pick<
+ ContentRuntimeArtifact,
+ "documents" | "contents" | "assetReferences" | "queries"
+ >;
+ revision: string;
+ catalog?: BuilderAssetFieldCatalog;
+ documentGraph?: ReturnType<typeof createDocumentGraph>;
+ inlineDocuments?: ReadonlyMap<string, ContentDatabaseDocument>;
+ readContent?: AssetResourceContentReader;
+}): RuntimeContentDatabase => {
+ const executeQuery = async (
+ request: AssetQueryRequestInput,
+ queryContentReader?: AssetResourceContentReader,
+ runtimeAssets?: Readonly<Record<string, AssetRuntimeData>>,
+ options?: {
+ documents?: readonly ContentDatabaseDocument[];
+ skipMaterialized?: boolean;
+ }
+ ) => {
+ if (
+ request.indexRevision !== undefined &&
+ request.indexRevision !== revision
+ ) {
+ throw new AssetIndexRevisionError();
+ }
+ const materialized =
+ options?.skipMaterialized === true
+ ? undefined
+ : await getMaterializedAssetQueryResult({
+ queries: artifact.queries,
+ query: request.query,
+ });
+ if (materialized !== undefined) {
+ return materialized;
+ }
+ const readEmbeddedContent: AssetResourceContentReader = async (
+ contentRef,
+ range
+ ) => {
+ const content = artifact.contents?.[contentRef];
+ if (content === undefined) {
+ const externalReader = queryContentReader ?? readContent;
+ if (externalReader === undefined) {
+ throw new Error("Content is not embedded in this database");
+ }
+ return await externalReader(contentRef, range);
+ }
+ const bytes = encodeUtf8(content);
+ const selected =
+ range === undefined
+ ? bytes
+ : bytes.slice(range.offset, range.offset + range.length);
+ return {
+ data: (async function* () {
+ yield selected;
+ })(),
+ contentLength: selected.byteLength,
+ };
+ };
+ const result = await executeAssetQuery({
+ query: request.query,
+ catalog,
+ documents: options?.documents ?? artifact.documents,
+ read: readEmbeddedContent,
+ runtimeAssets,
+ assetReferences: artifact.assetReferences,
+ });
+ return result;
+ };
+ const query = async (...args: ContentDatabaseQueryArguments) =>
+ await executeQuery(...args);
+ return {
+ query,
+ queryWithDocumentGraph: async ({
+ request,
+ load,
+ readContent: queryContentReader,
+ runtimeAssets,
+ signal,
+ onEvent,
+ }) => {
+ if (documentGraph === undefined) {
+ return await executeQuery(request, queryContentReader, runtimeAssets);
+ }
+ const contentReader =
+ queryContentReader ??
+ createDocumentContentReader({ graph: documentGraph, load, signal });
+ const query = assetQuery.parse(request.query);
+ const documentsById = new Map(
+ artifact.documents.map((document) => [document._id, document])
+ );
+ const rootIds = getDocumentGraphQueryRootIds({
+ graph: documentGraph,
+ query,
+ }).filter((rootId) => {
+ const document = documentsById.get(rootId);
+ if (document === undefined) {
+ return false;
+ }
+ return (
+ evaluateQueryWhere(query.where, (filter) => {
+ if (
+ isDocumentGraphFieldAffected({
+ graph: documentGraph,
+ sourceId: rootId,
+ field: filter.field,
+ })
+ ) {
+ return;
+ }
+ return matchesAssetQueryFilter(
+ document,
+ filter,
+ runtimeAssets?.[rootId]
+ );
+ }) !== false
+ );
+ });
+ if (rootIds.length === 0) {
+ return await executeQuery(request, contentReader, runtimeAssets);
+ }
+ const queryGraph = selectDocumentGraphForQuery({
+ graph: documentGraph,
+ query,
+ rootIds,
+ });
+ emitDocumentGraphRuntimeEvent(onEvent, {
+ type: "roots-selected",
+ rootCount: rootIds.length,
+ });
+ const resolved = await resolveAdaptedDocumentGraph({
+ graph: queryGraph,
+ rootIds,
+ load: async (node, options) => {
+ const inlineDocument = inlineDocuments?.get(node.id);
+ if (inlineDocument !== undefined) {
+ return {
+ format: "json",
+ revision: node.revision,
+ source: JSON.stringify(inlineDocument.properties),
+ };
+ }
+ return await load(node, options);
+ },
+ concurrency: contentEngineLimits.concurrentContentReads,
+ signal,
+ onEvent,
+ allowUnresolvedReferences: true,
+ });
+ const propertiesById = new Map(
+ rootIds.flatMap((rootId, index) => {
+ const properties = getAdaptedDocumentProperties(
+ resolved.roots[index]
+ );
+ return properties === undefined
+ ? []
+ : [[rootId, properties] as const];
+ })
+ );
+ const documents = artifact.documents.map((document) => {
+ const properties = propertiesById.get(document._id);
+ return properties === undefined
+ ? document
+ : contentDatabaseDocument.parse({ ...document, properties });
+ });
+ return await executeQuery(request, contentReader, runtimeAssets, {
+ documents,
+ skipMaterialized: true,
+ });
+ },
+ };
+};
+
export const createContentDatabase = ({
artifact,
readContent,
@@ -40,73 +321,56 @@ export const createContentDatabase = ({
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,
+ const documentGraph =
+ artifact.documentGraph === undefined
+ ? undefined
+ : createDocumentGraph({
+ nodes: artifact.documentGraph.nodes,
+ edges: artifact.documentGraph.edges,
+ });
+ const database = createQueryableContentDatabase({
+ artifact,
revision: artifact.integrity.checksum,
- usedBytes,
- maxBytes,
- unboundedBytes,
- includedDocumentCount,
- omittedDocumentCount,
- omissionReason:
- omittedDocumentCount === 0
- ? undefined
- : unboundedBytes > maxBytes
- ? "size"
- : "unavailable",
- truncated: omittedDocumentCount > 0,
- };
+ catalog: artifact.fieldCatalog,
+ documentGraph,
+ readContent,
+ });
return {
- query: async (request, queryContentReader, runtimeAssets) => {
- if (
- request.indexRevision !== undefined &&
- request.indexRevision !== artifact.integrity.checksum
- ) {
- throw new AssetIndexRevisionError();
- }
- const materialized = await getMaterializedAssetQueryResult({
- queries: artifact.queries,
- query: request.query,
- });
- if (materialized !== undefined) {
- return materialized;
- }
- const readEmbeddedContent: AssetResourceContentReader = async (
- contentRef,
- range
- ) => {
- const content = artifact.contents?.[contentRef];
- if (content === undefined) {
- const externalReader = queryContentReader ?? readContent;
- if (externalReader === undefined) {
- throw new Error("Content is not embedded in this database");
- }
- return await externalReader(contentRef, range);
- }
- const bytes = encodeUtf8(content);
- const selected =
- range === undefined
- ? bytes
- : bytes.slice(range.offset, range.offset + range.length);
- return {
- data: (async function* () {
- yield selected;
- })(),
- contentLength: selected.byteLength,
- };
- };
- const result = await executeAssetQuery({
- query: request.query,
- catalog: artifact.fieldCatalog,
- documents: artifact.documents,
- read: readEmbeddedContent,
- runtimeAssets,
- assetReferences: artifact.assetReferences,
- });
- return result;
- },
+ ...database,
getFieldCatalog: () => artifact.fieldCatalog,
- getStats: () => stats,
+ getStats: () => ({
+ format: artifact.format,
+ version: artifact.version,
+ revision: artifact.integrity.checksum,
+ usedBytes,
+ maxBytes,
+ unboundedBytes,
+ includedDocumentCount,
+ omittedDocumentCount,
+ omissionReason:
+ omittedDocumentCount === 0
+ ? undefined
+ : unboundedBytes > maxBytes
+ ? "size"
+ : "unavailable",
+ truncated: omittedDocumentCount > 0,
+ }),
};
};
+
+export const createRuntimeContentDatabase = ({
+ artifact,
+ readContent,
+}: {
+ artifact: ContentRuntimeArtifact;
+ readContent?: AssetResourceContentReader;
+}): RuntimeContentDatabase => {
+ const restored = restoreContentRuntimeDocumentGraph({ artifact });
+ return createQueryableContentDatabase({
+ artifact,
+ revision: artifact.revision,
+ documentGraph: restored?.graph,
+ inlineDocuments: restored?.inlineDocuments,
+ readContent,
+ });
+};
diff --git a/packages/content-engine/src/content-runtime-artifact.test.ts b/packages/content-engine/src/content-runtime-artifact.test.ts
new file mode 100644
index 0000000000..85744bd8e4
--- /dev/null
+++ b/packages/content-engine/src/content-runtime-artifact.test.ts
@@ -0,0 +1,114 @@
+import { expect, test } from "vitest";
+import { compileContentArtifact } from "./asset-index";
+import { createCanonicalAssetFileEntry } from "./canonical";
+import { serializeContentArtifact } from "./content-artifact";
+import {
+ createContentRuntimeArtifact,
+ getContentRuntimeArtifactRuntimeAssetIds,
+ restoreContentRuntimeDocumentGraph,
+ serializeContentRuntimeArtifact,
+} from "./content-runtime-artifact";
+import { createDocumentGraph } from "./document-graph";
+import type { AssetFileDocument } from "./schema";
+
+test("projects build metadata and inline JSON graph sources out of the runtime artifact", async () => {
+ const post: AssetFileDocument = {
+ _id: "post",
+ _type: "asset.file",
+ name: "post.json",
+ path: "posts/post.json",
+ key: "post",
+ extension: "json",
+ mimeType: "application/json",
+ size: 80,
+ revision: "post-r1",
+ contentRef: "post.json",
+ properties: {
+ kind: "post",
+ slug: "post",
+ title: "Post",
+ body: { $ref: "./post.md#body" },
+ },
+ };
+ const markdown: AssetFileDocument = {
+ ...post,
+ _id: "markdown",
+ name: "post.md",
+ path: "posts/post.md",
+ extension: "md",
+ mimeType: "text/markdown",
+ size: 2_000,
+ revision: "markdown-r1",
+ contentRef: "post.md",
+ properties: { title: "Post" },
+ };
+ const { artifact } = await compileContentArtifact({
+ projectId: "project",
+ entries: [post, markdown].map((document) =>
+ createCanonicalAssetFileEntry({ projectId: "project", document })
+ ),
+ documentGraph: createDocumentGraph({
+ nodes: [
+ {
+ id: post._id,
+ revision: post.revision,
+ contentRef: post.contentRef,
+ format: "json",
+ },
+ {
+ id: markdown._id,
+ revision: markdown.revision,
+ contentRef: markdown.contentRef,
+ format: "markdown",
+ },
+ ],
+ edges: [
+ {
+ sourceId: post._id,
+ referenceId: "#/body",
+ reference: {
+ documentId: markdown._id,
+ revision: markdown.revision,
+ representation: { type: "markdown-body" },
+ },
+ },
+ ],
+ }),
+ });
+
+ const runtime = createContentRuntimeArtifact(artifact);
+ const serialized = serializeContentRuntimeArtifact(runtime);
+ const parsed = JSON.parse(serialized);
+
+ expect(serialized.length).toBeLessThan(
+ serializeContentArtifact(artifact).length / 3
+ );
+ expect(parsed).not.toHaveProperty("fieldCatalog");
+ expect(parsed).not.toHaveProperty("database");
+ expect(parsed).not.toHaveProperty("integrity");
+ expect(runtime.documentGraph?.nodes.map(({ id }) => id)).toEqual([
+ "markdown",
+ ]);
+ expect(runtime.documentGraph?.edges).toEqual([
+ {
+ sourceId: "post",
+ referenceId: "#/body",
+ documentId: "markdown",
+ representation: { type: "markdown-body" },
+ },
+ ]);
+ expect(
+ getContentRuntimeArtifactRuntimeAssetIds({
+ artifact: runtime,
+ includeDocuments: false,
+ })
+ ).toEqual(["markdown"]);
+
+ const restored = restoreContentRuntimeDocumentGraph({ artifact: runtime });
+ expect(restored?.inlineDocuments.has("post")).toBe(true);
+ expect(restored?.graph.nodes.map(({ id }) => id)).toEqual([
+ "markdown",
+ "post",
+ ]);
+ expect(restored?.graph.edges[0].reference.revision).toBe("markdown-r1");
+});
diff --git a/packages/content-engine/src/content-runtime-artifact.ts b/packages/content-engine/src/content-runtime-artifact.ts
new file mode 100644
index 0000000000..4a014c53d2
--- /dev/null
+++ b/packages/content-engine/src/content-runtime-artifact.ts
@@ -0,0 +1,175 @@
+import { serializeJsonDeterministically } from "./canonical-json";
+import type {
+ ContentArtifactV1,
+ ContentDatabaseDocument,
+ MaterializedAssetQuery,
+} from "./schema";
+import {
+ createDocumentGraph,
+ type DocumentGraph,
+ type DocumentGraphNode,
+ type DocumentRepresentation,
+} from "./document-graph";
+import type { MarkdownAssetReferences } from "./markdown-references";
+
+type RuntimeDocumentGraphEdge = Readonly<{
+ sourceId: string;
+ referenceId: string;
+ documentId: string;
+ representation: DocumentRepresentation;
+}>;
+
+export type ContentRuntimeArtifact = Readonly<{
+ revision: string;
+ documents: readonly ContentDatabaseDocument[];
+ documentGraph?: Readonly<{
+ nodes: readonly DocumentGraphNode[];
+ edges: readonly RuntimeDocumentGraphEdge[];
+ }>;
+ contents?: Readonly<Record<string, string>>;
+ assetReferences?: MarkdownAssetReferences;
+ queries?: Readonly<Record<string, MaterializedAssetQuery>>;
+}>;
+
+const getInlineDocumentIds = (artifact: ContentArtifactV1) => {
+ const documentIds = new Set(
+ artifact.documents
+ .filter(({ properties }) => properties !== undefined)
+ .map(({ _id }) => _id)
+ );
+ const targetIds = new Set(
+ artifact.documentGraph?.edges.map(({ reference }) => reference.documentId)
+ );
+ return new Set(
+ artifact.documentGraph?.nodes.flatMap((node) =>
+ node.format === "json" &&
+ documentIds.has(node.id) &&
+ targetIds.has(node.id) === false
+ ? [node.id]
+ : []
+ )
+ );
+};
+
+/** Projects the verified build artifact to the data executed in a Worker. */
+export const createContentRuntimeArtifact = (
+ artifact: ContentArtifactV1
+): ContentRuntimeArtifact => {
+ const inlineDocumentIds = getInlineDocumentIds(artifact);
+ const documentGraph =
+ artifact.documentGraph === undefined
+ ? undefined
+ : {
+ nodes: artifact.documentGraph.nodes.filter(
+ ({ id }) => inlineDocumentIds.has(id) === false
+ ),
+ edges: artifact.documentGraph.edges.map(
+ ({ sourceId, referenceId, reference }) => ({
+ sourceId,
+ referenceId,
+ documentId: reference.documentId,
+ representation: reference.representation,
+ })
+ ),
+ };
+ return {
+ revision: artifact.integrity.checksum,
+ documents: artifact.documents,
+ ...(documentGraph === undefined ? {} : { documentGraph }),
+ ...(artifact.contents === undefined ? {} : { contents: artifact.contents }),
+ ...(artifact.assetReferences === undefined
+ ? {}
+ : { assetReferences: artifact.assetReferences }),
+ ...(artifact.queries === undefined ? {} : { queries: artifact.queries }),
+ };
+};
+
+export const serializeContentRuntimeArtifact = (
+ artifact: ContentRuntimeArtifact
+) => serializeJsonDeterministically(artifact);
+
+export const getContentRuntimeArtifactRuntimeAssetIds = ({
+ artifact,
+ includeDocuments,
+}: {
+ artifact: ContentRuntimeArtifact;
+ includeDocuments: boolean;
+}) => {
+ const ids = new Set(
+ Object.values(artifact.assetReferences ?? {})
+ .flat()
+ .map(({ assetId }) => assetId)
+ );
+ if (includeDocuments) {
+ for (const { _id } of artifact.documents) {
+ ids.add(_id);
+ }
+ }
+ for (const { id } of artifact.documentGraph?.nodes ?? []) {
+ ids.add(id);
+ }
+ return [...ids].sort();
+};
+
+export const restoreContentRuntimeDocumentGraph = ({
+ artifact,
+}: {
+ artifact: ContentRuntimeArtifact;
+}):
+ | Readonly<{
+ graph: DocumentGraph;
+ inlineDocuments: ReadonlyMap<string, ContentDatabaseDocument>;
+ }>
+ | undefined => {
+ if (artifact.documentGraph === undefined) {
+ return;
+ }
+ const documentsById = new Map(
+ artifact.documents.map((document) => [document._id, document])
+ );
+ const nodesById = new Map(
+ artifact.documentGraph.nodes.map((node) => [node.id, node])
+ );
+ const inlineDocuments = new Map<string, ContentDatabaseDocument>();
+ for (const { sourceId } of artifact.documentGraph.edges) {
+ if (nodesById.has(sourceId)) {
+ continue;
+ }
+ const document = documentsById.get(sourceId);
+ if (document?.properties === undefined) {
+ throw new Error(
+ `Runtime document graph source ${sourceId} is unavailable`
+ );
+ }
+ inlineDocuments.set(sourceId, document);
+ nodesById.set(sourceId, {
+ id: sourceId,
+ revision: sourceId,
+ contentRef: sourceId,
+ format: "json",
+ });
+ }
+ const graph = createDocumentGraph({
+ nodes: [...nodesById.values()],
+ edges: artifact.documentGraph.edges.map(
+ ({ sourceId, referenceId, documentId, representation }) => {
+ const target = nodesById.get(documentId);
+ if (target === undefined) {
+ throw new Error(
+ `Runtime document graph target ${documentId} is unavailable`
+ );
+ }
+ return {
+ sourceId,
+ referenceId,
+ reference: {
+ documentId,
+ revision: target.revision,
+ representation,
+ },
+ };
+ }
+ ),
+ });
+ return { graph, inlineDocuments };
+};
diff --git a/packages/content-engine/src/content-source.test.ts b/packages/content-engine/src/content-source.test.ts
index f0c19c9113..0840e6d57f 100644
--- a/packages/content-engine/src/content-source.test.ts
+++ b/packages/content-engine/src/content-source.test.ts
@@ -94,7 +94,349 @@ const createMutableSource = ({
};
};
+const createDocumentSource = ({
+ files,
+ sources,
+}: {
+ files: readonly ContentSourceFile[];
+ sources: Readonly<Partial<Record<string, string>>>;
+}): ContentSource => ({
+ async openSnapshot() {
+ return {
+ revision: getRevision(files),
+ files,
+ async loadEntries() {
+ return files.map(createEntry);
+ },
+ async loadDocumentSources() {
+ return files.map(({ id }) => ({ id, source: sources[id] ?? "" }));
+ },
+ async isCurrent() {
+ return true;
+ },
+ };
+ },
+});
+
describe("content source snapshots", () => {
+ test("analyzes only query roots and their reachable document targets", async () => {
+ const post = createFile({ id: "post", path: "blog/post.md" });
+ const author = createFile({
+ id: "author",
+ path: "blog/author.json",
+ contentType: "application/json",
+ });
+ const unrelated = createFile({
+ id: "unrelated",
+ path: "other/broken.json",
+ contentType: "application/json",
+ });
+ const source: ContentSource = {
+ async openSnapshot() {
+ return {
+ revision: "snapshot",
+ files: [post, author, unrelated],
+ async loadEntries() {
+ return [post].map(createEntry);
+ },
+ async loadDocumentSources() {
+ return [
+ {
+ id: "post",
+ source:
+ "---\nauthor:\n $ref: ./author.json#/profile\n---\nPost\n",
+ },
+ { id: "author", source: '{"profile":{"name":"Ada"}}' },
+ { id: "unrelated", source: "{invalid" },
+ ];
+ },
+ async isCurrent() {
+ return true;
+ },
+ };
+ },
+ };
+
+ const result = await compileContentSource({
+ source,
+ projectId,
+ plan: {
+ standardFields: [],
+ structuredPropertyPaths: [["properties", "author"]],
+ excerpt: false,
+ metadataError: false,
+ queries: [
+ {
+ id: "posts",
+ where: { all: [] },
+ sort: [],
+ limit: { type: "literal", value: 1 },
+ offset: { type: "literal", value: 0 },
+ output: {
+ mode: "fields",
+ includeMetadata: false,
+ fields: [["properties", "author"]],
+ },
+ content: { mode: "none" },
+ },
+ ],
+ },
+ });
+
+ expect(result.documentGraph?.nodes.map(({ id }) => id)).toEqual([
+ "author",
+ "post",
+ ]);
+ expect(result.documentGraph?.edges).toHaveLength(1);
+ });
+
+ test.each(["filter", "sort"] as const)(
+ "discovers references used only by a query %s",
+ async (usage) => {
+ const post = createFile({
+ id: "post",
+ path: "posts/post.json",
+ contentType: "application/json",
+ });
+ const author = createFile({
+ id: "author",
+ path: "authors/author.json",
+ contentType: "application/json",
+ });
+ const source = createDocumentSource({
+ files: [post, author],
+ sources: {
+ post: '{"author":{"$ref":"../authors/author.json"}}',
+ author: '{"name":"Ada"}',
+ },
+ });
+ const authorField: ["properties", "author", "name"] = [
+ "properties",
+ "author",
+ "name",
+ ];
+
+ const result = await compileContentSource({
+ source,
+ projectId,
+ plan: {
+ standardFields: [["id"]],
+ structuredPropertyPaths: [authorField],
+ excerpt: false,
+ metadataError: false,
+ queries: [
+ {
+ id: usage,
+ where:
+ usage === "filter"
+ ? {
+ all: [
+ {
+ field: authorField,
+ operator: "eq",
+ value: { type: "literal", value: "Ada" },
+ },
+ ],
+ }
+ : { all: [] },
+ sort:
+ usage === "sort"
+ ? [{ field: authorField, direction: "asc" }]
+ : [],
+ limit: { type: "literal", value: 1 },
+ offset: { type: "literal", value: 0 },
+ output: {
+ mode: "fields",
+ includeMetadata: false,
+ fields: [["id"]],
+ },
+ content: { mode: "none" },
+ },
+ ],
+ },
+ });
+
+ expect(result.documentGraph?.edges).toHaveLength(1);
+ expect(result.documentGraph?.edges[0]).toMatchObject({
+ sourceId: "post",
+ referenceId: "#/author",
+ });
+ }
+ );
+
+ test("discovers document references without embedding source payloads", async () => {
+ const post = createFile({
+ id: "post",
+ path: "posts/hello.json",
+ contentType: "application/json",
+ contentRef: "revisions/post.json",
+ });
+ const author = createFile({
+ id: "author",
+ path: "authors/ada.md",
+ contentRef: "revisions/author.md",
+ });
+ const source: ContentSource = {
+ async openSnapshot() {
+ return {
+ revision: "snapshot",
+ files: [post, author],
+ async loadEntries() {
+ return [post, author].map(createEntry);
+ },
+ async loadDocumentSources() {
+ return [
+ {
+ id: "post",
+ source: '{"author":{"$ref":"../authors/ada.md#frontmatter"}}',
+ },
+ {
+ id: "author",
+ source: "---\nname: Ada\n---\nWriter.\n",
+ },
+ ];
+ },
+ async isCurrent() {
+ return true;
+ },
+ };
+ },
+ };
+
+ const result = await compileContentSource({ source, projectId });
+
+ expect(result.artifact.contents).toBeUndefined();
+ expect(result.documentGraph?.edges).toEqual([
+ {
+ sourceId: "post",
+ referenceId: "#/author",
+ reference: {
+ documentId: "author",
+ revision: "revision-author",
+ representation: { type: "markdown-frontmatter" },
+ },
+ },
+ ]);
+ expect(result.artifact.documentGraph).toMatchObject({
+ format: "webstudio-document-graph",
+ version: 1,
+ nodes: result.documentGraph?.nodes,
+ edges: result.documentGraph?.edges,
+ integrity: {
+ algorithm: "sha256",
+ checksum: expect.stringMatching(/^sha256:[a-f0-9]{64}$/),
+ },
+ });
+ });
+
+ test("resolves encoded references to asset paths containing URL delimiters", async () => {
+ const post = createFile({
+ id: "post",
+ path: "content/post.json",
+ contentType: "application/json",
+ });
+ const author = createFile({
+ id: "author",
+ path: "content/author#draft?50%.json",
+ contentType: "application/json",
+ });
+
+ const result = await compileContentSource({
+ projectId,
+ source: createDocumentSource({
+ files: [post, author],
+ sources: {
+ post: '{"author":{"$ref":"./author%23draft%3F50%25.json"}}',
+ author: '{"name":"Ada"}',
+ },
+ }),
+ });
+
+ expect(result.documentGraph?.edges).toMatchObject([
+ {
+ sourceId: "post",
+ reference: { documentId: "author" },
+ },
+ ]);
+ });
+
+ test.each([
+ {
+ name: "a missing target",
+ files: [
+ createFile({
+ id: "post",
+ path: "content/post.json",
+ contentType: "application/json",
+ }),
+ ],
+ sources: { post: '{"author":{"$ref":"./missing.json"}}' },
+ code: "TARGET_NOT_FOUND",
+ },
+ {
+ name: "a dependency cycle",
+ files: [
+ createFile({
+ id: "post",
+ path: "content/post.json",
+ contentType: "application/json",
+ }),
+ createFile({
+ id: "author",
+ path: "content/author.json",
+ contentType: "application/json",
+ }),
+ ],
+ sources: {
+ post: '{"author":{"$ref":"./author.json"}}',
+ author: '{"post":{"$ref":"./post.json"}}',
+ },
+ code: "CYCLE",
+ },
+ ])("rejects $name while compiling stored document sources", async (input) => {
+ await expect(
+ compileContentSource({
+ projectId,
+ source: createDocumentSource(input),
+ })
+ ).rejects.toMatchObject({ code: input.code });
+ });
+
+ test("propagates changed target revisions into graph edges and artifact integrity", async () => {
+ const compile = async (authorRevision: string) => {
+ const post = createFile({
+ id: "post",
+ path: "content/post.json",
+ contentType: "application/json",
+ });
+ const author = createFile({
+ id: "author",
+ path: "content/author.json",
+ contentType: "application/json",
+ revision: authorRevision,
+ });
+ return await compileContentSource({
+ projectId,
+ source: createDocumentSource({
+ files: [post, author],
+ sources: {
+ post: '{"author":{"$ref":"./author.json"}}',
+ author: '{"name":"Ada"}',
+ },
+ }),
+ });
+ };
+
+ const first = await compile("author-r1");
+ const second = await compile("author-r2");
+
+ expect(first.documentGraph?.edges[0].reference.revision).toBe("author-r1");
+ expect(second.documentGraph?.edges[0].reference.revision).toBe("author-r2");
+ expect(first.artifact.integrity.checksum).not.toBe(
+ second.artifact.integrity.checksum
+ );
+ });
+
test("describes a compiler entry with the snapshot contract", () => {
const file = createFile({ id: "post" });
expect(createContentSourceFile(createEntry(file))).toEqual(file);
@@ -292,6 +634,78 @@ describe("content source snapshots", () => {
).toEqual({ "revisions/post.md": ["hero"] });
});
+ test("keeps Markdown body content in storage for graph-backed queries", async () => {
+ const markdown = "---\ntitle: Post\nslug: post\n---\nStored body\n";
+ const post = createFile({
+ id: "post",
+ path: "blog/post.md",
+ size: new TextEncoder().encode(markdown).byteLength,
+ });
+ const source: ContentSource = {
+ async openSnapshot() {
+ return {
+ revision: "snapshot",
+ files: [post],
+ async loadEntries() {
+ return [{ ...createEntry(post), content: markdown }];
+ },
+ async loadDocumentSources() {
+ return [{ id: post.id, source: markdown }];
+ },
+ async isCurrent() {
+ return true;
+ },
+ };
+ },
+ };
+
+ const result = await compileContentSource({
+ source,
+ projectId,
+ plan: {
+ standardFields: [["extension"], ["mimeType"], ["revision"], ["size"]],
+ structuredPropertyPaths: [["properties", "slug"]],
+ excerpt: false,
+ metadataError: false,
+ queries: [
+ {
+ id: "post",
+ where: {
+ all: [
+ {
+ field: ["properties", "slug"],
+ operator: "eq",
+ value: { type: "dynamic" },
+ },
+ ],
+ },
+ sort: [],
+ limit: { type: "literal", value: 1 },
+ offset: { type: "literal", value: 0 },
+ output: {
+ mode: "fields",
+ includeMetadata: false,
+ fields: [["properties", "slug"]],
+ },
+ content: { mode: "markdown-body" },
+ },
+ ],
+ },
+ });
+
+ expect(result.artifact.contents).toBeUndefined();
+ expect(result.artifact.documentGraph).toMatchObject({
+ nodes: [
+ {
+ id: "post",
+ contentRef: "revisions/post.md",
+ format: "markdown",
+ },
+ ],
+ edges: [],
+ });
+ });
+
test("does not resolve an ambiguous Asset path", async () => {
const post = createFile({ id: "post", path: "blog/post.md" });
const firstImage = createFile({
diff --git a/packages/content-engine/src/content-source.ts b/packages/content-engine/src/content-source.ts
index 9ea88f2339..8c43eda50d 100644
--- a/packages/content-engine/src/content-source.ts
+++ b/packages/content-engine/src/content-source.ts
@@ -1,20 +1,29 @@
-import type { ContentCompilationPlan } from "./compilation-plan";
+import {
+ createContentCompilationPlan,
+ requiresStructuredProperties,
+ selectContentHydrationCandidates,
+ type ContentCompilationPlan,
+} from "./compilation-plan";
import {
compileContentArtifact,
type ContentCompilerDiagnostics,
type ContentCompilerInput,
} from "./asset-index";
import type { ContentArtifactV1 } from "./schema";
-import { selectContentHydrationCandidates } from "./compilation-plan";
import {
createUniqueAssetIdsByPath,
discoverMarkdownAssetReferenceRanges,
} from "./markdown-assets";
import type { MarkdownAssetReferences } from "./markdown-references";
import { compareStrings } from "./canonical-json";
-import { encodeUtf8 } from "./byte-stream";
+import { encodeUtf8, type ByteSource } from "./byte-stream";
import { extractMarkdownBody } from "./markdown-body";
import { contentEngineLimits } from "./limits";
+import {
+ compileDocumentSourceGraph,
+ getDocumentFormatByContentType,
+ type DocumentGraph,
+} from "./document-graph";
export type ContentSourceFile = {
id: string;
@@ -33,9 +42,15 @@ export interface ContentSourceSnapshot {
plan?: ContentCompilationPlan,
options?: { maximumContentBytes: number }
): Promise<readonly ContentCompilerInput[]>;
+ loadDocumentSources?(): Promise<readonly ContentSourceDocument[]>;
isCurrent(): Promise<boolean>;
}
+export type ContentSourceDocument = Readonly<{
+ id: string;
+ source: ByteSource;
+}>;
+
export interface ContentSource {
openSnapshot(): Promise<ContentSourceSnapshot>;
}
@@ -160,6 +175,95 @@ const discoverSnapshotAssetReferences = async ({
return references;
};
+const documentUrlBase = "https://content.webstudio.local/";
+
+const getDocumentUrl = (path: string) =>
+ new URL(path.split("/").map(encodeURIComponent).join("/"), documentUrlBase)
+ .href;
+
+const queryNeedsDocumentGraph = (
+ query: ContentCompilationPlan["queries"][number]
+) => {
+ if (
+ query.limit.type === "literal" &&
+ typeof query.limit.value === "number" &&
+ query.limit.value <= 0
+ ) {
+ return false;
+ }
+ if (query.content.mode === "markdown-body") {
+ return true;
+ }
+ const queryPlan = createContentCompilationPlan([query]);
+ return queryPlan !== undefined && requiresStructuredProperties(queryPlan);
+};
+
+const planDefersMarkdownBodies = (plan?: ContentCompilationPlan) =>
+ plan?.queries.some(({ content }) => content.mode === "markdown-body") ===
+ true;
+
+const discoverSnapshotDocumentGraph = async (
+ snapshot: ContentSourceSnapshot,
+ entries: readonly ContentCompilerInput[],
+ plan?: ContentCompilationPlan
+): Promise<DocumentGraph | undefined> => {
+ if (
+ snapshot.loadDocumentSources === undefined ||
+ (plan !== undefined && plan.queries.some(queryNeedsDocumentGraph) === false)
+ ) {
+ return;
+ }
+ const sourceDocuments = await snapshot.loadDocumentSources();
+ const filesById = new Map(snapshot.files.map((file) => [file.id, file]));
+ const sourcesById = new Map<string, ByteSource>();
+ for (const document of sourceDocuments) {
+ if (sourcesById.has(document.id)) {
+ throw new Error("Content source returned duplicate document sources");
+ }
+ const file = filesById.get(document.id);
+ if (
+ file === undefined ||
+ getDocumentFormatByContentType(file.contentType) === undefined
+ ) {
+ throw new Error("Content source returned an unsupported document source");
+ }
+ sourcesById.set(document.id, document.source);
+ }
+ const supportedFiles = snapshot.files.filter(
+ (file) => getDocumentFormatByContentType(file.contentType) !== undefined
+ );
+ if (supportedFiles.some((file) => sourcesById.has(file.id) === false)) {
+ throw new Error("Content source omitted a supported document source");
+ }
+ const graph = await compileDocumentSourceGraph({
+ documents: supportedFiles.map((file) => {
+ const format = getDocumentFormatByContentType(file.contentType);
+ const source = sourcesById.get(file.id);
+ if (format === undefined || source === undefined) {
+ throw new Error("Content source document catalog is incomplete");
+ }
+ return {
+ id: file.id,
+ documentUrl: getDocumentUrl(file.path),
+ revision: file.revision,
+ contentRef: file.contentRef,
+ format,
+ source,
+ };
+ }),
+ ...(plan === undefined
+ ? {}
+ : {
+ rootIds: entries.flatMap(({ assetId }) =>
+ sourcesById.has(assetId) ? [assetId] : []
+ ),
+ }),
+ });
+ return graph.edges.length === 0 && planDefersMarkdownBodies(plan) === false
+ ? undefined
+ : graph;
+};
+
export const materializeContentSnapshot = async ({
snapshot,
plan,
@@ -173,13 +277,23 @@ export const materializeContentSnapshot = async ({
try {
const entries = await snapshot.loadEntries(plan, { maximumContentBytes });
validateEntries({ snapshot, entries });
+ const documentGraph = await discoverSnapshotDocumentGraph(
+ snapshot,
+ entries,
+ plan
+ );
const assetReferences = await discoverSnapshotAssetReferences({
snapshot,
entries,
plan,
});
if (await snapshot.isCurrent()) {
- return { sourceRevision: snapshot.revision, entries, assetReferences };
+ return {
+ sourceRevision: snapshot.revision,
+ entries,
+ assetReferences,
+ documentGraph,
+ };
}
} catch (error) {
if (await snapshot.isCurrent()) {
@@ -201,10 +315,11 @@ export const compileContentSource = async ({
maxBytes?: number;
}): Promise<{
sourceRevision: string;
+ documentGraph?: DocumentGraph;
artifact: ContentArtifactV1;
diagnostics: ContentCompilerDiagnostics;
}> => {
- const { sourceRevision, entries, assetReferences } =
+ const { sourceRevision, entries, assetReferences, documentGraph } =
await materializeContentSource({
source,
plan,
@@ -214,10 +329,11 @@ export const compileContentSource = async ({
projectId,
entries,
assetReferences,
+ documentGraph,
...(plan === undefined ? {} : { plan }),
...(maxBytes === undefined ? {} : { maxBytes }),
});
- return { sourceRevision, ...compiled };
+ return { sourceRevision, documentGraph, ...compiled };
};
export const materializeContentSource = async ({
@@ -232,6 +348,7 @@ export const materializeContentSource = async ({
sourceRevision: string;
entries: readonly ContentCompilerInput[];
assetReferences: MarkdownAssetReferences;
+ documentGraph?: DocumentGraph;
}> => {
for (let attempt = 0; attempt < 2; attempt += 1) {
const snapshot = await source.openSnapshot();
diff --git a/packages/content-engine/src/document-graph/cached-document-loader.test.ts b/packages/content-engine/src/document-graph/cached-document-loader.test.ts
new file mode 100644
index 0000000000..2554bc2c36
--- /dev/null
+++ b/packages/content-engine/src/document-graph/cached-document-loader.test.ts
@@ -0,0 +1,239 @@
+import { describe, expect, test, vi } from "vitest";
+import { parseDocumentSource } from "./document-adapter";
+import {
+ createCachedDocumentSourceLoader,
+ getDocumentSourceCacheKey,
+ type CachedDocumentSource,
+} from "./cached-document-loader";
+
+const node = {
+ id: "post",
+ revision: "post-r1",
+ contentRef: "content:post",
+ format: "json" as const,
+};
+
+describe("cached document source loader", () => {
+ test("supports loader-defined formats", async () => {
+ const cache = {
+ get: vi.fn(async () => undefined),
+ set: vi.fn(async () => undefined),
+ };
+ const load = vi.fn(async () => ({
+ format: "json" as const,
+ revision: "post-r1",
+ source: "{}",
+ }));
+ const cachedLoad = createCachedDocumentSourceLoader({ cache, load });
+
+ await expect(
+ cachedLoad(
+ {
+ id: "post",
+ revision: "post-r1",
+ contentRef: "content:post",
+ },
+ {}
+ )
+ ).resolves.toMatchObject({ format: "json", revision: "post-r1" });
+ expect(load).toHaveBeenCalledOnce();
+ expect(cache.set).toHaveBeenCalledOnce();
+ });
+
+ test("returns replayable bytes from a revision-keyed cache hit", async () => {
+ const cached: CachedDocumentSource = {
+ format: "json",
+ revision: "post-r1",
+ bytes: new TextEncoder().encode('{"title":"Cached"}'),
+ };
+ const cache = {
+ get: vi.fn(async () => cached),
+ set: vi.fn(async () => undefined),
+ };
+ const load = vi.fn(async () => {
+ throw new Error("source loader must not run");
+ });
+ const cachedLoad = createCachedDocumentSourceLoader({ cache, load });
+
+ const result = await cachedLoad(node, {});
+ expect(cache.get).toHaveBeenCalledWith(
+ getDocumentSourceCacheKey({
+ contentRef: "content:post",
+ revision: "post-r1",
+ format: "json",
+ })
+ );
+ expect(load).not.toHaveBeenCalled();
+ await expect(parseDocumentSource(result)).resolves.toEqual({
+ format: "json",
+ value: { title: "Cached" },
+ });
+ });
+
+ test("does not reuse a cached source with a different format", async () => {
+ const load = vi.fn(async () => ({
+ format: "json" as const,
+ revision: "post-r1",
+ source: "{}",
+ }));
+ const cache = {
+ get: vi.fn(async () => ({
+ format: "markdown" as const,
+ revision: "post-r1",
+ bytes: new TextEncoder().encode("# stale"),
+ })),
+ set: vi.fn(async () => undefined),
+ };
+
+ const result = await createCachedDocumentSourceLoader({ cache, load })(
+ node,
+ {}
+ );
+
+ expect(load).toHaveBeenCalledOnce();
+ await expect(parseDocumentSource(result)).resolves.toEqual({
+ format: "json",
+ value: {},
+ });
+ });
+
+ test("does not reuse a cached source above the active byte limit", async () => {
+ const load = vi.fn(async () => ({
+ format: "json" as const,
+ revision: "post-r1",
+ source: "{}",
+ }));
+ const cache = {
+ get: vi.fn(async () => ({
+ format: "json" as const,
+ revision: "post-r1",
+ bytes: new TextEncoder().encode("{}\n"),
+ })),
+ set: vi.fn(async () => undefined),
+ };
+
+ const result = await createCachedDocumentSourceLoader({
+ cache,
+ load,
+ maximumBytes: 2,
+ })(node, {});
+
+ expect(load).toHaveBeenCalledOnce();
+ expect(cache.set).toHaveBeenCalledOnce();
+ await expect(parseDocumentSource(result)).resolves.toEqual({
+ format: "json",
+ value: {},
+ });
+ });
+
+ test("materializes and stores one bounded miss for concurrent callers", async () => {
+ const cache = {
+ get: vi.fn(async () => undefined),
+ set: vi.fn(async () => undefined),
+ };
+ const load = vi.fn(async () => ({
+ format: "json" as const,
+ revision: "post-r1",
+ source: {
+ async *[Symbol.asyncIterator]() {
+ yield new TextEncoder().encode('{"title":');
+ await Promise.resolve();
+ yield new TextEncoder().encode('"Fresh"}');
+ },
+ },
+ }));
+ const cachedLoad = createCachedDocumentSourceLoader({ cache, load });
+
+ const [first, second] = await Promise.all([
+ cachedLoad(node, {}),
+ cachedLoad(node, {}),
+ ]);
+
+ expect(load).toHaveBeenCalledOnce();
+ expect(cache.set).toHaveBeenCalledOnce();
+ expect(first).toBe(second);
+ expect(first.source).toBeInstanceOf(Uint8Array);
+ });
+
+ test("replaces stale cache entries and rejects oversized misses", async () => {
+ const set = vi.fn(async () => undefined);
+ const load = vi.fn(async () => ({
+ format: "json" as const,
+ revision: "post-r1",
+ source: '{"title":"Fresh"}',
+ }));
+ const staleLoad = createCachedDocumentSourceLoader({
+ cache: {
+ get: async () => ({
+ format: "json",
+ revision: "stale-r1",
+ bytes: new Uint8Array(),
+ }),
+ set,
+ },
+ load,
+ });
+ const refreshed = await staleLoad(node, {});
+ await expect(parseDocumentSource(refreshed)).resolves.toEqual({
+ format: "json",
+ value: { title: "Fresh" },
+ });
+ expect(load).toHaveBeenCalledOnce();
+ expect(set).toHaveBeenCalledOnce();
+
+ const cache = {
+ get: async () => undefined,
+ set: vi.fn(async () => undefined),
+ };
+ const oversizedLoad = createCachedDocumentSourceLoader({
+ cache,
+ maximumBytes: 2,
+ load: async () => ({
+ format: "json",
+ revision: "post-r1",
+ source: "{}\n",
+ }),
+ });
+ await expect(oversizedLoad(node, {})).rejects.toMatchObject({
+ code: "CONTENT_LIMIT_EXCEEDED",
+ documentId: "post",
+ });
+ expect(cache.set).not.toHaveBeenCalled();
+ });
+
+ test("reports cache hits, misses, and stores", async () => {
+ const events: unknown[] = [];
+ const cached: CachedDocumentSource = {
+ format: "json",
+ revision: "post-r1",
+ bytes: new TextEncoder().encode("{}"),
+ };
+ const load = vi.fn(async () => ({
+ format: "json" as const,
+ revision: "post-r1",
+ source: "{}",
+ }));
+ const cache = {
+ get: vi.fn().mockResolvedValueOnce(undefined).mockResolvedValue(cached),
+ set: vi.fn(async () => undefined),
+ };
+ const cachedLoad = createCachedDocumentSourceLoader({
+ cache,
+ load,
+ onEvent: (event) => events.push(event),
+ });
+
+ await cachedLoad(node, {});
+ await cachedLoad(node, {});
+
+ expect(events).toEqual([
+ { type: "document-cache-miss", documentId: "post", revision: "post-r1" },
+ {
+ type: "document-cache-stored",
+ documentId: "post",
+ revision: "post-r1",
+ },
+ { type: "document-cache-hit", documentId: "post", revision: "post-r1" },
+ ]);
+ });
+});
diff --git a/packages/content-engine/src/document-graph/cached-document-loader.ts b/packages/content-engine/src/document-graph/cached-document-loader.ts
new file mode 100644
index 0000000000..1c6dac8d22
--- /dev/null
+++ b/packages/content-engine/src/document-graph/cached-document-loader.ts
@@ -0,0 +1,187 @@
+import { ByteLimitExceededError, readBoundedBytes } from "../byte-stream";
+import { serializeJsonDeterministically } from "../canonical-json";
+import { contentEngineLimits } from "../limits";
+import type { DocumentFormat } from "./document-adapter";
+import type { DocumentGraphNode } from "./graph";
+import {
+ assertDocumentSourceIdentity,
+ type DocumentSource,
+ type DocumentSourceLoader,
+} from "./document-source";
+import {
+ emitDocumentGraphRuntimeEvent,
+ getDocumentGraphErrorCode,
+ type DocumentGraphRuntimeObserver,
+} from "./observability";
+
+export type CachedDocumentSource = Readonly<{
+ format: DocumentFormat;
+ revision: string;
+ bytes: Uint8Array;
+}>;
+
+export interface DocumentSourceCache {
+ get(key: string): Promise<CachedDocumentSource | undefined>;
+ set(key: string, source: CachedDocumentSource): Promise<void>;
+}
+
+export class CachedDocumentLoaderError extends Error {
+ readonly code = "CONTENT_LIMIT_EXCEEDED";
+ readonly documentId: string;
+ readonly contentByteLimit: number;
+
+ constructor({
+ message,
+ documentId,
+ contentByteLimit,
+ cause,
+ }: {
+ message: string;
+ documentId: string;
+ contentByteLimit: number;
+ cause?: unknown;
+ }) {
+ super(message, { cause });
+ this.name = "CachedDocumentLoaderError";
+ this.documentId = documentId;
+ this.contentByteLimit = contentByteLimit;
+ }
+}
+
+export const getDocumentSourceCacheKey = ({
+ contentRef,
+ revision,
+ format,
+}: Pick<DocumentGraphNode, "contentRef" | "revision" | "format">) =>
+ serializeJsonDeterministically([contentRef, revision, format ?? null]);
+
+const isCachedDocumentSource = (
+ input: unknown
+): input is CachedDocumentSource => {
+ if (typeof input !== "object" || input === null) {
+ return false;
+ }
+ const value = input as Partial<CachedDocumentSource>;
+ return (
+ (value.format === "json" || value.format === "markdown") &&
+ typeof value.revision === "string" &&
+ value.revision.length > 0 &&
+ value.bytes instanceof Uint8Array
+ );
+};
+
+const toDocumentSource = (source: CachedDocumentSource): DocumentSource =>
+ Object.freeze({
+ format: source.format,
+ revision: source.revision,
+ source: source.bytes,
+ });
+
+/** Adds revision-keyed bounded caching around any document source loader. */
+export const createCachedDocumentSourceLoader = ({
+ load,
+ cache,
+ maximumBytes = contentEngineLimits.hydratedFileBytes,
+ onEvent,
+}: {
+ load: DocumentSourceLoader;
+ cache: DocumentSourceCache;
+ maximumBytes?: number;
+ onEvent?: DocumentGraphRuntimeObserver;
+}): DocumentSourceLoader => {
+ const pending = new Map<
+ string,
+ Map<AbortSignal | undefined, Promise<DocumentSource>>
+ >();
+
+ return async (node, options) => {
+ const key = getDocumentSourceCacheKey(node);
+ const pendingBySignal = pending.get(key) ?? new Map();
+ pending.set(key, pendingBySignal);
+ const previous = pendingBySignal.get(options.signal);
+ if (previous !== undefined) {
+ return await previous;
+ }
+ const request = (async () => {
+ let cached: CachedDocumentSource | undefined;
+ try {
+ cached = await cache.get(key);
+ } catch (error) {
+ emitDocumentGraphRuntimeEvent(onEvent, {
+ type: "document-cache-read-failed",
+ documentId: node.id,
+ revision: node.revision,
+ errorCode: getDocumentGraphErrorCode(error),
+ });
+ // Cache availability must not prevent an origin read.
+ }
+ if (
+ isCachedDocumentSource(cached) &&
+ cached.revision === node.revision &&
+ cached.bytes.byteLength <= maximumBytes &&
+ (node.format === undefined || cached.format === node.format)
+ ) {
+ emitDocumentGraphRuntimeEvent(onEvent, {
+ type: "document-cache-hit",
+ documentId: node.id,
+ revision: node.revision,
+ });
+ return toDocumentSource(cached);
+ }
+ emitDocumentGraphRuntimeEvent(onEvent, {
+ type: "document-cache-miss",
+ documentId: node.id,
+ revision: node.revision,
+ });
+
+ const loaded = assertDocumentSourceIdentity({
+ node,
+ source: await load(node, options),
+ });
+ let bytes: Uint8Array;
+ try {
+ bytes = await readBoundedBytes(loaded.source, maximumBytes);
+ } catch (cause) {
+ if (cause instanceof ByteLimitExceededError) {
+ throw new CachedDocumentLoaderError({
+ message: `Document ${node.id} exceeds the cache byte limit`,
+ documentId: node.id,
+ contentByteLimit: maximumBytes,
+ cause,
+ });
+ }
+ throw cause;
+ }
+ const entry = Object.freeze({
+ format: loaded.format,
+ revision: loaded.revision,
+ bytes,
+ });
+ try {
+ await cache.set(key, entry);
+ emitDocumentGraphRuntimeEvent(onEvent, {
+ type: "document-cache-stored",
+ documentId: node.id,
+ revision: node.revision,
+ });
+ } catch (error) {
+ emitDocumentGraphRuntimeEvent(onEvent, {
+ type: "document-cache-write-failed",
+ documentId: node.id,
+ revision: node.revision,
+ errorCode: getDocumentGraphErrorCode(error),
+ });
+ }
+ return toDocumentSource(entry);
+ })();
+ pendingBySignal.set(options.signal, request);
+ try {
+ return await request;
+ } finally {
+ pendingBySignal.delete(options.signal);
+ if (pendingBySignal.size === 0) {
+ pending.delete(key);
+ }
+ }
+ };
+};
diff --git a/packages/content-engine/src/document-graph/compiler.test.ts b/packages/content-engine/src/document-graph/compiler.test.ts
new file mode 100644
index 0000000000..d118434f8d
--- /dev/null
+++ b/packages/content-engine/src/document-graph/compiler.test.ts
@@ -0,0 +1,215 @@
+import { describe, expect, test } from "vitest";
+import { parseSourceDocumentReference } from "./reference-codec";
+import {
+ compileDocumentGraph,
+ DocumentGraphCompilationError,
+} from "./compiler";
+
+const documents = [
+ {
+ id: "post",
+ documentUrl: "https://content.webstudio.test/posts/hello.json",
+ revision: "post-r1",
+ contentRef: "content:post",
+ },
+ {
+ id: "author",
+ documentUrl: "https://content.webstudio.test/authors/ada.json",
+ revision: "author-r2",
+ contentRef: "content:author",
+ },
+ {
+ id: "avatar",
+ documentUrl: "https://content.webstudio.test/media/ada.json",
+ revision: "avatar-r3",
+ contentRef: "content:avatar",
+ },
+];
+
+const references = [
+ {
+ sourceDocumentId: "post",
+ referenceId: "author",
+ reference: parseSourceDocumentReference({
+ value: "../authors/ada.json#/name",
+ baseUrl: documents[0].documentUrl,
+ }),
+ },
+ {
+ sourceDocumentId: "author",
+ referenceId: "avatar",
+ reference: parseSourceDocumentReference({
+ value: "../media/ada.json",
+ baseUrl: documents[1].documentUrl,
+ }),
+ },
+];
+
+describe("document graph compiler", () => {
+ test("resolves source references to deterministic graph edges", () => {
+ const graph = compileDocumentGraph({
+ documents: [...documents].reverse(),
+ references: [...references].reverse(),
+ });
+
+ expect(graph.nodes).toEqual([
+ { id: "author", revision: "author-r2", contentRef: "content:author" },
+ { id: "avatar", revision: "avatar-r3", contentRef: "content:avatar" },
+ { id: "post", revision: "post-r1", contentRef: "content:post" },
+ ]);
+ expect(graph.edges).toEqual([
+ {
+ sourceId: "author",
+ referenceId: "avatar",
+ reference: {
+ documentId: "avatar",
+ revision: "avatar-r3",
+ representation: { type: "document" },
+ },
+ },
+ {
+ sourceId: "post",
+ referenceId: "author",
+ reference: {
+ documentId: "author",
+ revision: "author-r2",
+ representation: { type: "json", path: ["name"] },
+ },
+ },
+ ]);
+ });
+
+ test("matches canonical document URLs", () => {
+ const graph = compileDocumentGraph({
+ documents,
+ references: [
+ {
+ ...references[0],
+ reference: {
+ ...references[0].reference,
+ documentUrl:
+ "https://CONTENT.webstudio.test/authors/../authors/ada.json",
+ },
+ },
+ ],
+ });
+
+ expect(graph.edges[0].reference.documentId).toBe("author");
+ });
+
+ test("reports a missing target with source occurrence context", () => {
+ expect(() =>
+ compileDocumentGraph({
+ documents,
+ references: [
+ {
+ ...references[0],
+ referenceId: "missing-author",
+ reference: {
+ ...references[0].reference,
+ documentUrl:
+ "https://content.webstudio.test/authors/missing.json",
+ },
+ },
+ ],
+ })
+ ).toThrowError(
+ expect.objectContaining({
+ code: "TARGET_NOT_FOUND",
+ sourceDocumentId: "post",
+ referenceId: "missing-author",
+ documentUrl: "https://content.webstudio.test/authors/missing.json",
+ } satisfies Partial<DocumentGraphCompilationError>)
+ );
+ });
+
+ test("reports a missing source with reference context", () => {
+ expect(() =>
+ compileDocumentGraph({
+ documents,
+ references: [{ ...references[0], sourceDocumentId: "missing-post" }],
+ })
+ ).toThrowError(
+ expect.objectContaining({
+ code: "SOURCE_NOT_FOUND",
+ sourceDocumentId: "missing-post",
+ referenceId: "author",
+ } satisfies Partial<DocumentGraphCompilationError>)
+ );
+ });
+
+ test("rejects duplicate canonical document URLs", () => {
+ expect(() =>
+ compileDocumentGraph({
+ documents: [
+ ...documents,
+ {
+ id: "author-alias",
+ documentUrl:
+ "https://CONTENT.webstudio.test/people/../authors/ada.json",
+ revision: "author-r2",
+ contentRef: "content:author",
+ },
+ ],
+ references: [],
+ })
+ ).toThrowError(
+ expect.objectContaining({
+ code: "DUPLICATE_DOCUMENT_URL",
+ documentIds: ["author", "author-alias"],
+ } satisfies Partial<DocumentGraphCompilationError>)
+ );
+ });
+
+ test("rejects duplicate document IDs before resolving references", () => {
+ expect(() =>
+ compileDocumentGraph({
+ documents: [
+ ...documents,
+ {
+ id: "author",
+ documentUrl: "https://content.webstudio.test/authors/grace.json",
+ revision: "author-r4",
+ contentRef: "content:grace",
+ },
+ ].reverse(),
+ references,
+ })
+ ).toThrowError(
+ expect.objectContaining({
+ code: "DUPLICATE_DOCUMENT_ID",
+ documentIds: ["author"],
+ } satisfies Partial<DocumentGraphCompilationError>)
+ );
+ });
+
+ test("validates cycles across disconnected components", () => {
+ const cycleReferences = [
+ {
+ sourceDocumentId: "author",
+ referenceId: "avatar",
+ reference: parseSourceDocumentReference({
+ value: documents[2].documentUrl,
+ baseUrl: documents[1].documentUrl,
+ }),
+ },
+ {
+ sourceDocumentId: "avatar",
+ referenceId: "author",
+ reference: parseSourceDocumentReference({
+ value: documents[1].documentUrl,
+ baseUrl: documents[2].documentUrl,
+ }),
+ },
+ ];
+
+ expect(() =>
+ compileDocumentGraph({ documents, references: cycleReferences })
+ ).toThrowError(
+ expect.objectContaining({
+ code: "CYCLE",
+ documentIds: ["author", "avatar", "author"],
+ } satisfies Partial<DocumentGraphCompilationError>)
+ );
+ });
+});
diff --git a/packages/content-engine/src/document-graph/compiler.ts b/packages/content-engine/src/document-graph/compiler.ts
new file mode 100644
index 0000000000..2e42bb7817
--- /dev/null
+++ b/packages/content-engine/src/document-graph/compiler.ts
@@ -0,0 +1,239 @@
+import { compareStrings } from "../canonical-json";
+import {
+ createDocumentGraph,
+ DocumentGraphError,
+ getDocumentGraphClosure,
+ type DocumentGraph,
+} from "./graph";
+import type { SourceReferenceOccurrence } from "./reference-codec";
+
+export type DocumentDescriptor = Readonly<{
+ id: string;
+ documentUrl: string;
+ revision: string;
+ contentRef: string;
+ format?: "json" | "markdown";
+}>;
+
+export type DocumentGraphCompilationErrorCode =
+ | "INVALID_DOCUMENT_URL"
+ | "INVALID_REFERENCE_URL"
+ | "DUPLICATE_DOCUMENT_ID"
+ | "DUPLICATE_DOCUMENT_URL"
+ | "SOURCE_NOT_FOUND"
+ | "TARGET_NOT_FOUND"
+ | "INVALID_GRAPH"
+ | "CYCLE";
+
+export class DocumentGraphCompilationError extends Error {
+ readonly code: DocumentGraphCompilationErrorCode;
+ readonly sourceDocumentId?: string;
+ readonly referenceId?: string;
+ readonly documentUrl?: string;
+ readonly documentIds: readonly string[];
+
+ constructor({
+ code,
+ message,
+ sourceDocumentId,
+ referenceId,
+ documentUrl,
+ documentIds = [],
+ cause,
+ }: {
+ code: DocumentGraphCompilationErrorCode;
+ message: string;
+ sourceDocumentId?: string;
+ referenceId?: string;
+ documentUrl?: string;
+ documentIds?: readonly string[];
+ cause?: unknown;
+ }) {
+ super(message, { cause });
+ this.name = "DocumentGraphCompilationError";
+ this.code = code;
+ this.sourceDocumentId = sourceDocumentId;
+ this.referenceId = referenceId;
+ this.documentUrl = documentUrl;
+ this.documentIds = Object.freeze([...documentIds]);
+ }
+}
+
+const getCanonicalDocumentUrl = ({
+ documentUrl,
+ documentId,
+ occurrence,
+}: {
+ documentUrl: string;
+ documentId?: string;
+ occurrence?: SourceReferenceOccurrence;
+}) => {
+ let url: URL;
+ try {
+ url = new URL(documentUrl);
+ } catch (cause) {
+ throw new DocumentGraphCompilationError({
+ code:
+ occurrence === undefined
+ ? "INVALID_DOCUMENT_URL"
+ : "INVALID_REFERENCE_URL",
+ message:
+ occurrence === undefined
+ ? `Document ${documentId} URL must be absolute`
+ : `Document ${occurrence.sourceDocumentId} reference ${occurrence.referenceId} target URL must be absolute`,
+ sourceDocumentId: occurrence?.sourceDocumentId,
+ referenceId: occurrence?.referenceId,
+ documentUrl,
+ documentIds: documentId === undefined ? [] : [documentId],
+ cause,
+ });
+ }
+ if (url.hash !== "") {
+ throw new DocumentGraphCompilationError({
+ code:
+ occurrence === undefined
+ ? "INVALID_DOCUMENT_URL"
+ : "INVALID_REFERENCE_URL",
+ message:
+ occurrence === undefined
+ ? `Document ${documentId} URL must not contain a fragment`
+ : `Document ${occurrence.sourceDocumentId} reference ${occurrence.referenceId} target URL must not contain a fragment`,
+ sourceDocumentId: occurrence?.sourceDocumentId,
+ referenceId: occurrence?.referenceId,
+ documentUrl,
+ documentIds: documentId === undefined ? [] : [documentId],
+ });
+ }
+ return url.href;
+};
+
+const compareReferences = (
+ left: SourceReferenceOccurrence,
+ right: SourceReferenceOccurrence
+) =>
+ compareStrings(left.sourceDocumentId, right.sourceDocumentId) ||
+ compareStrings(left.referenceId, right.referenceId) ||
+ compareStrings(left.reference.documentUrl, right.reference.documentUrl);
+
+/** Resolves parsed source references into a validated, storage-independent graph. */
+export const compileDocumentGraph = ({
+ documents: documentInputs,
+ references: referenceInputs,
+}: {
+ documents: readonly DocumentDescriptor[];
+ references: readonly SourceReferenceOccurrence[];
+}): DocumentGraph => {
+ const documents = [...documentInputs]
+ .sort(
+ (left, right) =>
+ compareStrings(left.id, right.id) ||
+ compareStrings(left.documentUrl, right.documentUrl) ||
+ compareStrings(left.revision, right.revision) ||
+ compareStrings(left.contentRef, right.contentRef)
+ )
+ .map((document) => ({
+ ...document,
+ documentUrl: getCanonicalDocumentUrl({
+ documentUrl: document.documentUrl,
+ documentId: document.id,
+ }),
+ }));
+ const documentsById = new Map<string, DocumentDescriptor>();
+ const documentsByUrl = new Map<string, DocumentDescriptor>();
+ for (const document of documents) {
+ if (documentsById.has(document.id)) {
+ throw new DocumentGraphCompilationError({
+ code: "DUPLICATE_DOCUMENT_ID",
+ message: `Document catalog contains duplicate ID ${document.id}`,
+ documentIds: [document.id],
+ });
+ }
+ documentsById.set(document.id, document);
+ const previous = documentsByUrl.get(document.documentUrl);
+ if (previous !== undefined) {
+ throw new DocumentGraphCompilationError({
+ code: "DUPLICATE_DOCUMENT_URL",
+ message: `Documents ${previous.id} and ${document.id} have the same canonical URL`,
+ documentUrl: document.documentUrl,
+ documentIds: [previous.id, document.id],
+ });
+ }
+ documentsByUrl.set(document.documentUrl, document);
+ }
+
+ const edges = [...referenceInputs]
+ .sort(compareReferences)
+ .map((occurrence) => {
+ if (documentsById.has(occurrence.sourceDocumentId) === false) {
+ throw new DocumentGraphCompilationError({
+ code: "SOURCE_NOT_FOUND",
+ message: `Document graph source ${occurrence.sourceDocumentId} does not exist`,
+ sourceDocumentId: occurrence.sourceDocumentId,
+ referenceId: occurrence.referenceId,
+ documentIds: [occurrence.sourceDocumentId],
+ });
+ }
+ const documentUrl = getCanonicalDocumentUrl({
+ documentUrl: occurrence.reference.documentUrl,
+ occurrence,
+ });
+ const target = documentsByUrl.get(documentUrl);
+ if (target === undefined) {
+ throw new DocumentGraphCompilationError({
+ code: "TARGET_NOT_FOUND",
+ message: `Document ${occurrence.sourceDocumentId} reference ${occurrence.referenceId} target does not exist`,
+ sourceDocumentId: occurrence.sourceDocumentId,
+ referenceId: occurrence.referenceId,
+ documentUrl,
+ documentIds: [occurrence.sourceDocumentId],
+ });
+ }
+ return {
+ sourceId: occurrence.sourceDocumentId,
+ referenceId: occurrence.referenceId,
+ reference: {
+ documentId: target.id,
+ revision: target.revision,
+ representation: occurrence.reference.representation,
+ },
+ };
+ });
+
+ let graph: DocumentGraph;
+ try {
+ graph = createDocumentGraph({
+ nodes: documents.map(({ id, revision, contentRef, format }) => ({
+ id,
+ revision,
+ contentRef,
+ ...(format === undefined ? {} : { format }),
+ })),
+ edges,
+ });
+ } catch (cause) {
+ throw new DocumentGraphCompilationError({
+ code: "INVALID_GRAPH",
+ message: "Compiled document graph is invalid",
+ documentIds: cause instanceof DocumentGraphError ? cause.documentIds : [],
+ cause,
+ });
+ }
+
+ try {
+ getDocumentGraphClosure({
+ graph,
+ rootIds: graph.nodes.map(({ id }) => id),
+ });
+ } catch (cause) {
+ if (cause instanceof DocumentGraphError && cause.code === "CYCLE") {
+ throw new DocumentGraphCompilationError({
+ code: "CYCLE",
+ message: cause.message,
+ documentIds: cause.documentIds,
+ cause,
+ });
+ }
+ throw cause;
+ }
+ return graph;
+};
diff --git a/packages/content-engine/src/document-graph/document-adapter.test.ts b/packages/content-engine/src/document-graph/document-adapter.test.ts
new file mode 100644
index 0000000000..dc7e1aff7f
--- /dev/null
+++ b/packages/content-engine/src/document-graph/document-adapter.test.ts
@@ -0,0 +1,86 @@
+import { describe, expect, test } from "vitest";
+import {
+ analyzeDocumentSource,
+ assembleDocument,
+ selectDocumentRepresentation,
+} from "./document-adapter";
+
+const documentUrl = "https://content.webstudio.test/posts/hello";
+
+describe("document adapter", () => {
+ test.each([
+ {
+ format: "json" as const,
+ source: '{"title":"Hello","author":{"$ref":"../authors/ada.json"}}',
+ referenceId: "#/author",
+ },
+ {
+ format: "markdown" as const,
+ source: "---\nauthor:\n $ref: ../authors/ada.json\n---\n# Hello\n",
+ referenceId: "#frontmatter/author",
+ },
+ ])("analyzes $format sources through one contract", async (fixture) => {
+ const analyzed = await analyzeDocumentSource({
+ format: fixture.format,
+ source: fixture.source,
+ sourceDocumentId: "post",
+ documentUrl,
+ });
+
+ expect(analyzed.format).toBe(fixture.format);
+ expect(analyzed.references).toEqual([
+ expect.objectContaining({ referenceId: fixture.referenceId }),
+ ]);
+ });
+
+ test("assembles and selects JSON representations without losing the format", async () => {
+ const analyzed = await analyzeDocumentSource({
+ format: "json",
+ source: '{"author":{"$ref":"../authors/ada.json"},"title":"Hello"}',
+ sourceDocumentId: "post",
+ documentUrl,
+ });
+ const assembled = assembleDocument({
+ document: analyzed,
+ references: new Map([["#/author", { name: "Ada" }]]),
+ });
+
+ expect(assembled).toEqual({
+ format: "json",
+ value: { author: { name: "Ada" }, title: "Hello" },
+ });
+ expect(
+ selectDocumentRepresentation({
+ document: assembled,
+ representation: { type: "json", path: ["author", "name"] },
+ })
+ ).toBe("Ada");
+ });
+
+ test("assembles and selects Markdown representations without losing the format", async () => {
+ const analyzed = await analyzeDocumentSource({
+ format: "markdown",
+ source: "---\nauthor:\n $ref: ../authors/ada.json\n---\n# Hello\n",
+ sourceDocumentId: "post",
+ documentUrl,
+ });
+ const assembled = assembleDocument({
+ document: analyzed,
+ references: new Map([["#frontmatter/author", { name: "Ada" }]]),
+ });
+
+ expect(assembled.format).toBe("markdown");
+ expect(
+ selectDocumentRepresentation({
+ document: assembled,
+ representation: { type: "markdown-frontmatter" },
+ })
+ ).toEqual({ author: { name: "Ada" } });
+ expect(
+ selectDocumentRepresentation({
+ document: assembled,
+ representation: { type: "markdown-body" },
+ })
+ ).toBe("# Hello\n");
+ });
+});
diff --git a/packages/content-engine/src/document-graph/document-adapter.ts b/packages/content-engine/src/document-graph/document-adapter.ts
new file mode 100644
index 0000000000..7d3790c9c6
--- /dev/null
+++ b/packages/content-engine/src/document-graph/document-adapter.ts
@@ -0,0 +1,171 @@
+import type { ByteSource } from "../byte-stream";
+import type { JsonValue } from "../canonical-json";
+import { contentEngineLimits } from "../limits";
+import {
+ analyzeJsonDocumentSource,
+ assembleJsonDocument,
+ parseJsonDocumentSource,
+ selectJsonDocumentRepresentation,
+} from "./json-document";
+import {
+ analyzeMarkdownDocument,
+ assembleMarkdownDocument,
+ parseMarkdownDocumentSource,
+ selectMarkdownDocumentRepresentation,
+ type MarkdownDocument,
+} from "./markdown-document";
+import type { DocumentRepresentation } from "./reference";
+import type { SourceReferenceOccurrence } from "./reference-codec";
+import { isJsonObject } from "./document-utils";
+
+export type DocumentFormat = "json" | "markdown";
+
+export const getDocumentFormatByContentType = (
+ contentType: string
+): DocumentFormat | undefined => {
+ const mimeType = contentType.split(";", 1)[0].trim().toLowerCase();
+ if (mimeType === "application/json") {
+ return "json";
+ }
+ if (mimeType === "text/markdown") {
+ return "markdown";
+ }
+};
+
+export type AdaptedDocument =
+ | Readonly<{ format: "json"; value: JsonValue }>
+ | Readonly<{ format: "markdown"; value: MarkdownDocument }>;
+
+export type AnalyzedDocument =
+ | Readonly<{
+ format: "json";
+ value: JsonValue;
+ references: readonly SourceReferenceOccurrence[];
+ }>
+ | Readonly<{
+ format: "markdown";
+ value: MarkdownDocument;
+ references: readonly SourceReferenceOccurrence[];
+ }>;
+
+export const getAdaptedDocumentProperties = (document: AdaptedDocument) => {
+ const value =
+ document.format === "markdown"
+ ? document.value.frontmatter
+ : document.value;
+ return isJsonObject(value) ? value : undefined;
+};
+
+const freezeDocument = <Document extends AdaptedDocument | AnalyzedDocument>(
+ document: Document
+) => Object.freeze(document);
+
+/** Parses a bounded source without resolving its reference syntax. */
+export const parseDocumentSource = async ({
+ format,
+ source,
+ maximumBytes = contentEngineLimits.hydratedFileBytes,
+}: {
+ format: DocumentFormat;
+ source: ByteSource;
+ maximumBytes?: number;
+}): Promise<AdaptedDocument> => {
+ if (format === "json") {
+ return freezeDocument({
+ format,
+ value: await parseJsonDocumentSource({ source, maximumBytes }),
+ });
+ }
+ return freezeDocument({
+ format,
+ value: await parseMarkdownDocumentSource({ source, maximumBytes }),
+ });
+};
+
+/** Parses a bounded source through its format-specific adapter. */
+export const analyzeDocumentSource = async ({
+ format,
+ source,
+ sourceDocumentId,
+ documentUrl,
+ maximumBytes = contentEngineLimits.hydratedFileBytes,
+}: {
+ format: DocumentFormat;
+ source: ByteSource;
+ sourceDocumentId: string;
+ documentUrl: string | URL;
+ maximumBytes?: number;
+}): Promise<AnalyzedDocument> => {
+ if (format === "json") {
+ const analyzed = await analyzeJsonDocumentSource({
+ source,
+ sourceDocumentId,
+ documentUrl,
+ maximumBytes,
+ });
+ return freezeDocument({
+ format,
+ value: analyzed.document,
+ references: analyzed.references,
+ });
+ }
+ const analyzed = await analyzeMarkdownDocument({
+ source,
+ sourceDocumentId,
+ documentUrl,
+ maximumBytes,
+ });
+ return freezeDocument({
+ format,
+ value: analyzed.document,
+ references: analyzed.references,
+ });
+};
+
+export const assembleDocument = ({
+ document,
+ references,
+ allowUnresolvedReferences,
+}: {
+ document: AdaptedDocument;
+ references: ReadonlyMap<string, unknown>;
+ allowUnresolvedReferences?: boolean;
+}): AdaptedDocument => {
+ if (document.format === "json") {
+ return freezeDocument({
+ format: document.format,
+ value: assembleJsonDocument({
+ document: document.value,
+ references,
+ allowUnresolvedReferences,
+ }),
+ });
+ }
+ return freezeDocument({
+ format: document.format,
+ value: assembleMarkdownDocument({
+ document: document.value,
+ references,
+ allowUnresolvedReferences,
+ }),
+ });
+};
+
+export const selectDocumentRepresentation = ({
+ document,
+ representation,
+}: {
+ document: AdaptedDocument;
+ representation: DocumentRepresentation;
+}): JsonValue => {
+ if (document.format === "json") {
+ return selectJsonDocumentRepresentation({
+ document: document.value,
+ representation,
+ });
+ }
+ return selectMarkdownDocumentRepresentation({
+ document: document.value,
+ representation,
+ });
+};
diff --git a/packages/content-engine/src/document-graph/document-resolution.test.ts b/packages/content-engine/src/document-graph/document-resolution.test.ts
new file mode 100644
index 0000000000..0d2bd8066e
--- /dev/null
+++ b/packages/content-engine/src/document-graph/document-resolution.test.ts
@@ -0,0 +1,209 @@
+import { describe, expect, test } from "vitest";
+import { createDocumentGraph } from "./graph";
+import { resolveAdaptedDocumentGraph } from "./document-resolution";
+
+const graph = createDocumentGraph({
+ nodes: [
+ { id: "post", revision: "post-r1", contentRef: "content:post" },
+ { id: "author", revision: "author-r1", contentRef: "content:author" },
+ { id: "avatar", revision: "avatar-r1", contentRef: "content:avatar" },
+ ],
+ edges: [
+ {
+ sourceId: "post",
+ referenceId: "#/author",
+ reference: {
+ documentId: "author",
+ revision: "author-r1",
+ representation: { type: "markdown-frontmatter" },
+ },
+ },
+ {
+ sourceId: "post",
+ referenceId: "#/bio",
+ reference: {
+ documentId: "author",
+ revision: "author-r1",
+ representation: { type: "markdown-body" },
+ },
+ },
+ {
+ sourceId: "author",
+ referenceId: "#frontmatter/avatar",
+ reference: {
+ documentId: "avatar",
+ revision: "avatar-r1",
+ representation: { type: "json", path: ["url"] },
+ },
+ },
+ ],
+});
+
+describe("adapted document graph resolution", () => {
+ test("parses once and assembles nested shared cross-format references", async () => {
+ const sources = new Map([
+ [
+ "content:post",
+ {
+ format: "json" as const,
+ revision: "post-r1",
+ source:
+ '{"title":"Hello","author":{"$ref":"./author.md#frontmatter"},"bio":{"$ref":"./author.md#body"}}',
+ },
+ ],
+ [
+ "content:author",
+ {
+ format: "markdown" as const,
+ revision: "author-r1",
+ source:
+ "---\nname: Ada\navatar:\n $ref: ./avatar.json#/url\n---\nWrites about the web.\n",
+ },
+ ],
+ [
+ "content:avatar",
+ {
+ format: "json" as const,
+ revision: "avatar-r1",
+ source: '{"url":"/ada.png"}',
+ },
+ ],
+ ]);
+ const loaded: string[] = [];
+
+ const result = await resolveAdaptedDocumentGraph({
+ graph,
+ rootIds: ["post"],
+ concurrency: 3,
+ load: async (node) => {
+ loaded.push(node.contentRef);
+ const source = sources.get(node.contentRef);
+ if (source === undefined) {
+ throw new Error("missing fixture source");
+ }
+ return source;
+ },
+ });
+
+ expect(loaded.sort()).toEqual([...sources.keys()].sort());
+ expect(result.roots).toEqual([
+ {
+ format: "json",
+ value: {
+ title: "Hello",
+ author: { name: "Ada", avatar: "/ada.png" },
+ bio: "Writes about the web.\n",
+ },
+ },
+ ]);
+ expect(result.values.get("author")).toMatchObject({
+ format: "markdown",
+ value: { frontmatter: { name: "Ada", avatar: "/ada.png" } },
+ });
+ });
+
+ test("applies the byte limit while loading document sources", async () => {
+ await expect(
+ resolveAdaptedDocumentGraph({
+ graph: createDocumentGraph({
+ nodes: [
+ { id: "post", revision: "post-r1", contentRef: "content:post" },
+ ],
+ edges: [],
+ }),
+ rootIds: ["post"],
+ concurrency: 1,
+ maximumBytes: 4,
+ load: async () => ({
+ format: "json",
+ revision: "post-r1",
+ source: '{"title":"Hello"}',
+ }),
+ })
+ ).rejects.toMatchObject({
+ code: "DOCUMENT_LOAD_FAILED",
+ documentId: "post",
+ cause: expect.objectContaining({ code: "CONTENT_LIMIT_EXCEEDED" }),
+ });
+ });
+
+ test("rejects a loaded revision before parsing stale document bytes", async () => {
+ await expect(
+ resolveAdaptedDocumentGraph({
+ graph: createDocumentGraph({
+ nodes: [
+ { id: "post", revision: "post-r1", contentRef: "content:post" },
+ ],
+ edges: [],
+ }),
+ rootIds: ["post"],
+ concurrency: 1,
+ load: async () => ({
+ format: "json",
+ revision: "stale-r1",
+ source: "not valid JSON",
+ }),
+ })
+ ).rejects.toMatchObject({
+ code: "DOCUMENT_LOAD_FAILED",
+ documentId: "post",
+ cause: expect.objectContaining({
+ code: "REVISION_MISMATCH",
+ expectedRevision: "post-r1",
+ actualRevision: "stale-r1",
+ }),
+ });
+ });
+
+ test("limits the reachable document count before loading", async () => {
+ const load = async () => ({
+ format: "json" as const,
+ revision: "unused",
+ source: "{}",
+ });
+
+ await expect(
+ resolveAdaptedDocumentGraph({
+ graph,
+ rootIds: ["post"],
+ concurrency: 3,
+ maximumDocuments: 2,
+ load,
+ })
+ ).rejects.toMatchObject({
+ code: "DOCUMENT_COUNT_EXCEEDED",
+ documentCount: 3,
+ documentLimit: 2,
+ });
+ });
+
+ test("limits aggregate source bytes before parsing", async () => {
+ await expect(
+ resolveAdaptedDocumentGraph({
+ graph: createDocumentGraph({
+ nodes: [
+ { id: "post", revision: "post-r1", contentRef: "content:post" },
+ ],
+ edges: [],
+ }),
+ rootIds: ["post"],
+ concurrency: 1,
+ maximumBytes: 10,
+ maximumTotalBytes: 2,
+ load: async () => ({
+ format: "json",
+ revision: "post-r1",
+ source: "{}\n",
+ }),
+ })
+ ).rejects.toMatchObject({
+ code: "DOCUMENT_LOAD_FAILED",
+ documentId: "post",
+ cause: expect.objectContaining({
+ code: "TOTAL_BYTES_EXCEEDED",
+ totalBytes: 3,
+ totalByteLimit: 2,
+ }),
+ });
+ });
+});
diff --git a/packages/content-engine/src/document-graph/document-resolution.ts b/packages/content-engine/src/document-graph/document-resolution.ts
new file mode 100644
index 0000000000..a2ffafbec4
--- /dev/null
+++ b/packages/content-engine/src/document-graph/document-resolution.ts
@@ -0,0 +1,185 @@
+import { ByteLimitExceededError, readBoundedBytes } from "../byte-stream";
+import { contentEngineLimits } from "../limits";
+import {
+ assembleDocument,
+ parseDocumentSource,
+ selectDocumentRepresentation,
+ type AdaptedDocument,
+} from "./document-adapter";
+import {
+ getDocumentGraphClosure,
+ type DocumentGraph,
+ type DocumentGraphNode,
+} from "./graph";
+import {
+ assertDocumentSourceIdentity,
+ type DocumentSource,
+} from "./document-source";
+import { resolveDocumentGraph, type ResolvedDocumentGraph } from "./resolver";
+import {
+ emitDocumentGraphRuntimeEvent,
+ getDocumentGraphErrorCode,
+ type DocumentGraphRuntimeObserver,
+} from "./observability";
+
+export type DocumentResolutionLimitErrorCode =
+ | "DOCUMENT_COUNT_EXCEEDED"
+ | "CONTENT_LIMIT_EXCEEDED"
+ | "TOTAL_BYTES_EXCEEDED";
+
+export class DocumentResolutionLimitError extends Error {
+ readonly code: DocumentResolutionLimitErrorCode;
+ readonly documentId?: string;
+ readonly documentCount?: number;
+ readonly documentLimit?: number;
+ readonly contentByteLimit?: number;
+ readonly totalBytes?: number;
+ readonly totalByteLimit?: number;
+
+ constructor({
+ code,
+ message,
+ documentId,
+ documentCount,
+ documentLimit,
+ contentByteLimit,
+ totalBytes,
+ totalByteLimit,
+ cause,
+ }: {
+ code: DocumentResolutionLimitErrorCode;
+ message: string;
+ documentId?: string;
+ documentCount?: number;
+ documentLimit?: number;
+ contentByteLimit?: number;
+ totalBytes?: number;
+ totalByteLimit?: number;
+ cause?: unknown;
+ }) {
+ super(message, { cause });
+ this.name = "DocumentResolutionLimitError";
+ this.code = code;
+ this.documentId = documentId;
+ this.documentCount = documentCount;
+ this.documentLimit = documentLimit;
+ this.contentByteLimit = contentByteLimit;
+ this.totalBytes = totalBytes;
+ this.totalByteLimit = totalByteLimit;
+ }
+}
+
+/** Resolves parsed JSON and Markdown values without depending on storage. */
+export const resolveAdaptedDocumentGraph = async ({
+ graph,
+ rootIds,
+ concurrency,
+ maximumBytes = contentEngineLimits.hydratedFileBytes,
+ maximumTotalBytes = contentEngineLimits.hydratedTotalBytes,
+ maximumDocuments = contentEngineLimits.hydratedFileCount,
+ signal,
+ load,
+ onEvent,
+ allowUnresolvedReferences = false,
+}: {
+ graph: DocumentGraph;
+ rootIds: readonly string[];
+ concurrency: number;
+ maximumBytes?: number;
+ maximumTotalBytes?: number;
+ maximumDocuments?: number;
+ signal?: AbortSignal;
+ load: (
+ node: DocumentGraphNode,
+ options: { signal?: AbortSignal }
+ ) => Promise<DocumentSource>;
+ onEvent?: DocumentGraphRuntimeObserver;
+ allowUnresolvedReferences?: boolean;
+}): Promise<ResolvedDocumentGraph<AdaptedDocument>> => {
+ const documentCount = getDocumentGraphClosure({ graph, rootIds }).length;
+ const resolutionEvent = { rootCount: rootIds.length, documentCount };
+ emitDocumentGraphRuntimeEvent(onEvent, {
+ type: "resolution-started",
+ ...resolutionEvent,
+ });
+ try {
+ if (documentCount > maximumDocuments) {
+ throw new DocumentResolutionLimitError({
+ code: "DOCUMENT_COUNT_EXCEEDED",
+ message: "Document graph resolution exceeds the document limit",
+ documentCount,
+ documentLimit: maximumDocuments,
+ });
+ }
+ let totalBytes = 0;
+ const resolved = await resolveDocumentGraph<
+ AdaptedDocument,
+ AdaptedDocument
+ >({
+ graph,
+ rootIds,
+ concurrency,
+ signal,
+ load: async (node, options) => {
+ const loaded = assertDocumentSourceIdentity({
+ node,
+ source: await load(node, options),
+ });
+ let bytes: Uint8Array;
+ try {
+ bytes = await readBoundedBytes(loaded.source, maximumBytes);
+ } catch (cause) {
+ if (cause instanceof ByteLimitExceededError) {
+ throw new DocumentResolutionLimitError({
+ code: "CONTENT_LIMIT_EXCEEDED",
+ message: `Document ${node.id} exceeds the byte limit`,
+ documentId: node.id,
+ contentByteLimit: maximumBytes,
+ cause,
+ });
+ }
+ throw cause;
+ }
+ const nextTotalBytes = totalBytes + bytes.byteLength;
+ if (nextTotalBytes > maximumTotalBytes) {
+ throw new DocumentResolutionLimitError({
+ code: "TOTAL_BYTES_EXCEEDED",
+ message: "Document graph resolution exceeds the total byte limit",
+ documentId: node.id,
+ totalBytes: nextTotalBytes,
+ totalByteLimit: maximumTotalBytes,
+ });
+ }
+ totalBytes = nextTotalBytes;
+ return await parseDocumentSource({
+ format: loaded.format,
+ source: bytes,
+ maximumBytes,
+ });
+ },
+ select: ({ reference, value }) =>
+ selectDocumentRepresentation({
+ document: value,
+ representation: reference.representation,
+ }),
+ assemble: ({ source, references }) =>
+ assembleDocument({
+ document: source,
+ references,
+ allowUnresolvedReferences,
+ }),
+ });
+ emitDocumentGraphRuntimeEvent(onEvent, {
+ type: "resolution-completed",
+ ...resolutionEvent,
+ });
+ return resolved;
+ } catch (error) {
+ emitDocumentGraphRuntimeEvent(onEvent, {
+ type: "resolution-failed",
+ ...resolutionEvent,
+ errorCode: getDocumentGraphErrorCode(error),
+ });
+ throw error;
+ }
+};
diff --git a/packages/content-engine/src/document-graph/document-source.test.ts b/packages/content-engine/src/document-graph/document-source.test.ts
new file mode 100644
index 0000000000..d3e674234f
--- /dev/null
+++ b/packages/content-engine/src/document-graph/document-source.test.ts
@@ -0,0 +1,46 @@
+import { describe, expect, test } from "vitest";
+import { assertDocumentSourceIdentity } from "./document-source";
+
+describe("document source", () => {
+ test("accepts matching revisions and reports stale source identity", () => {
+ const node = {
+ id: "post",
+ revision: "post-r1",
+ contentRef: "content:post",
+ format: "json" as const,
+ };
+ const source = {
+ format: "json" as const,
+ revision: "post-r1",
+ source: '{"title":"Hello"}',
+ };
+
+ expect(assertDocumentSourceIdentity({ node, source })).toBe(source);
+ expect(() =>
+ assertDocumentSourceIdentity({
+ node,
+ source: { ...source, revision: "stale-r1" },
+ })
+ ).toThrowError(
+ expect.objectContaining({
+ code: "REVISION_MISMATCH",
+ documentId: "post",
+ expectedRevision: "post-r1",
+ actualRevision: "stale-r1",
+ })
+ );
+ expect(() =>
+ assertDocumentSourceIdentity({
+ node,
+ source: { ...source, format: "markdown" },
+ })
+ ).toThrowError(
+ expect.objectContaining({
+ code: "FORMAT_MISMATCH",
+ documentId: "post",
+ expectedFormat: "json",
+ actualFormat: "markdown",
+ })
+ );
+ });
+});
diff --git a/packages/content-engine/src/document-graph/document-source.ts b/packages/content-engine/src/document-graph/document-source.ts
new file mode 100644
index 0000000000..053d011d79
--- /dev/null
+++ b/packages/content-engine/src/document-graph/document-source.ts
@@ -0,0 +1,77 @@
+import type { ByteSource } from "../byte-stream";
+import type { DocumentFormat } from "./document-adapter";
+import type { DocumentGraphNode } from "./graph";
+
+export type DocumentSource = Readonly<{
+ format: DocumentFormat;
+ revision: string;
+ source: ByteSource;
+}>;
+
+export type DocumentSourceLoader = (
+ node: DocumentGraphNode,
+ options: { signal?: AbortSignal }
+) => Promise<DocumentSource>;
+
+export class DocumentSourceError extends Error {
+ readonly code: "REVISION_MISMATCH" | "FORMAT_MISMATCH";
+ readonly documentId: string;
+ readonly expectedRevision?: string;
+ readonly actualRevision?: string;
+ readonly expectedFormat?: DocumentFormat;
+ readonly actualFormat?: DocumentFormat;
+
+ constructor({
+ code,
+ documentId,
+ expectedRevision,
+ actualRevision,
+ expectedFormat,
+ actualFormat,
+ }: {
+ code: "REVISION_MISMATCH" | "FORMAT_MISMATCH";
+ documentId: string;
+ expectedRevision?: string;
+ actualRevision?: string;
+ expectedFormat?: DocumentFormat;
+ actualFormat?: DocumentFormat;
+ }) {
+ super(
+ `Document ${documentId} source ${code === "REVISION_MISMATCH" ? "revision" : "format"} does not match its graph`
+ );
+ this.name = "DocumentSourceError";
+ this.code = code;
+ this.documentId = documentId;
+ this.expectedRevision = expectedRevision;
+ this.actualRevision = actualRevision;
+ this.expectedFormat = expectedFormat;
+ this.actualFormat = actualFormat;
+ }
+}
+
+/** Prevents graph metadata and a loaded source with another identity from mixing. */
+export const assertDocumentSourceIdentity = ({
+ node,
+ source,
+}: {
+ node: DocumentGraphNode;
+ source: DocumentSource;
+}) => {
+ if (source.revision !== node.revision) {
+ throw new DocumentSourceError({
+ code: "REVISION_MISMATCH",
+ documentId: node.id,
+ expectedRevision: node.revision,
+ actualRevision: source.revision,
+ });
+ }
+ if (node.format !== undefined && source.format !== node.format) {
+ throw new DocumentSourceError({
+ code: "FORMAT_MISMATCH",
+ documentId: node.id,
+ expectedFormat: node.format,
+ actualFormat: source.format,
+ });
+ }
+ return source;
+};
diff --git a/packages/content-engine/src/document-graph/document-utils.ts b/packages/content-engine/src/document-graph/document-utils.ts
new file mode 100644
index 0000000000..07476eff4a
--- /dev/null
+++ b/packages/content-engine/src/document-graph/document-utils.ts
@@ -0,0 +1,20 @@
+import type { JsonValue } from "../canonical-json";
+
+export const isJsonObject = (
+ value: JsonValue
+): value is { readonly [key: string]: JsonValue } =>
+ typeof value === "object" && value !== null && Array.isArray(value) === false;
+
+/** Returns the value from an exact JSON `{ $ref }` marker. */
+export const getJsonReferenceMarkerValue = (
+ value: JsonValue
+): JsonValue | undefined => {
+ if (isJsonObject(value) === false) {
+ return;
+ }
+ const keys = Object.keys(value);
+ if (keys.length !== 1 || keys[0] !== "$ref") {
+ return;
+ }
+ return value.$ref;
+};
diff --git a/packages/content-engine/src/document-graph/graph-artifact.test.ts b/packages/content-engine/src/document-graph/graph-artifact.test.ts
new file mode 100644
index 0000000000..06604c84a0
--- /dev/null
+++ b/packages/content-engine/src/document-graph/graph-artifact.test.ts
@@ -0,0 +1,113 @@
+import { describe, expect, test } from "vitest";
+import { serializeJsonDeterministically, sha256 } from "../canonical-json";
+import { createDocumentGraph } from "./graph";
+import {
+ createDocumentGraphArtifact,
+ DocumentGraphArtifactError,
+ parseDocumentGraphArtifact,
+ serializeDocumentGraphArtifact,
+ verifyDocumentGraphArtifact,
+} from "./graph-artifact";
+
+const createFixtureGraph = (reverse = false) =>
+ createDocumentGraph({
+ nodes: reverse
+ ? [
+ { id: "author", revision: "author-r1", contentRef: "content:author" },
+ { id: "post", revision: "post-r1", contentRef: "content:post" },
+ ]
+ : [
+ { id: "post", revision: "post-r1", contentRef: "content:post" },
+ { id: "author", revision: "author-r1", contentRef: "content:author" },
+ ],
+ edges: [
+ {
+ sourceId: "post",
+ referenceId: "#/author",
+ reference: {
+ documentId: "author",
+ revision: "author-r1",
+ representation: { type: "json", path: ["name"] },
+ },
+ },
+ ],
+ });
+
+describe("document graph artifact", () => {
+ test("creates and serializes a deterministic versioned artifact", async () => {
+ const artifact = await createDocumentGraphArtifact(createFixtureGraph());
+
+ expect(artifact).toMatchObject({
+ format: "webstudio-document-graph",
+ version: 1,
+ nodes: [
+ { id: "author", revision: "author-r1", contentRef: "content:author" },
+ { id: "post", revision: "post-r1", contentRef: "content:post" },
+ ],
+ integrity: {
+ algorithm: "sha256",
+ checksum: expect.stringMatching(/^sha256:[a-f0-9]{64}$/),
+ },
+ });
+ const equivalent = await createDocumentGraphArtifact(
+ createFixtureGraph(true)
+ );
+ expect(equivalent).toEqual(artifact);
+ expect(serializeDocumentGraphArtifact(equivalent)).toBe(
+ serializeDocumentGraphArtifact(artifact)
+ );
+ });
+
+ test("parses and verifies an artifact into an immutable graph", async () => {
+ const artifact = await createDocumentGraphArtifact(createFixtureGraph());
+ const verified = await parseDocumentGraphArtifact(
+ serializeDocumentGraphArtifact(artifact)
+ );
+
+ expect(verified.artifact).toEqual(artifact);
+ expect(verified.graph).toEqual(createFixtureGraph());
+ expect(Object.isFrozen(verified.artifact)).toBe(true);
+ expect(Object.isFrozen(verified.graph)).toBe(true);
+ });
+
+ test("rejects payload tampering", async () => {
+ const artifact = await createDocumentGraphArtifact(createFixtureGraph());
+
+ await expect(
+ verifyDocumentGraphArtifact({
+ ...artifact,
+ nodes: artifact.nodes.map((node) =>
+ node.id === "author" ? { ...node, revision: "tampered" } : node
+ ),
+ })
+ ).rejects.toMatchObject({ code: "CHECKSUM_MISMATCH" });
+ });
+
+ test("rejects noncanonical graph ordering even with a matching checksum", async () => {
+ const artifact = await createDocumentGraphArtifact(createFixtureGraph());
+ const payload = {
+ format: artifact.format,
+ version: artifact.version,
+ nodes: [...artifact.nodes].reverse(),
+ edges: artifact.edges,
+ };
+ const checksum = await sha256(serializeJsonDeterministically(payload));
+
+ await expect(
+ verifyDocumentGraphArtifact({
+ ...payload,
+ integrity: { algorithm: "sha256", checksum },
+ })
+ ).rejects.toMatchObject({ code: "NON_CANONICAL_GRAPH" });
+ });
+
+ test("rejects invalid JSON and unknown artifact fields", async () => {
+ await expect(parseDocumentGraphArtifact("not json")).rejects.toMatchObject({
+ code: "INVALID_ARTIFACT",
+ } satisfies Partial<DocumentGraphArtifactError>);
+ const artifact = await createDocumentGraphArtifact(createFixtureGraph());
+ await expect(
+ verifyDocumentGraphArtifact({ ...artifact, unknown: true })
+ ).rejects.toMatchObject({ code: "INVALID_ARTIFACT" });
+ });
+});
diff --git a/packages/content-engine/src/document-graph/graph-artifact.ts b/packages/content-engine/src/document-graph/graph-artifact.ts
new file mode 100644
index 0000000000..62dd09e1c1
--- /dev/null
+++ b/packages/content-engine/src/document-graph/graph-artifact.ts
@@ -0,0 +1,192 @@
+import { array, literal, strictObject, string } from "zod";
+import { serializeJsonDeterministically, sha256 } from "../canonical-json";
+import {
+ createDocumentGraph,
+ type DocumentGraph,
+ type DocumentGraphEdge,
+ type DocumentGraphNode,
+} from "./graph";
+import {
+ documentGraphEdgeSchema,
+ documentGraphNodeSchema,
+} from "./graph-schema";
+
+const sha256Revision = string().regex(/^sha256:[a-f0-9]{64}$/);
+
+export const documentGraphArtifactV1 = strictObject({
+ format: literal("webstudio-document-graph"),
+ version: literal(1),
+ nodes: array(documentGraphNodeSchema),
+ edges: array(documentGraphEdgeSchema),
+ integrity: strictObject({
+ algorithm: literal("sha256"),
+ checksum: sha256Revision,
+ }),
+});
+
+export type DocumentGraphArtifactV1 = Readonly<{
+ format: "webstudio-document-graph";
+ version: 1;
+ nodes: readonly DocumentGraphNode[];
+ edges: readonly DocumentGraphEdge[];
+ integrity: Readonly<{
+ algorithm: "sha256";
+ checksum: string;
+ }>;
+}>;
+
+export type DocumentGraphArtifactErrorCode =
+ | "INVALID_ARTIFACT"
+ | "CHECKSUM_MISMATCH"
+ | "NON_CANONICAL_GRAPH";
+
+export class DocumentGraphArtifactError extends Error {
+ readonly code: DocumentGraphArtifactErrorCode;
+
+ constructor({
+ code,
+ message,
+ cause,
+ }: {
+ code: DocumentGraphArtifactErrorCode;
+ message: string;
+ cause?: unknown;
+ }) {
+ super(message, { cause });
+ this.name = "DocumentGraphArtifactError";
+ this.code = code;
+ }
+}
+
+export type VerifiedDocumentGraphArtifact = Readonly<{
+ artifact: DocumentGraphArtifactV1;
+ graph: DocumentGraph;
+}>;
+
+const getArtifactPayload = (
+ artifact: Pick<
+ DocumentGraphArtifactV1,
+ "format" | "version" | "nodes" | "edges"
+ >
+) => ({
+ format: artifact.format,
+ version: artifact.version,
+ nodes: artifact.nodes,
+ edges: artifact.edges,
+});
+
+const checksumArtifactPayload = async (
+ artifact: Pick<
+ DocumentGraphArtifactV1,
+ "format" | "version" | "nodes" | "edges"
+ >
+) => await sha256(serializeJsonDeterministically(getArtifactPayload(artifact)));
+
+const parseArtifactShape = (input: unknown) => {
+ try {
+ return documentGraphArtifactV1.parse(input);
+ } catch (cause) {
+ throw new DocumentGraphArtifactError({
+ code: "INVALID_ARTIFACT",
+ message: "Document graph artifact is invalid",
+ cause,
+ });
+ }
+};
+
+const getCanonicalGraph = ({
+ nodes,
+ edges,
+}: Pick<DocumentGraphArtifactV1, "nodes" | "edges">) => {
+ let graph: DocumentGraph;
+ try {
+ graph = createDocumentGraph({ nodes, edges });
+ } catch (cause) {
+ throw new DocumentGraphArtifactError({
+ code: "INVALID_ARTIFACT",
+ message: "Document graph artifact contains an invalid graph",
+ cause,
+ });
+ }
+ if (
+ serializeJsonDeterministically({ nodes, edges }) !==
+ serializeJsonDeterministically({ nodes: graph.nodes, edges: graph.edges })
+ ) {
+ throw new DocumentGraphArtifactError({
+ code: "NON_CANONICAL_GRAPH",
+ message: "Document graph artifact nodes and edges must be canonical",
+ });
+ }
+ return graph;
+};
+
+const freezeArtifact = ({
+ graph,
+ checksum,
+}: {
+ graph: DocumentGraph;
+ checksum: string;
+}): DocumentGraphArtifactV1 =>
+ Object.freeze({
+ format: "webstudio-document-graph",
+ version: 1,
+ nodes: graph.nodes,
+ edges: graph.edges,
+ integrity: Object.freeze({ algorithm: "sha256", checksum }),
+ });
+
+export const createDocumentGraphArtifact = async (
+ input: DocumentGraph
+): Promise<DocumentGraphArtifactV1> => {
+ const graph = createDocumentGraph({ nodes: input.nodes, edges: input.edges });
+ const payload = {
+ format: "webstudio-document-graph" as const,
+ version: 1 as const,
+ nodes: graph.nodes,
+ edges: graph.edges,
+ };
+ return freezeArtifact({
+ graph,
+ checksum: await checksumArtifactPayload(payload),
+ });
+};
+
+export const serializeDocumentGraphArtifact = (input: unknown) => {
+ const artifact = parseArtifactShape(input);
+ getCanonicalGraph(artifact);
+ return serializeJsonDeterministically(artifact);
+};
+
+export const verifyDocumentGraphArtifact = async (
+ input: unknown
+): Promise<VerifiedDocumentGraphArtifact> => {
+ const parsed = parseArtifactShape(input);
+ if (parsed.integrity.checksum !== (await checksumArtifactPayload(parsed))) {
+ throw new DocumentGraphArtifactError({
+ code: "CHECKSUM_MISMATCH",
+ message: "Document graph artifact checksum does not match its payload",
+ });
+ }
+ const graph = getCanonicalGraph(parsed);
+ const artifact = freezeArtifact({
+ graph,
+ checksum: parsed.integrity.checksum,
+ });
+ return Object.freeze({ artifact, graph });
+};
+
+export const parseDocumentGraphArtifact = async (
+ source: string
+): Promise<VerifiedDocumentGraphArtifact> => {
+ let input: unknown;
+ try {
+ input = JSON.parse(source);
+ } catch (cause) {
+ throw new DocumentGraphArtifactError({
+ code: "INVALID_ARTIFACT",
+ message: "Document graph artifact is not valid JSON",
+ cause,
+ });
+ }
+ return await verifyDocumentGraphArtifact(input);
+};
diff --git a/packages/content-engine/src/document-graph/graph-schema.ts b/packages/content-engine/src/document-graph/graph-schema.ts
new file mode 100644
index 0000000000..1308bf2d2e
--- /dev/null
+++ b/packages/content-engine/src/document-graph/graph-schema.ts
@@ -0,0 +1,15 @@
+import { enum as zEnum, strictObject, string } from "zod";
+import { documentReference } from "./reference";
+
+export const documentGraphNodeSchema = strictObject({
+ id: string().min(1),
+ revision: string().min(1),
+ contentRef: string().min(1),
+ format: zEnum(["json", "markdown"]).optional(),
+});
+
+export const documentGraphEdgeSchema = strictObject({
+ sourceId: string().min(1),
+ referenceId: string().min(1),
+ reference: documentReference,
+});
diff --git a/packages/content-engine/src/document-graph/graph-utils.ts b/packages/content-engine/src/document-graph/graph-utils.ts
new file mode 100644
index 0000000000..390cb8bc29
--- /dev/null
+++ b/packages/content-engine/src/document-graph/graph-utils.ts
@@ -0,0 +1,13 @@
+import type { DocumentGraphEdge } from "./graph";
+
+export const getDocumentGraphEdgesBySourceId = (
+ edges: readonly DocumentGraphEdge[]
+) => {
+ const result = new Map<string, DocumentGraphEdge[]>();
+ for (const edge of edges) {
+ const sourceEdges = result.get(edge.sourceId) ?? [];
+ sourceEdges.push(edge);
+ result.set(edge.sourceId, sourceEdges);
+ }
+ return result;
+};
diff --git a/packages/content-engine/src/document-graph/graph.test.ts b/packages/content-engine/src/document-graph/graph.test.ts
new file mode 100644
index 0000000000..41cb94e8a3
--- /dev/null
+++ b/packages/content-engine/src/document-graph/graph.test.ts
@@ -0,0 +1,160 @@
+import { describe, expect, test } from "vitest";
+import {
+ createDocumentGraph,
+ DocumentGraphError,
+ getDocumentGraphClosure,
+ getDocumentGraphDependencies,
+} from "./graph";
+
+const nodes = [
+ { id: "post", revision: "post-r1", contentRef: "content:post" },
+ { id: "author", revision: "author-r1", contentRef: "content:author" },
+ { id: "avatar", revision: "avatar-r1", contentRef: "content:avatar" },
+];
+
+const edges = [
+ {
+ sourceId: "post",
+ referenceId: "author",
+ reference: {
+ documentId: "author",
+ revision: "author-r1",
+ representation: { type: "document" as const },
+ },
+ },
+ {
+ sourceId: "author",
+ referenceId: "avatar",
+ reference: {
+ documentId: "avatar",
+ revision: "avatar-r1",
+ representation: { type: "document" as const },
+ },
+ },
+];
+
+describe("document graph", () => {
+ test("rejects conflicting revisions for one content reference", () => {
+ expect(() =>
+ createDocumentGraph({
+ nodes: [
+ {
+ id: "first",
+ revision: "first-r1",
+ contentRef: "content:shared",
+ format: "json",
+ },
+ {
+ id: "second",
+ revision: "second-r1",
+ contentRef: "content:shared",
+ format: "json",
+ },
+ ],
+ edges: [],
+ })
+ ).toThrowError(
+ expect.objectContaining({ code: "CONTENT_IDENTITY_CONFLICT" })
+ );
+ });
+
+ test("normalizes nodes and edges deterministically", () => {
+ const graph = createDocumentGraph({
+ nodes: [...nodes].reverse(),
+ edges: [...edges].reverse(),
+ });
+
+ expect(graph.nodes.map(({ id }) => id)).toEqual([
+ "author",
+ "avatar",
+ "post",
+ ]);
+ expect(
+ graph.edges.map(({ sourceId, referenceId }) => [sourceId, referenceId])
+ ).toEqual([
+ ["author", "avatar"],
+ ["post", "author"],
+ ]);
+ expect(Object.isFrozen(graph)).toBe(true);
+ expect(Object.isFrozen(graph.nodes)).toBe(true);
+ expect(Object.isFrozen(graph.edges)).toBe(true);
+ });
+
+ test("returns direct dependencies and a dependency-first closure", () => {
+ const graph = createDocumentGraph({ nodes, edges });
+
+ expect(
+ getDocumentGraphDependencies(graph, "post").map(({ id }) => id)
+ ).toEqual(["author"]);
+ expect(
+ getDocumentGraphClosure({ graph, rootIds: ["post"] }).map(({ id }) => id)
+ ).toEqual(["avatar", "author", "post"]);
+ });
+
+ test("rejects missing nodes, stale revisions, and duplicate reference IDs", () => {
+ expect(() =>
+ createDocumentGraph({
+ nodes,
+ edges: [{ ...edges[0], sourceId: "missing" }],
+ })
+ ).toThrowError(DocumentGraphError);
+ expect(() =>
+ createDocumentGraph({
+ nodes,
+ edges: [
+ {
+ ...edges[0],
+ reference: { ...edges[0].reference, revision: "author-r0" },
+ },
+ ],
+ })
+ ).toThrow("revision");
+ expect(() =>
+ createDocumentGraph({ nodes, edges: [edges[0], edges[0]] })
+ ).toThrow("reference ID");
+ });
+
+ test("rejects conflicting formats for one shared content reference", () => {
+ expect(() =>
+ createDocumentGraph({
+ nodes: [
+ {
+ id: "first",
+ revision: "r1",
+ contentRef: "shared",
+ format: "json",
+ },
+ {
+ id: "second",
+ revision: "r1",
+ contentRef: "shared",
+ format: "markdown",
+ },
+ ],
+ edges: [],
+ })
+ ).toThrow("content reference");
+ });
+
+ test("reports the reachable cycle", () => {
+ const graph = createDocumentGraph({
+ nodes,
+ edges: [
+ ...edges,
+ {
+ sourceId: "avatar",
+ referenceId: "post",
+ reference: {
+ documentId: "post",
+ revision: "post-r1",
+ representation: { type: "document" },
+ },
+ },
+ ],
+ });
+
+ expect(() => getDocumentGraphClosure({ graph, rootIds: ["post"] })).toThrow(
+ "post -> author -> avatar -> post"
+ );
+ });
+});
diff --git a/packages/content-engine/src/document-graph/graph.ts b/packages/content-engine/src/document-graph/graph.ts
new file mode 100644
index 0000000000..65c63b0a77
--- /dev/null
+++ b/packages/content-engine/src/document-graph/graph.ts
@@ -0,0 +1,225 @@
+import { compareStrings } from "../canonical-json";
+import { createDocumentReference, type DocumentReference } from "./reference";
+import {
+ documentGraphEdgeSchema,
+ documentGraphNodeSchema,
+} from "./graph-schema";
+import { getDocumentGraphEdgesBySourceId } from "./graph-utils";
+
+export type DocumentGraphNode = Readonly<{
+ id: string;
+ revision: string;
+ contentRef: string;
+ format?: "json" | "markdown";
+}>;
+
+export type DocumentGraphEdge = Readonly<{
+ sourceId: string;
+ referenceId: string;
+ reference: DocumentReference;
+}>;
+
+export type DocumentGraph = Readonly<{
+ nodes: readonly DocumentGraphNode[];
+ edges: readonly DocumentGraphEdge[];
+}>;
+
+export type DocumentGraphErrorCode =
+ | "DUPLICATE_NODE"
+ | "CONTENT_IDENTITY_CONFLICT"
+ | "DUPLICATE_REFERENCE"
+ | "SOURCE_NOT_FOUND"
+ | "TARGET_NOT_FOUND"
+ | "TARGET_REVISION_MISMATCH"
+ | "ROOT_NOT_FOUND"
+ | "CYCLE";
+
+export class DocumentGraphError extends Error {
+ readonly code: DocumentGraphErrorCode;
+ readonly documentIds: readonly string[];
+
+ constructor({
+ code,
+ message,
+ documentIds = [],
+ }: {
+ code: DocumentGraphErrorCode;
+ message: string;
+ documentIds?: readonly string[];
+ }) {
+ super(message);
+ this.name = "DocumentGraphError";
+ this.code = code;
+ this.documentIds = Object.freeze([...documentIds]);
+ }
+}
+
+const compareEdges = (left: DocumentGraphEdge, right: DocumentGraphEdge) =>
+ compareStrings(left.sourceId, right.sourceId) ||
+ compareStrings(left.referenceId, right.referenceId);
+
+export const createDocumentGraph = ({
+ nodes: nodeInputs,
+ edges: edgeInputs,
+}: {
+ nodes: readonly unknown[];
+ edges: readonly unknown[];
+}): DocumentGraph => {
+ const nodes = nodeInputs
+ .map((input) => Object.freeze(documentGraphNodeSchema.parse(input)))
+ .sort((left, right) => compareStrings(left.id, right.id));
+ const nodesById = new Map<string, DocumentGraphNode>();
+ const nodesByContentRef = new Map<string, DocumentGraphNode>();
+ for (const node of nodes) {
+ if (nodesById.has(node.id)) {
+ throw new DocumentGraphError({
+ code: "DUPLICATE_NODE",
+ message: `Document graph contains duplicate node ${node.id}`,
+ documentIds: [node.id],
+ });
+ }
+ nodesById.set(node.id, node);
+ const previousContent = nodesByContentRef.get(node.contentRef);
+ if (
+ previousContent !== undefined &&
+ (previousContent.revision !== node.revision ||
+ previousContent.format !== node.format)
+ ) {
+ throw new DocumentGraphError({
+ code: "CONTENT_IDENTITY_CONFLICT",
+ message: `Document graph content reference ${node.contentRef} has conflicting identities`,
+ documentIds: [previousContent.id, node.id],
+ });
+ }
+ nodesByContentRef.set(node.contentRef, node);
+ }
+
+ const edges = edgeInputs
+ .map((input) => {
+ const edge = documentGraphEdgeSchema.parse(input);
+ return Object.freeze({
+ ...edge,
+ reference: createDocumentReference(edge.reference),
+ });
+ })
+ .sort(compareEdges);
+ const referenceKeys = new Set<string>();
+ for (const edge of edges) {
+ const source = nodesById.get(edge.sourceId);
+ if (source === undefined) {
+ throw new DocumentGraphError({
+ code: "SOURCE_NOT_FOUND",
+ message: `Document graph source ${edge.sourceId} does not exist`,
+ documentIds: [edge.sourceId],
+ });
+ }
+ const target = nodesById.get(edge.reference.documentId);
+ if (target === undefined) {
+ throw new DocumentGraphError({
+ code: "TARGET_NOT_FOUND",
+ message: `Document graph target ${edge.reference.documentId} does not exist`,
+ documentIds: [edge.sourceId, edge.reference.documentId],
+ });
+ }
+ if (target.revision !== edge.reference.revision) {
+ throw new DocumentGraphError({
+ code: "TARGET_REVISION_MISMATCH",
+ message: `Document graph target ${target.id} revision does not match its reference`,
+ documentIds: [edge.sourceId, target.id],
+ });
+ }
+ const referenceKey = `${edge.sourceId}\0${edge.referenceId}`;
+ if (referenceKeys.has(referenceKey)) {
+ throw new DocumentGraphError({
+ code: "DUPLICATE_REFERENCE",
+ message: `Document ${edge.sourceId} contains duplicate reference ID ${edge.referenceId}`,
+ documentIds: [edge.sourceId],
+ });
+ }
+ referenceKeys.add(referenceKey);
+ }
+
+ return Object.freeze({
+ nodes: Object.freeze(nodes),
+ edges: Object.freeze(edges),
+ });
+};
+
+const getNodesById = (graph: DocumentGraph) =>
+ new Map(graph.nodes.map((node) => [node.id, node]));
+
+export const getDocumentGraphDependencies = (
+ graph: DocumentGraph,
+ documentId: string
+): readonly DocumentGraphNode[] => {
+ const nodesById = getNodesById(graph);
+ if (nodesById.has(documentId) === false) {
+ throw new DocumentGraphError({
+ code: "ROOT_NOT_FOUND",
+ message: `Document graph node ${documentId} does not exist`,
+ documentIds: [documentId],
+ });
+ }
+ const dependencies = new Map<string, DocumentGraphNode>();
+ for (const edge of graph.edges) {
+ if (edge.sourceId === documentId) {
+ const target = nodesById.get(edge.reference.documentId);
+ if (target !== undefined) {
+ dependencies.set(target.id, target);
+ }
+ }
+ }
+ return Object.freeze([...dependencies.values()]);
+};
+
+/** Returns each reachable node once, with dependencies before their consumers. */
+export const getDocumentGraphClosure = ({
+ graph,
+ rootIds,
+}: {
+ graph: DocumentGraph;
+ rootIds: readonly string[];
+}): readonly DocumentGraphNode[] => {
+ const nodesById = getNodesById(graph);
+ const edgesBySourceId = getDocumentGraphEdgesBySourceId(graph.edges);
+ const state = new Map<string, "visiting" | "visited">();
+ const stack: string[] = [];
+ const ordered: DocumentGraphNode[] = [];
+
+ const visit = (documentId: string) => {
+ const node = nodesById.get(documentId);
+ if (node === undefined) {
+ throw new DocumentGraphError({
+ code: "ROOT_NOT_FOUND",
+ message: `Document graph root ${documentId} does not exist`,
+ documentIds: [documentId],
+ });
+ }
+ const nodeState = state.get(documentId);
+ if (nodeState === "visited") {
+ return;
+ }
+ if (nodeState === "visiting") {
+ const cycleStart = stack.indexOf(documentId);
+ const cycle = [...stack.slice(cycleStart), documentId];
+ throw new DocumentGraphError({
+ code: "CYCLE",
+ message: `Document graph contains a cycle: ${cycle.join(" -> ")}`,
+ documentIds: cycle,
+ });
+ }
+ state.set(documentId, "visiting");
+ stack.push(documentId);
+ for (const edge of edgesBySourceId.get(documentId) ?? []) {
+ visit(edge.reference.documentId);
+ }
+ stack.pop();
+ state.set(documentId, "visited");
+ ordered.push(node);
+ };
+
+ for (const rootId of [...new Set(rootIds)].sort(compareStrings)) {
+ visit(rootId);
+ }
+ return Object.freeze(ordered);
+};
diff --git a/packages/content-engine/src/document-graph/http-document-loader.test.ts b/packages/content-engine/src/document-graph/http-document-loader.test.ts
new file mode 100644
index 0000000000..3691fea9f6
--- /dev/null
+++ b/packages/content-engine/src/document-graph/http-document-loader.test.ts
@@ -0,0 +1,134 @@
+import { describe, expect, test, vi } from "vitest";
+import { parseDocumentSource } from "./document-adapter";
+import { createHttpDocumentSourceLoader } from "./http-document-loader";
+
+const node = {
+ id: "post",
+ revision: "post-r1",
+ contentRef: "content:post",
+};
+
+describe("HTTP document loader", () => {
+ test("streams a successful response through injected request and metadata mappings", async () => {
+ const request = new Request("https://cdn.webstudio.test/post.json");
+ const fetch = vi.fn(async () =>
+ Promise.resolve(
+ new Response('{"title":"Hello"}', {
+ headers: { "x-content-revision": "post-r1" },
+ })
+ )
+ );
+ const load = createHttpDocumentSourceLoader({
+ fetch,
+ getRequest: () => request,
+ getMetadata: ({ response }) => ({
+ format: "json",
+ revision: response.headers.get("x-content-revision"),
+ }),
+ });
+
+ const loaded = await load(node, {});
+ expect(fetch).toHaveBeenCalledWith(request, { signal: undefined });
+ expect(loaded).toMatchObject({ format: "json", revision: "post-r1" });
+ await expect(parseDocumentSource(loaded)).resolves.toEqual({
+ format: "json",
+ value: { title: "Hello" },
+ });
+ });
+
+ test("reports non-success responses without consuming their body", async () => {
+ let bodyRead = false;
+ const response = {
+ ok: false,
+ status: 503,
+ get body() {
+ bodyRead = true;
+ return new Response("private details").body;
+ },
+ } as Response;
+ const load = createHttpDocumentSourceLoader({
+ fetch: async () => response,
+ getRequest: () => "https://cdn.webstudio.test/post.json",
+ getMetadata: () => ({ format: "json", revision: "post-r1" }),
+ });
+
+ await expect(load(node, {})).rejects.toMatchObject({
+ code: "HTTP_STATUS",
+ documentId: "post",
+ status: 503,
+ });
+ expect(bodyRead).toBe(false);
+ });
+
+ test("wraps invalid response metadata and forwards cancellation", async () => {
+ const controller = new AbortController();
+ const fetch = vi.fn(async () => new Response("{}"));
+ const load = createHttpDocumentSourceLoader({
+ fetch,
+ getRequest: () => "https://cdn.webstudio.test/post.json",
+ getMetadata: () => ({ format: "json", revision: undefined }),
+ });
+
+ await expect(
+ load(node, { signal: controller.signal })
+ ).rejects.toMatchObject({
+ code: "INVALID_METADATA",
+ documentId: "post",
+ });
+ expect(fetch).toHaveBeenCalledWith("https://cdn.webstudio.test/post.json", {
+ signal: controller.signal,
+ });
+ });
+
+ test("reports document fetch completion and sanitized failures", async () => {
+ const events: unknown[] = [];
+ const load = createHttpDocumentSourceLoader({
+ fetch: async () => new Response("{}"),
+ getRequest: () =>
+ "https://cdn.webstudio.test/private-path.json?token=secret",
+ getMetadata: () => ({ format: "json", revision: "post-r1" }),
+ onEvent: (event) => events.push(event),
+ });
+
+ await load(node, {});
+ expect(events).toEqual([
+ {
+ type: "document-fetch-started",
+ documentId: "post",
+ revision: "post-r1",
+ },
+ {
+ type: "document-fetch-completed",
+ documentId: "post",
+ revision: "post-r1",
+ },
+ ]);
+
+ const failedEvents: unknown[] = [];
+ const failedLoad = createHttpDocumentSourceLoader({
+ fetch: async () => {
+ throw new Error("https://private.example/?token=secret");
+ },
+ getRequest: () => "https://cdn.webstudio.test/private.json",
+ getMetadata: () => ({ format: "json", revision: "post-r1" }),
+ onEvent: (event) => failedEvents.push(event),
+ });
+ await expect(failedLoad(node, {})).rejects.toMatchObject({
+ code: "REQUEST_FAILED",
+ });
+ expect(failedEvents).toEqual([
+ {
+ type: "document-fetch-started",
+ documentId: "post",
+ revision: "post-r1",
+ },
+ {
+ type: "document-fetch-failed",
+ documentId: "post",
+ revision: "post-r1",
+ errorCode: "REQUEST_FAILED",
+ },
+ ]);
+ expect(JSON.stringify(failedEvents)).not.toContain("secret");
+ });
+});
diff --git a/packages/content-engine/src/document-graph/http-document-loader.ts b/packages/content-engine/src/document-graph/http-document-loader.ts
new file mode 100644
index 0000000000..604a02b19d
--- /dev/null
+++ b/packages/content-engine/src/document-graph/http-document-loader.ts
@@ -0,0 +1,134 @@
+import { enum as zEnum, strictObject, string } from "zod";
+import type { DocumentGraphNode } from "./graph";
+import type { DocumentSourceLoader } from "./document-source";
+import {
+ observeDocumentSourceLoader,
+ type DocumentGraphRuntimeObserver,
+} from "./observability";
+
+const documentSourceMetadata = strictObject({
+ format: zEnum(["json", "markdown"]),
+ revision: string().min(1),
+});
+
+export type HttpDocumentLoaderErrorCode =
+ | "REQUEST_FAILED"
+ | "HTTP_STATUS"
+ | "BODY_MISSING"
+ | "INVALID_METADATA";
+
+export class HttpDocumentLoaderError extends Error {
+ readonly code: HttpDocumentLoaderErrorCode;
+ readonly documentId: string;
+ readonly status?: number;
+
+ constructor({
+ code,
+ message,
+ documentId,
+ status,
+ cause,
+ }: {
+ code: HttpDocumentLoaderErrorCode;
+ message: string;
+ documentId: string;
+ status?: number;
+ cause?: unknown;
+ }) {
+ super(message, { cause });
+ this.name = "HttpDocumentLoaderError";
+ this.code = code;
+ this.documentId = documentId;
+ this.status = status;
+ }
+}
+
+const streamResponseBody = (
+ body: ReadableStream<Uint8Array>
+): AsyncIterable<Uint8Array> => ({
+ async *[Symbol.asyncIterator]() {
+ const reader = body.getReader();
+ let completed = false;
+ try {
+ while (true) {
+ const chunk = await reader.read();
+ if (chunk.done) {
+ completed = true;
+ return;
+ }
+ yield chunk.value;
+ }
+ } finally {
+ if (completed === false) {
+ try {
+ await reader.cancel();
+ } catch {
+ // Preserve the consumer error that stopped the stream.
+ }
+ }
+ reader.releaseLock();
+ }
+ },
+});
+
+/** Adapts an injected HTTP/CDN transport to the revisioned source contract. */
+export const createHttpDocumentSourceLoader = ({
+ fetch: fetchResponse,
+ getRequest,
+ getMetadata,
+ onEvent,
+}: {
+ fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
+ getRequest: (node: DocumentGraphNode) => RequestInfo | URL;
+ getMetadata: (input: {
+ node: DocumentGraphNode;
+ response: Response;
+ }) => unknown;
+ onEvent?: DocumentGraphRuntimeObserver;
+}): DocumentSourceLoader => {
+ const load: DocumentSourceLoader = async (node, { signal }) => {
+ let response: Response;
+ try {
+ response = await fetchResponse(getRequest(node), { signal });
+ } catch (cause) {
+ throw new HttpDocumentLoaderError({
+ code: "REQUEST_FAILED",
+ message: `Document ${node.id} request failed`,
+ documentId: node.id,
+ cause,
+ });
+ }
+ if (response.ok === false) {
+ throw new HttpDocumentLoaderError({
+ code: "HTTP_STATUS",
+ message: `Document ${node.id} request returned status ${response.status}`,
+ documentId: node.id,
+ status: response.status,
+ });
+ }
+ let metadata;
+ try {
+ metadata = documentSourceMetadata.parse(getMetadata({ node, response }));
+ } catch (cause) {
+ throw new HttpDocumentLoaderError({
+ code: "INVALID_METADATA",
+ message: `Document ${node.id} response metadata is invalid`,
+ documentId: node.id,
+ cause,
+ });
+ }
+ const body = response.body;
+ if (body === null) {
+ throw new HttpDocumentLoaderError({
+ code: "BODY_MISSING",
+ message: `Document ${node.id} response body is unavailable`,
+ documentId: node.id,
+ });
+ }
+ return Object.freeze({
+ ...metadata,
+ source: streamResponseBody(body),
+ });
+ };
+ return observeDocumentSourceLoader({ load, onEvent });
+};
diff --git a/packages/content-engine/src/document-graph/index.ts b/packages/content-engine/src/document-graph/index.ts
new file mode 100644
index 0000000000..c3c58232ea
--- /dev/null
+++ b/packages/content-engine/src/document-graph/index.ts
@@ -0,0 +1,16 @@
+export * from "./reference";
+export * from "./reference-codec";
+export * from "./graph";
+export * from "./graph-artifact";
+export * from "./compiler";
+export * from "./source-compiler";
+export * from "./json-document";
+export * from "./markdown-document";
+export * from "./document-adapter";
+export * from "./document-source";
+export * from "./http-document-loader";
+export * from "./cached-document-loader";
+export * from "./resolver";
+export * from "./document-resolution";
+export * from "./query-references";
+export * from "./observability";
diff --git a/packages/content-engine/src/document-graph/json-document.test.ts b/packages/content-engine/src/document-graph/json-document.test.ts
new file mode 100644
index 0000000000..f1a42398bf
--- /dev/null
+++ b/packages/content-engine/src/document-graph/json-document.test.ts
@@ -0,0 +1,207 @@
+import { describe, expect, test } from "vitest";
+import {
+ analyzeJsonDocument,
+ analyzeJsonDocumentSource,
+ assembleJsonDocument,
+ JsonDocumentError,
+ selectJsonDocumentRepresentation,
+} from "./json-document";
+
+const documentUrl = "https://content.webstudio.test/posts/hello.json";
+
+describe("JSON document adapter", () => {
+ test("parses bounded UTF-8 JSON source before analyzing references", async () => {
+ const analyzed = await analyzeJsonDocumentSource({
+ source: '\uFEFF{"author":{"$ref":"../authors/ada.json"}}',
+ sourceDocumentId: "post",
+ documentUrl,
+ });
+
+ expect(analyzed.document).toEqual({
+ author: { $ref: "../authors/ada.json" },
+ });
+ expect(analyzed.references).toHaveLength(1);
+
+ await expect(
+ analyzeJsonDocumentSource({
+ source: '{"title":"too large"}',
+ sourceDocumentId: "post",
+ documentUrl,
+ maximumBytes: 5,
+ })
+ ).rejects.toMatchObject({ code: "CONTENT_LIMIT_EXCEEDED" });
+ await expect(
+ analyzeJsonDocumentSource({
+ source: new Uint8Array([0xff]),
+ sourceDocumentId: "post",
+ documentUrl,
+ })
+ ).rejects.toMatchObject({ code: "CONTENT_DECODING_FAILED" });
+ await expect(
+ analyzeJsonDocumentSource({
+ source: "{",
+ sourceDocumentId: "post",
+ documentUrl,
+ })
+ ).rejects.toMatchObject({ code: "INVALID_DOCUMENT" });
+ });
+
+ test("finds exact reference markers with stable JSON Pointer IDs", () => {
+ const value = {
+ title: "Hello",
+ author: { $ref: "../authors/ada.json#/name" },
+ blocks: [{ $ref: "../shared/cta.md#body" }],
+ metadata: { $ref: "ordinary-data", label: "Not a reference marker" },
+ "escaped/key~": { $ref: "../shared/value.json" },
+ };
+
+ const analyzed = analyzeJsonDocument({
+ value,
+ sourceDocumentId: "post",
+ documentUrl,
+ });
+
+ expect(analyzed.document).toEqual(value);
+ expect(analyzed.references).toEqual([
+ {
+ sourceDocumentId: "post",
+ referenceId: "#/author",
+ reference: {
+ documentUrl: "https://content.webstudio.test/authors/ada.json",
+ representation: { type: "json", path: ["name"] },
+ },
+ },
+ {
+ sourceDocumentId: "post",
+ referenceId: "#/blocks/0",
+ reference: {
+ documentUrl: "https://content.webstudio.test/shared/cta.md",
+ representation: { type: "markdown-body" },
+ },
+ },
+ {
+ sourceDocumentId: "post",
+ referenceId: "#/escaped~1key~0",
+ reference: {
+ documentUrl: "https://content.webstudio.test/shared/value.json",
+ representation: { type: "document" },
+ },
+ },
+ ]);
+ });
+
+ test("supports a reference marker as the document root", () => {
+ expect(
+ analyzeJsonDocument({
+ value: { $ref: "../shared/value.json" },
+ sourceDocumentId: "post",
+ documentUrl,
+ }).references[0]
+ ).toMatchObject({ referenceId: "#" });
+ });
+
+ test("reports an invalid exact reference marker with its location", () => {
+ expect(() =>
+ analyzeJsonDocument({
+ value: { author: { $ref: 42 } },
+ sourceDocumentId: "post",
+ documentUrl,
+ })
+ ).toThrowError(
+ expect.objectContaining({
+ code: "INVALID_REFERENCE_MARKER",
+ referenceId: "#/author",
+ } satisfies Partial<JsonDocumentError>)
+ );
+ });
+
+ test("selects the whole document or a nested JSON path", () => {
+ const document = {
+ author: { "display/name": "Ada" },
+ };
+
+ expect(
+ selectJsonDocumentRepresentation({
+ document,
+ representation: { type: "document" },
+ })
+ ).toEqual(document);
+ expect(
+ selectJsonDocumentRepresentation({
+ document,
+ representation: {
+ type: "json",
+ path: ["author", "display/name"],
+ },
+ })
+ ).toBe("Ada");
+ });
+
+ test("reports missing paths and unsupported representations", () => {
+ expect(() =>
+ selectJsonDocumentRepresentation({
+ document: { author: {} },
+ representation: { type: "json", path: ["author", "name"] },
+ })
+ ).toThrowError(expect.objectContaining({ code: "JSON_PATH_NOT_FOUND" }));
+ expect(() =>
+ selectJsonDocumentRepresentation({
+ document: {},
+ representation: { type: "markdown-body" },
+ })
+ ).toThrowError(
+ expect.objectContaining({ code: "UNSUPPORTED_REPRESENTATION" })
+ );
+ });
+
+ test("assembles nested references without mutating the source document", () => {
+ const document = {
+ title: "Hello",
+ author: { $ref: "../authors/ada.json" },
+ blocks: [{ $ref: "../shared/cta.md#body" }],
+ };
+ const result = assembleJsonDocument({
+ document,
+ references: new Map<string, unknown>([
+ ["#/author", { name: "Ada" }],
+ ["#/blocks/0", "Join us"],
+ ]),
+ });
+
+ expect(result).toEqual({
+ title: "Hello",
+ author: { name: "Ada" },
+ blocks: ["Join us"],
+ });
+ expect(document).toEqual({
+ title: "Hello",
+ author: { $ref: "../authors/ada.json" },
+ blocks: [{ $ref: "../shared/cta.md#body" }],
+ });
+ });
+
+ test("requires every marker and supplied reference to participate", () => {
+ expect(() =>
+ assembleJsonDocument({
+ document: { author: { $ref: "../authors/ada.json" } },
+ references: new Map(),
+ })
+ ).toThrowError(
+ expect.objectContaining({
+ code: "REFERENCE_NOT_FOUND",
+ referenceId: "#/author",
+ })
+ );
+ expect(() =>
+ assembleJsonDocument({
+ document: {},
+ references: new Map([["#/unused", "value"]]),
+ })
+ ).toThrowError(
+ expect.objectContaining({
+ code: "UNUSED_REFERENCE",
+ referenceId: "#/unused",
+ })
+ );
+ });
+});
diff --git a/packages/content-engine/src/document-graph/json-document.ts b/packages/content-engine/src/document-graph/json-document.ts
new file mode 100644
index 0000000000..31b239c121
--- /dev/null
+++ b/packages/content-engine/src/document-graph/json-document.ts
@@ -0,0 +1,330 @@
+import { append as appendJsonPointerSegment } from "@hyperjump/json-pointer";
+import {
+ ByteLimitExceededError,
+ decodeUtf8,
+ readBoundedBytes,
+ stripUtf8ByteOrderMark,
+ type ByteSource,
+} from "../byte-stream";
+import { normalizeJsonValue, type JsonValue } from "../canonical-json";
+import { contentEngineLimits } from "../limits";
+import type { DocumentRepresentation } from "./reference";
+import { getJsonReferenceMarkerValue, isJsonObject } from "./document-utils";
+import {
+ DocumentReferenceSyntaxError,
+ parseSourceDocumentReference,
+ type SourceReferenceOccurrence,
+} from "./reference-codec";
+
+export type JsonDocumentErrorCode =
+ | "CONTENT_LIMIT_EXCEEDED"
+ | "CONTENT_DECODING_FAILED"
+ | "INVALID_DOCUMENT"
+ | "INVALID_REFERENCE_MARKER"
+ | "INVALID_REFERENCE"
+ | "JSON_PATH_NOT_FOUND"
+ | "UNSUPPORTED_REPRESENTATION"
+ | "REFERENCE_NOT_FOUND"
+ | "INVALID_RESOLVED_VALUE"
+ | "UNUSED_REFERENCE";
+
+export class JsonDocumentError extends Error {
+ readonly code: JsonDocumentErrorCode;
+ readonly referenceId?: string;
+
+ constructor({
+ code,
+ message,
+ referenceId,
+ cause,
+ }: {
+ code: JsonDocumentErrorCode;
+ message: string;
+ referenceId?: string;
+ cause?: unknown;
+ }) {
+ super(message, { cause });
+ this.name = "JsonDocumentError";
+ this.code = code;
+ this.referenceId = referenceId;
+ }
+}
+
+const getReferenceMarker = (
+ value: JsonValue,
+ referenceId: string
+): string | undefined => {
+ const reference = getJsonReferenceMarkerValue(value);
+ if (reference === undefined) {
+ return;
+ }
+ if (typeof reference !== "string") {
+ throw new JsonDocumentError({
+ code: "INVALID_REFERENCE_MARKER",
+ message: `JSON reference marker ${referenceId} must contain a string $ref`,
+ referenceId,
+ });
+ }
+ return reference;
+};
+
+const getReferenceId = (pointer: string) => `#${pointer}`;
+
+/** Normalizes one parsed JSON value and discovers exact { $ref } markers. */
+export const analyzeJsonDocument = ({
+ value,
+ sourceDocumentId,
+ documentUrl,
+}: {
+ value: unknown;
+ sourceDocumentId: string;
+ documentUrl: string | URL;
+}): Readonly<{
+ document: JsonValue;
+ references: readonly SourceReferenceOccurrence[];
+}> => {
+ const document = normalizeJsonValue(value);
+ const references: SourceReferenceOccurrence[] = [];
+ const visit = (current: JsonValue, pointer: string) => {
+ const referenceId = getReferenceId(pointer);
+ const marker = getReferenceMarker(current, referenceId);
+ if (marker !== undefined) {
+ try {
+ references.push(
+ Object.freeze({
+ sourceDocumentId,
+ referenceId,
+ reference: parseSourceDocumentReference({
+ value: marker,
+ baseUrl: documentUrl,
+ }),
+ })
+ );
+ } catch (cause) {
+ if (cause instanceof DocumentReferenceSyntaxError) {
+ throw new JsonDocumentError({
+ code: "INVALID_REFERENCE",
+ message: `JSON reference marker ${referenceId} is invalid`,
+ referenceId,
+ cause,
+ });
+ }
+ throw cause;
+ }
+ return;
+ }
+ if (Array.isArray(current)) {
+ for (const [index, item] of current.entries()) {
+ visit(item, appendJsonPointerSegment(String(index), pointer));
+ }
+ return;
+ }
+ if (isJsonObject(current)) {
+ for (const key of Object.keys(current).sort()) {
+ visit(current[key], appendJsonPointerSegment(key, pointer));
+ }
+ }
+ };
+ visit(document, "");
+ return Object.freeze({
+ document,
+ references: Object.freeze(references),
+ });
+};
+
+/** Reads and normalizes one bounded JSON source. */
+export const parseJsonDocumentSource = async ({
+ source,
+ maximumBytes = contentEngineLimits.hydratedFileBytes,
+}: {
+ source: ByteSource;
+ maximumBytes?: number;
+}): Promise<JsonValue> => {
+ let bytes: Uint8Array;
+ try {
+ bytes = await readBoundedBytes(source, maximumBytes);
+ } catch (cause) {
+ if (cause instanceof ByteLimitExceededError) {
+ throw new JsonDocumentError({
+ code: "CONTENT_LIMIT_EXCEEDED",
+ message: "JSON document exceeds the byte limit",
+ cause,
+ });
+ }
+ throw cause;
+ }
+ let sourceText: string;
+ try {
+ sourceText = stripUtf8ByteOrderMark(decodeUtf8(bytes));
+ } catch (cause) {
+ throw new JsonDocumentError({
+ code: "CONTENT_DECODING_FAILED",
+ message: "JSON document is not valid UTF-8",
+ cause,
+ });
+ }
+ try {
+ return normalizeJsonValue(JSON.parse(sourceText));
+ } catch (cause) {
+ throw new JsonDocumentError({
+ code: "INVALID_DOCUMENT",
+ message: "JSON document is invalid",
+ cause,
+ });
+ }
+};
+
+/** Reads one bounded JSON source before discovering references. */
+export const analyzeJsonDocumentSource = async ({
+ source,
+ sourceDocumentId,
+ documentUrl,
+ maximumBytes = contentEngineLimits.hydratedFileBytes,
+}: {
+ source: ByteSource;
+ sourceDocumentId: string;
+ documentUrl: string | URL;
+ maximumBytes?: number;
+}): Promise<ReturnType<typeof analyzeJsonDocument>> =>
+ analyzeJsonDocument({
+ value: await parseJsonDocumentSource({ source, maximumBytes }),
+ sourceDocumentId,
+ documentUrl,
+ });
+
+const getJsonPathValue = (
+ document: JsonValue,
+ path: readonly string[]
+): JsonValue | undefined => {
+ let value: JsonValue = document;
+ for (const segment of path) {
+ if (Array.isArray(value)) {
+ const index = Number(segment);
+ if (
+ Number.isSafeInteger(index) === false ||
+ index < 0 ||
+ String(index) !== segment ||
+ index >= value.length
+ ) {
+ return;
+ }
+ value = value[index];
+ continue;
+ }
+ if (isJsonObject(value) && Object.hasOwn(value, segment)) {
+ value = value[segment];
+ continue;
+ }
+ return;
+ }
+ return value;
+};
+
+export const selectJsonDocumentRepresentation = ({
+ document: input,
+ representation,
+}: {
+ document: unknown;
+ representation: DocumentRepresentation;
+}): JsonValue => {
+ const document = normalizeJsonValue(input);
+ if (representation.type === "document") {
+ return document;
+ }
+ if (representation.type !== "json") {
+ throw new JsonDocumentError({
+ code: "UNSUPPORTED_REPRESENTATION",
+ message: `JSON documents do not support ${representation.type}`,
+ });
+ }
+ const value = getJsonPathValue(document, representation.path);
+ if (value === undefined) {
+ throw new JsonDocumentError({
+ code: "JSON_PATH_NOT_FOUND",
+ message: "JSON document path does not exist",
+ });
+ }
+ return value;
+};
+
+const defineJsonProperty = (
+ target: Record<string, JsonValue>,
+ key: string,
+ value: JsonValue
+) => {
+ Object.defineProperty(target, key, {
+ value,
+ enumerable: true,
+ configurable: true,
+ writable: true,
+ });
+};
+
+/** Replaces exact reference markers without mutating the parsed source value. */
+export const assembleJsonDocument = ({
+ document: input,
+ references,
+ allowUnresolvedReferences = false,
+}: {
+ document: unknown;
+ references: ReadonlyMap<string, unknown>;
+ allowUnresolvedReferences?: boolean;
+}): JsonValue => {
+ const document = normalizeJsonValue(input);
+ const usedReferences = new Set<string>();
+ const assemble = (current: JsonValue, pointer: string): JsonValue => {
+ const referenceId = getReferenceId(pointer);
+ const marker = getReferenceMarker(current, referenceId);
+ if (marker !== undefined) {
+ if (references.has(referenceId) === false) {
+ if (allowUnresolvedReferences) {
+ return current;
+ }
+ throw new JsonDocumentError({
+ code: "REFERENCE_NOT_FOUND",
+ message: `Resolved JSON reference ${referenceId} is unavailable`,
+ referenceId,
+ });
+ }
+ usedReferences.add(referenceId);
+ try {
+ return normalizeJsonValue(references.get(referenceId));
+ } catch (cause) {
+ throw new JsonDocumentError({
+ code: "INVALID_RESOLVED_VALUE",
+ message: `Resolved JSON reference ${referenceId} is not JSON-compatible`,
+ referenceId,
+ cause,
+ });
+ }
+ }
+ if (Array.isArray(current)) {
+ return current.map((item, index) =>
+ assemble(item, appendJsonPointerSegment(String(index), pointer))
+ );
+ }
+ if (isJsonObject(current)) {
+ const result: Record<string, JsonValue> = {};
+ for (const [key, value] of Object.entries(current)) {
+ defineJsonProperty(
+ result,
+ key,
+ assemble(value, appendJsonPointerSegment(key, pointer))
+ );
+ }
+ return result;
+ }
+ return current;
+ };
+ const result = assemble(document, "");
+ for (const referenceId of [...references.keys()].sort()) {
+ if (usedReferences.has(referenceId) === false) {
+ throw new JsonDocumentError({
+ code: "UNUSED_REFERENCE",
+ message: `Resolved JSON reference ${referenceId} has no marker`,
+ referenceId,
+ });
+ }
+ }
+ return result;
+};
diff --git a/packages/content-engine/src/document-graph/markdown-document.test.ts b/packages/content-engine/src/document-graph/markdown-document.test.ts
new file mode 100644
index 0000000000..d09e0f8621
--- /dev/null
+++ b/packages/content-engine/src/document-graph/markdown-document.test.ts
@@ -0,0 +1,147 @@
+import { describe, expect, test } from "vitest";
+import {
+ analyzeMarkdownDocument,
+ assembleMarkdownDocument,
+ MarkdownDocumentError,
+ selectMarkdownDocumentRepresentation,
+} from "./markdown-document";
+
+const documentUrl = "https://content.webstudio.test/posts/hello.md";
+const source = `---
+title: Hello
+author:
+ $ref: ../authors/ada.json
+seo:
+ image:
+ $ref: ../media/card.json#/url
+---
+# Hello
+
+The body can contain { "$ref": "ordinary text" }.
+`;
+
+describe("Markdown document adapter", () => {
+ test("parses source, body, frontmatter, and compiler-ready references", async () => {
+ const analyzed = await analyzeMarkdownDocument({
+ source,
+ sourceDocumentId: "post",
+ documentUrl,
+ });
+
+ expect(analyzed.document.source).toBe(source);
+ expect(analyzed.document.body).toBe(
+ '# Hello\n\nThe body can contain { "$ref": "ordinary text" }.\n'
+ );
+ expect(analyzed.document.frontmatter).toEqual({
+ title: "Hello",
+ author: { $ref: "../authors/ada.json" },
+ seo: { image: { $ref: "../media/card.json#/url" } },
+ });
+ expect(analyzed.references).toEqual([
+ {
+ sourceDocumentId: "post",
+ referenceId: "#frontmatter/author",
+ reference: {
+ documentUrl: "https://content.webstudio.test/authors/ada.json",
+ representation: { type: "document" },
+ },
+ },
+ {
+ sourceDocumentId: "post",
+ referenceId: "#frontmatter/seo/image",
+ reference: {
+ documentUrl: "https://content.webstudio.test/media/card.json",
+ representation: { type: "json", path: ["url"] },
+ },
+ },
+ ]);
+ });
+
+ test("selects complete source, body, and assembled frontmatter", async () => {
+ const { document } = await analyzeMarkdownDocument({
+ source,
+ sourceDocumentId: "post",
+ documentUrl,
+ });
+ const assembled = assembleMarkdownDocument({
+ document,
+ references: new Map<string, unknown>([
+ ["#frontmatter/author", { name: "Ada" }],
+ ["#frontmatter/seo/image", "/card.png"],
+ ]),
+ });
+
+ expect(
+ selectMarkdownDocumentRepresentation({
+ document: assembled,
+ representation: { type: "document" },
+ })
+ ).toBe(source);
+ expect(
+ selectMarkdownDocumentRepresentation({
+ document: assembled,
+ representation: { type: "markdown-body" },
+ })
+ ).toBe('# Hello\n\nThe body can contain { "$ref": "ordinary text" }.\n');
+ expect(
+ selectMarkdownDocumentRepresentation({
+ document: assembled,
+ representation: { type: "markdown-frontmatter" },
+ })
+ ).toEqual({
+ title: "Hello",
+ author: { name: "Ada" },
+ seo: { image: "/card.png" },
+ });
+ expect(document.frontmatter).toHaveProperty("author.$ref");
+ });
+
+ test("reports unsupported representations", async () => {
+ const { document } = await analyzeMarkdownDocument({
+ source: "# Hello",
+ sourceDocumentId: "post",
+ documentUrl,
+ });
+
+ expect(() =>
+ selectMarkdownDocumentRepresentation({
+ document,
+ representation: { type: "json", path: ["title"] },
+ })
+ ).toThrowError(
+ expect.objectContaining({ code: "UNSUPPORTED_REPRESENTATION" })
+ );
+ });
+
+ test("reports frontmatter reference failures with namespaced IDs", async () => {
+ const { document } = await analyzeMarkdownDocument({
+ source,
+ sourceDocumentId: "post",
+ documentUrl,
+ });
+
+ expect(() =>
+ assembleMarkdownDocument({ document, references: new Map() })
+ ).toThrowError(
+ expect.objectContaining({
+ code: "REFERENCE_NOT_FOUND",
+ referenceId: "#frontmatter/author",
+ } satisfies Partial<MarkdownDocumentError>)
+ );
+ expect(() =>
+ assembleMarkdownDocument({
+ document: {
+ source: "---\nauthor:\n $ref: 42\n---\n",
+ body: "",
+ frontmatter: { author: { $ref: 42 } },
+ },
+ references: new Map(),
+ })
+ ).toThrowError(
+ expect.objectContaining({
+ code: "INVALID_REFERENCE_MARKER",
+ referenceId: "#frontmatter/author",
+ } satisfies Partial<MarkdownDocumentError>)
+ );
+ });
+});
diff --git a/packages/content-engine/src/document-graph/markdown-document.ts b/packages/content-engine/src/document-graph/markdown-document.ts
new file mode 100644
index 0000000000..cf6e7a9056
--- /dev/null
+++ b/packages/content-engine/src/document-graph/markdown-document.ts
@@ -0,0 +1,271 @@
+import { json, record, strictObject, string } from "zod";
+import {
+ ByteLimitExceededError,
+ decodeUtf8,
+ readBoundedBytes,
+ stripUtf8ByteOrderMark,
+ type ByteSource,
+} from "../byte-stream";
+import { normalizeJsonValue, type JsonValue } from "../canonical-json";
+import { extractMarkdownFrontmatter } from "../frontmatter";
+import { contentEngineLimits } from "../limits";
+import { extractMarkdownBody } from "../markdown-body";
+import type { DocumentRepresentation } from "./reference";
+import type { SourceReferenceOccurrence } from "./reference-codec";
+import {
+ analyzeJsonDocument,
+ assembleJsonDocument,
+ JsonDocumentError,
+} from "./json-document";
+
+export type MarkdownDocument = Readonly<{
+ source: string;
+ body: string;
+ frontmatter: { readonly [key: string]: JsonValue };
+}>;
+
+export type MarkdownDocumentErrorCode =
+ | "CONTENT_LIMIT_EXCEEDED"
+ | "CONTENT_DECODING_FAILED"
+ | "INVALID_DOCUMENT"
+ | "INVALID_REFERENCE_MARKER"
+ | "INVALID_REFERENCE"
+ | "REFERENCE_NOT_FOUND"
+ | "INVALID_RESOLVED_VALUE"
+ | "UNUSED_REFERENCE"
+ | "UNSUPPORTED_REPRESENTATION";
+
+export class MarkdownDocumentError extends Error {
+ readonly code: MarkdownDocumentErrorCode;
+ readonly referenceId?: string;
+
+ constructor({
+ code,
+ message,
+ referenceId,
+ cause,
+ }: {
+ code: MarkdownDocumentErrorCode;
+ message: string;
+ referenceId?: string;
+ cause?: unknown;
+ }) {
+ super(message, { cause });
+ this.name = "MarkdownDocumentError";
+ this.code = code;
+ this.referenceId = referenceId;
+ }
+}
+
+const markdownDocumentSchema = strictObject({
+ source: string(),
+ body: string(),
+ frontmatter: record(string(), json()),
+});
+
+const normalizeMarkdownDocument = (input: unknown): MarkdownDocument => {
+ let parsed;
+ try {
+ parsed = markdownDocumentSchema.parse(input);
+ } catch (cause) {
+ throw new MarkdownDocumentError({
+ code: "INVALID_DOCUMENT",
+ message: "Markdown document is invalid",
+ cause,
+ });
+ }
+ return Object.freeze({
+ source: parsed.source,
+ body: parsed.body,
+ frontmatter: normalizeJsonValue(parsed.frontmatter) as {
+ readonly [key: string]: JsonValue;
+ },
+ });
+};
+
+const markdownReferencePrefix = "#frontmatter";
+
+const toMarkdownReferenceId = (jsonReferenceId: string) =>
+ `${markdownReferencePrefix}${jsonReferenceId.slice(1)}`;
+
+const toJsonReferenceId = (markdownReferenceId: string) => {
+ if (
+ markdownReferenceId !== markdownReferencePrefix &&
+ markdownReferenceId.startsWith(`${markdownReferencePrefix}/`) === false
+ ) {
+ throw new MarkdownDocumentError({
+ code: "UNUSED_REFERENCE",
+ message: `Resolved Markdown reference ${markdownReferenceId} is outside frontmatter`,
+ referenceId: markdownReferenceId,
+ });
+ }
+ return `#${markdownReferenceId.slice(markdownReferencePrefix.length)}`;
+};
+
+const throwMarkdownJsonError = (error: JsonDocumentError): never => {
+ const referenceId =
+ error.referenceId === undefined
+ ? undefined
+ : toMarkdownReferenceId(error.referenceId);
+ let code: MarkdownDocumentErrorCode = "INVALID_DOCUMENT";
+ if (
+ error.code === "INVALID_REFERENCE_MARKER" ||
+ error.code === "INVALID_REFERENCE" ||
+ error.code === "REFERENCE_NOT_FOUND" ||
+ error.code === "INVALID_RESOLVED_VALUE" ||
+ error.code === "UNUSED_REFERENCE"
+ ) {
+ code = error.code;
+ }
+ throw new MarkdownDocumentError({
+ code,
+ message: error.message,
+ referenceId,
+ cause: error,
+ });
+};
+
+/** Reads and normalizes one bounded Markdown source. */
+export const parseMarkdownDocumentSource = async ({
+ source,
+ maximumBytes = contentEngineLimits.hydratedFileBytes,
+}: {
+ source: ByteSource;
+ maximumBytes?: number;
+}): Promise<MarkdownDocument> => {
+ let bytes: Uint8Array;
+ try {
+ bytes = await readBoundedBytes(source, maximumBytes);
+ } catch (cause) {
+ if (cause instanceof ByteLimitExceededError) {
+ throw new MarkdownDocumentError({
+ code: "CONTENT_LIMIT_EXCEEDED",
+ message: "Markdown document exceeds the byte limit",
+ cause,
+ });
+ }
+ throw cause;
+ }
+ let sourceText: string;
+ try {
+ sourceText = stripUtf8ByteOrderMark(decodeUtf8(bytes));
+ } catch (cause) {
+ throw new MarkdownDocumentError({
+ code: "CONTENT_DECODING_FAILED",
+ message: "Markdown document is not valid UTF-8",
+ cause,
+ });
+ }
+ const [body, frontmatter] = await Promise.all([
+ extractMarkdownBody(bytes, maximumBytes),
+ extractMarkdownFrontmatter(bytes),
+ ]);
+ return normalizeMarkdownDocument({
+ source: sourceText,
+ body: body.body,
+ frontmatter: frontmatter.properties,
+ });
+};
+
+/** Reads one bounded Markdown source and discovers references in frontmatter. */
+export const analyzeMarkdownDocument = async ({
+ source,
+ sourceDocumentId,
+ documentUrl,
+ maximumBytes = contentEngineLimits.hydratedFileBytes,
+}: {
+ source: ByteSource;
+ sourceDocumentId: string;
+ documentUrl: string | URL;
+ maximumBytes?: number;
+}): Promise<
+ Readonly<{
+ document: MarkdownDocument;
+ references: readonly SourceReferenceOccurrence[];
+ }>
+> => {
+ const parsed = await parseMarkdownDocumentSource({ source, maximumBytes });
+ let analyzedFrontmatter;
+ try {
+ analyzedFrontmatter = analyzeJsonDocument({
+ value: parsed.frontmatter,
+ sourceDocumentId,
+ documentUrl,
+ });
+ } catch (cause) {
+ if (cause instanceof JsonDocumentError) {
+ throwMarkdownJsonError(cause);
+ }
+ throw cause;
+ }
+ const document = normalizeMarkdownDocument({
+ source: parsed.source,
+ body: parsed.body,
+ frontmatter: analyzedFrontmatter.document,
+ });
+ return Object.freeze({
+ document,
+ references: Object.freeze(
+ analyzedFrontmatter.references.map((occurrence) =>
+ Object.freeze({
+ ...occurrence,
+ referenceId: toMarkdownReferenceId(occurrence.referenceId),
+ })
+ )
+ ),
+ });
+};
+
+/** Assembles frontmatter references while preserving the original source and body. */
+export const assembleMarkdownDocument = ({
+ document: input,
+ references,
+ allowUnresolvedReferences = false,
+}: {
+ document: unknown;
+ references: ReadonlyMap<string, unknown>;
+ allowUnresolvedReferences?: boolean;
+}): MarkdownDocument => {
+ const document = normalizeMarkdownDocument(input);
+ const jsonReferences = new Map<string, unknown>();
+ for (const [referenceId, value] of references) {
+ jsonReferences.set(toJsonReferenceId(referenceId), value);
+ }
+ let frontmatter: JsonValue;
+ try {
+ frontmatter = assembleJsonDocument({
+ document: document.frontmatter,
+ references: jsonReferences,
+ allowUnresolvedReferences,
+ });
+ } catch (cause) {
+ if (cause instanceof JsonDocumentError) {
+ throwMarkdownJsonError(cause);
+ }
+ throw cause;
+ }
+ return normalizeMarkdownDocument({ ...document, frontmatter });
+};
+
+export const selectMarkdownDocumentRepresentation = ({
+ document: input,
+ representation,
+}: {
+ document: unknown;
+ representation: DocumentRepresentation;
+}): JsonValue => {
+ const document = normalizeMarkdownDocument(input);
+ if (representation.type === "document") {
+ return document.source;
+ }
+ if (representation.type === "markdown-body") {
+ return document.body;
+ }
+ if (representation.type === "markdown-frontmatter") {
+ return document.frontmatter;
+ }
+ throw new MarkdownDocumentError({
+ code: "UNSUPPORTED_REPRESENTATION",
+ message: `Markdown documents do not support ${representation.type}`,
+ });
+};
diff --git a/packages/content-engine/src/document-graph/observability.ts b/packages/content-engine/src/document-graph/observability.ts
new file mode 100644
index 0000000000..031ffff771
--- /dev/null
+++ b/packages/content-engine/src/document-graph/observability.ts
@@ -0,0 +1,98 @@
+export type DocumentGraphRuntimeEvent =
+ | Readonly<{
+ type: "roots-selected";
+ rootCount: number;
+ }>
+ | Readonly<{
+ type: "resolution-started" | "resolution-completed";
+ rootCount: number;
+ documentCount: number;
+ }>
+ | Readonly<{
+ type: "resolution-failed";
+ rootCount: number;
+ documentCount: number;
+ errorCode: string;
+ }>
+ | Readonly<{
+ type:
+ | "document-fetch-started"
+ | "document-fetch-completed"
+ | "document-cache-hit"
+ | "document-cache-miss"
+ | "document-cache-stored";
+ documentId: string;
+ revision: string;
+ }>
+ | Readonly<{
+ type:
+ | "document-fetch-failed"
+ | "document-cache-read-failed"
+ | "document-cache-write-failed";
+ documentId: string;
+ revision: string;
+ errorCode: string;
+ }>;
+
+export type DocumentGraphRuntimeObserver = (
+ event: DocumentGraphRuntimeEvent
+) => void;
+
+export const getDocumentGraphErrorCode = (error: unknown) => {
+ if (typeof error === "object" && error !== null) {
+ const code = Reflect.get(error, "code");
+ if (typeof code === "string" && code.length > 0) {
+ return code;
+ }
+ const name = Reflect.get(error, "name");
+ if (typeof name === "string" && name.length > 0) {
+ return name;
+ }
+ }
+ return "UNKNOWN";
+};
+
+/** Observer failures must never change content query behavior. */
+export const emitDocumentGraphRuntimeEvent = (
+ observer: DocumentGraphRuntimeObserver | undefined,
+ event: DocumentGraphRuntimeEvent
+) => {
+ try {
+ observer?.(event);
+ } catch {
+ // Observability is best effort.
+ }
+};
+
+/** Adds transport-neutral fetch events around an object-store source loader. */
+export const observeDocumentSourceLoader =
+ ({
+ load,
+ onEvent,
+ }: {
+ load: DocumentSourceLoader;
+ onEvent?: DocumentGraphRuntimeObserver;
+ }): DocumentSourceLoader =>
+ async (node, options) => {
+ const event = { documentId: node.id, revision: node.revision };
+ emitDocumentGraphRuntimeEvent(onEvent, {
+ type: "document-fetch-started",
+ ...event,
+ });
+ try {
+ const source = await load(node, options);
+ emitDocumentGraphRuntimeEvent(onEvent, {
+ type: "document-fetch-completed",
+ ...event,
+ });
+ return source;
+ } catch (error) {
+ emitDocumentGraphRuntimeEvent(onEvent, {
+ type: "document-fetch-failed",
+ ...event,
+ errorCode: getDocumentGraphErrorCode(error),
+ });
+ throw error;
+ }
+ };
+import type { DocumentSourceLoader } from "./document-source";
diff --git a/packages/content-engine/src/document-graph/query-references.test.ts b/packages/content-engine/src/document-graph/query-references.test.ts
new file mode 100644
index 0000000000..90bc77c795
--- /dev/null
+++ b/packages/content-engine/src/document-graph/query-references.test.ts
@@ -0,0 +1,43 @@
+import { expect, test } from "vitest";
+import { assetQuery } from "../schema";
+import { createDocumentGraph } from "./graph";
+import {
+ getDocumentGraphQueryRootIds,
+ isDocumentGraphFieldAffected,
+} from "./query-references";
+
+test("ignores reference IDs that are not valid property pointers", () => {
+ const graph = createDocumentGraph({
+ nodes: [
+ { id: "post", revision: "post-r1", contentRef: "content:post" },
+ { id: "author", revision: "author-r1", contentRef: "content:author" },
+ ],
+ edges: [
+ {
+ sourceId: "post",
+ referenceId: "#/~",
+ reference: {
+ documentId: "author",
+ revision: "author-r1",
+ representation: { type: "document" },
+ },
+ },
+ ],
+ });
+ const query = assetQuery.parse({
+ output: {
+ mode: "fields",
+ fields: [["properties", "author"]],
+ includeMetadata: false,
+ },
+ });
+
+ expect(
+ isDocumentGraphFieldAffected({
+ graph,
+ sourceId: "post",
+ field: ["properties", "author"],
+ })
+ ).toBe(false);
+ expect(getDocumentGraphQueryRootIds({ graph, query })).toEqual([]);
+});
diff --git a/packages/content-engine/src/document-graph/query-references.ts b/packages/content-engine/src/document-graph/query-references.ts
new file mode 100644
index 0000000000..b2e98371bc
--- /dev/null
+++ b/packages/content-engine/src/document-graph/query-references.ts
@@ -0,0 +1,181 @@
+import { pointerSegments } from "@hyperjump/json-pointer";
+import { getQueryConditions } from "@webstudio-is/query-builder/runtime";
+import type { ContentCompilationQuery } from "../compilation-plan";
+import type { AssetQuery, AssetQueryFieldPath } from "../schema";
+import { createDocumentGraph, type DocumentGraph } from "./graph";
+import { getDocumentGraphEdgesBySourceId } from "./graph-utils";
+
+type QueryWithFields =
+ | Pick<AssetQuery, "where" | "sort" | "output">
+ | Pick<ContentCompilationQuery, "where" | "sort" | "output">;
+
+const getQueryPropertyPaths = (query: QueryWithFields) => {
+ if (query.output.mode === "all") {
+ return "all" as const;
+ }
+ const paths: AssetQueryFieldPath[] = [];
+ for (const { field } of getQueryConditions(query.where)) {
+ if (field[0] === "properties") {
+ paths.push(field);
+ }
+ }
+ for (const { field } of query.sort) {
+ if (field[0] === "properties") {
+ paths.push(field);
+ }
+ }
+ if (query.output.mode === "fields") {
+ for (const field of query.output.fields) {
+ if (field[0] === "properties") {
+ paths.push(field);
+ }
+ }
+ }
+ return paths;
+};
+
+const getReferencePropertyPath = (
+ referenceId: string
+): AssetQueryFieldPath | undefined => {
+ let pointer: string;
+ if (referenceId === "#frontmatter") {
+ pointer = "";
+ } else if (referenceId.startsWith("#frontmatter/")) {
+ pointer = referenceId.slice("#frontmatter".length);
+ } else if (referenceId === "#") {
+ pointer = "";
+ } else if (referenceId.startsWith("#/")) {
+ pointer = referenceId.slice(1);
+ } else {
+ return;
+ }
+ try {
+ return ["properties", ...pointerSegments(pointer)];
+ } catch {
+ return;
+ }
+};
+
+const pathsOverlap = (
+ left: AssetQueryFieldPath,
+ right: AssetQueryFieldPath
+) => {
+ const length = Math.min(left.length, right.length);
+ for (let index = 0; index < length; index += 1) {
+ if (left[index] !== right[index]) {
+ return false;
+ }
+ }
+ return true;
+};
+
+const queryPathMatchesReference = ({
+ queryPaths,
+ referenceId,
+}: {
+ queryPaths: "all" | readonly AssetQueryFieldPath[];
+ referenceId: string;
+}) => {
+ const referencePath = getReferencePropertyPath(referenceId);
+ return (
+ referencePath !== undefined &&
+ (queryPaths === "all" ||
+ queryPaths.some((queryPath) => pathsOverlap(queryPath, referencePath)))
+ );
+};
+
+export const isDocumentGraphFieldAffected = ({
+ graph,
+ sourceId,
+ field,
+}: {
+ graph: DocumentGraph;
+ sourceId: string;
+ field: AssetQueryFieldPath;
+}) => {
+ if (field[0] !== "properties") {
+ return false;
+ }
+ return graph.edges.some((edge) => {
+ if (edge.sourceId !== sourceId) {
+ return false;
+ }
+ const referencePath = getReferencePropertyPath(edge.referenceId);
+ return referencePath !== undefined && pathsOverlap(field, referencePath);
+ });
+};
+
+/** Finds graph sources whose reference locations can affect a query. */
+export const getDocumentGraphQueryRootIds = ({
+ graph,
+ query,
+}: {
+ graph: DocumentGraph;
+ query: QueryWithFields;
+}) => {
+ const queryPaths = getQueryPropertyPaths(query);
+ const rootIds = new Set<string>();
+ for (const edge of graph.edges) {
+ if (
+ queryPathMatchesReference({ queryPaths, referenceId: edge.referenceId })
+ ) {
+ rootIds.add(edge.sourceId);
+ }
+ }
+ return [...rootIds];
+};
+
+/** Keeps query-intersecting root edges and complete downstream dependencies. */
+export const selectDocumentGraphForQuery = ({
+ graph,
+ query,
+ rootIds,
+}: {
+ graph: DocumentGraph;
+ query: QueryWithFields;
+ rootIds: readonly string[];
+}) => {
+ const queryPaths = getQueryPropertyPaths(query);
+ const rootIdSet = new Set(rootIds);
+ const nodesById = new Map(graph.nodes.map((node) => [node.id, node]));
+ const edgesBySourceId = getDocumentGraphEdgesBySourceId(graph.edges);
+ const selectedNodeIds = new Set(rootIds);
+ const selectedEdges = new Set<(typeof graph.edges)[number]>();
+ const expandedDependencyIds = new Set<string>();
+
+ const selectDependencies = (documentId: string) => {
+ selectedNodeIds.add(documentId);
+ if (expandedDependencyIds.has(documentId)) {
+ return;
+ }
+ expandedDependencyIds.add(documentId);
+ for (const edge of edgesBySourceId.get(documentId) ?? []) {
+ selectedEdges.add(edge);
+ selectDependencies(edge.reference.documentId);
+ }
+ };
+
+ for (const edge of graph.edges) {
+ if (
+ rootIdSet.has(edge.sourceId) &&
+ queryPathMatchesReference({
+ queryPaths,
+ referenceId: edge.referenceId,
+ })
+ ) {
+ selectedEdges.add(edge);
+ selectDependencies(edge.reference.documentId);
+ }
+ }
+
+ return createDocumentGraph({
+ nodes: [...selectedNodeIds].map((id) => {
+ const node = nodesById.get(id);
+ if (node === undefined) {
+ throw new Error(`Document graph query root ${id} does not exist`);
+ }
+ return node;
+ }),
+ edges: [...selectedEdges],
+ });
+};
diff --git a/packages/content-engine/src/document-graph/query-resolution.test.ts b/packages/content-engine/src/document-graph/query-resolution.test.ts
new file mode 100644
index 0000000000..ce688acdca
--- /dev/null
+++ b/packages/content-engine/src/document-graph/query-resolution.test.ts
@@ -0,0 +1,345 @@
+import { describe, expect, test, vi } from "vitest";
+import { compileContentArtifact } from "../asset-index";
+import { createCanonicalAssetFileEntry } from "../canonical";
+import { createContentDatabase } from "../content-database";
+import type { AssetQuery } from "../schema";
+import {
+ createContentCompilationPlan,
+ createLiteralContentCompilationQuery,
+} from "../compilation-plan";
+import { createDocumentGraph } from "./graph";
+
+const createPostEntry = (id: string, authorPath: string) =>
+ createCanonicalAssetFileEntry({
+ projectId: "project",
+ document: {
+ _id: id,
+ _type: "asset.file",
+ name: `${id}.json`,
+ path: `posts/${id}.json`,
+ key: id,
+ extension: "json",
+ mimeType: "application/json",
+ size: 1,
+ revision: `${id}-r1`,
+ contentRef: `content:${id}`,
+ properties: { author: { $ref: authorPath } },
+ },
+ });
+
+describe("document graph query resolution", () => {
+ test("resolves referenced fields before filtering and projection", async () => {
+ const entries = [
+ createPostEntry("post-ada", "../authors/ada.json"),
+ createPostEntry("post-grace", "../authors/grace.json"),
+ ];
+ const graph = createDocumentGraph({
+ nodes: [
+ ...entries.map(({ assetId, revision, document }) => ({
+ id: assetId,
+ revision,
+ contentRef: document.contentRef,
+ format: "json" as const,
+ })),
+ {
+ id: "author-ada",
+ revision: "author-ada-r1",
+ contentRef: "content:author-ada",
+ format: "json",
+ },
+ {
+ id: "author-grace",
+ revision: "author-grace-r1",
+ contentRef: "content:author-grace",
+ format: "json",
+ },
+ ],
+ edges: [
+ {
+ sourceId: "post-ada",
+ referenceId: "#/author",
+ reference: {
+ documentId: "author-ada",
+ revision: "author-ada-r1",
+ representation: { type: "document" },
+ },
+ },
+ {
+ sourceId: "post-grace",
+ referenceId: "#/author",
+ reference: {
+ documentId: "author-grace",
+ revision: "author-grace-r1",
+ representation: { type: "document" },
+ },
+ },
+ ],
+ });
+ const { artifact } = await compileContentArtifact({
+ projectId: "project",
+ entries,
+ documentGraph: graph,
+ });
+ const sources: Record<string, string> = {
+ "post-ada": '{"author":{"$ref":"../authors/ada.json"}}',
+ "post-grace": '{"author":{"$ref":"../authors/grace.json"}}',
+ "author-ada": '{"name":"Ada"}',
+ "author-grace": '{"name":"Grace"}',
+ };
+ const load = vi.fn(async (node: (typeof graph.nodes)[number]) => ({
+ format: "json" as const,
+ revision: node.revision,
+ source: sources[node.id],
+ }));
+
+ const database = createContentDatabase({ artifact });
+ const result = await database.queryWithDocumentGraph({
+ request: {
+ query: {
+ where: {
+ all: [
+ {
+ field: ["properties", "author", "name"],
+ operator: "eq",
+ value: "Ada",
+ },
+ ],
+ },
+ sort: [
+ {
+ field: ["properties", "author", "name"],
+ direction: "asc",
+ },
+ ],
+ output: {
+ mode: "fields",
+ includeMetadata: false,
+ fields: [["properties", "author", "name"]],
+ },
+ content: { mode: "none" },
+ },
+ },
+ load,
+ });
+
+ expect(result).toEqual({
+ items: [
+ {
+ id: "post-ada",
+ properties: { author: { name: "Ada" } },
+ },
+ ],
+ totalCount: 1,
+ hasMore: false,
+ });
+ const sorted = await database.queryWithDocumentGraph({
+ request: {
+ query: {
+ where: { all: [] },
+ sort: [
+ {
+ field: ["properties", "author", "name"],
+ direction: "desc",
+ },
+ ],
+ limit: 1,
+ output: {
+ mode: "fields",
+ includeMetadata: false,
+ fields: [["properties", "author", "name"]],
+ },
+ content: { mode: "none" },
+ },
+ },
+ load,
+ });
+ expect(sorted.items).toEqual([
+ {
+ id: "post-grace",
+ properties: { author: { name: "Grace" } },
+ },
+ ]);
+ expect(load).toHaveBeenCalledTimes(8);
+
+ const graphQuery = {
+ where: {
+ all: [
+ {
+ field: ["properties", "author", "name"],
+ operator: "eq",
+ value: "Ada",
+ },
+ ],
+ },
+ sort: [],
+ limit: 20,
+ offset: 0,
+ output: {
+ mode: "fields",
+ includeMetadata: false,
+ fields: [["properties", "author"]],
+ },
+ content: { mode: "none" },
+ } satisfies AssetQuery;
+ const planned = await compileContentArtifact({
+ projectId: "project",
+ entries,
+ documentGraph: graph,
+ plan: createContentCompilationPlan([
+ createLiteralContentCompilationQuery({
+ id: "authors",
+ query: graphQuery,
+ }),
+ ]),
+ });
+ expect(planned.artifact.queries).toBeUndefined();
+ expect(planned.artifact.documents).toHaveLength(2);
+ });
+
+ test("narrows graph roots with static filters and skips unselected sibling references", async () => {
+ const postCount = 12;
+ const entries = Array.from({ length: postCount }, (_, index) => {
+ const id = `post-${String(index).padStart(2, "0")}`;
+ return createCanonicalAssetFileEntry({
+ projectId: "project",
+ document: {
+ _id: id,
+ _type: "asset.file",
+ name: `${id}.json`,
+ path: `posts/${id}.json`,
+ key: id,
+ extension: "json",
+ mimeType: "application/json",
+ size: 1,
+ revision: `${id}-r1`,
+ contentRef: `content:${id}`,
+ properties: {
+ slug: id,
+ author: { $ref: "../author.json" },
+ body: { $ref: `./${id}.md#body` },
+ },
+ },
+ });
+ });
+ const graph = createDocumentGraph({
+ nodes: [
+ ...entries.map(({ assetId, revision, document }) => ({
+ id: assetId,
+ revision,
+ contentRef: document.contentRef,
+ format: "json" as const,
+ })),
+ ...entries.map(({ assetId }) => ({
+ id: `${assetId}-body`,
+ revision: `${assetId}-body-r1`,
+ contentRef: `content:${assetId}-body`,
+ format: "markdown" as const,
+ })),
+ {
+ id: "author",
+ revision: "author-r1",
+ contentRef: "content:author",
+ format: "json" as const,
+ },
+ ],
+ edges: entries.flatMap(({ assetId }) => [
+ {
+ sourceId: assetId,
+ referenceId: "#/author",
+ reference: {
+ documentId: "author",
+ revision: "author-r1",
+ representation: { type: "document" as const },
+ },
+ },
+ {
+ sourceId: assetId,
+ referenceId: "#/body",
+ reference: {
+ documentId: `${assetId}-body`,
+ revision: `${assetId}-body-r1`,
+ representation: { type: "markdown-body" as const },
+ },
+ },
+ ]),
+ });
+ const { artifact } = await compileContentArtifact({
+ projectId: "project",
+ entries,
+ documentGraph: graph,
+ });
+ const sources = Object.fromEntries([
+ ...entries.map(({ assetId }) => [
+ assetId,
+ JSON.stringify({
+ slug: assetId,
+ author: { $ref: "../author.json" },
+ body: { $ref: `./${assetId}.md#body` },
+ }),
+ ]),
+ ...entries.map(({ assetId }) => [`${assetId}-body`, `# ${assetId}`]),
+ ["author", '{"name":"Ada"}'],
+ ]);
+ const load = vi.fn(async (node: (typeof graph.nodes)[number]) => ({
+ format: node.format as "json" | "markdown",
+ revision: node.revision,
+ source: sources[node.id],
+ }));
+ const database = createContentDatabase({ artifact });
+
+ const detail = await database.queryWithDocumentGraph({
+ request: {
+ query: {
+ where: {
+ all: [
+ {
+ field: ["properties", "slug"],
+ operator: "eq",
+ value: "post-07",
+ },
+ ],
+ },
+ limit: 1,
+ output: {
+ mode: "fields",
+ includeMetadata: false,
+ fields: [["properties", "body"]],
+ },
+ content: { mode: "none" },
+ },
+ },
+ load,
+ });
+
+ expect(detail.items).toEqual([
+ { id: "post-07", properties: { body: "# post-07" } },
+ ]);
+ expect(load.mock.calls.map(([node]) => node.id).sort()).toEqual([
+ "post-07",
+ "post-07-body",
+ ]);
+
+ load.mockClear();
+ const overview = await database.queryWithDocumentGraph({
+ request: {
+ query: {
+ where: { all: [] },
+ limit: postCount,
+ output: {
+ mode: "fields",
+ includeMetadata: false,
+ fields: [["properties", "author"]],
+ },
+ content: { mode: "none" },
+ },
+ },
+ load,
+ });
+
+ expect(overview.items).toHaveLength(postCount);
+ expect(load.mock.calls.map(([node]) => node.id).sort()).toEqual([
+ "author",
+ ...entries.map(({ assetId }) => assetId),
+ ]);
+ });
+});
diff --git a/packages/content-engine/src/document-graph/reference-codec.test.ts b/packages/content-engine/src/document-graph/reference-codec.test.ts
new file mode 100644
index 0000000000..1d06f2aaa8
--- /dev/null
+++ b/packages/content-engine/src/document-graph/reference-codec.test.ts
@@ -0,0 +1,106 @@
+import { describe, expect, test } from "vitest";
+import {
+ parseSourceDocumentReference,
+ serializeSourceDocumentReference,
+} from "./reference-codec";
+
+const baseUrl = "https://content.webstudio.test/posts/hello.json";
+
+describe("source document reference codec", () => {
+ test("resolves a relative document and decodes an RFC 6901 JSON Pointer", () => {
+ const reference = parseSourceDocumentReference({
+ value: "../authors/ada.json#/profile/display~1name",
+ baseUrl,
+ });
+
+ expect(reference).toEqual({
+ documentUrl: "https://content.webstudio.test/authors/ada.json",
+ representation: {
+ type: "json",
+ path: ["profile", "display/name"],
+ },
+ });
+ expect(Object.isFrozen(reference)).toBe(true);
+ expect(Object.isFrozen(reference.representation)).toBe(true);
+ });
+
+ test("supports URI-encoded JSON Pointer fragments", () => {
+ expect(
+ parseSourceDocumentReference({
+ value: "../authors/ada.json#%2Fprofile%2Fdisplay%20name",
+ baseUrl,
+ }).representation
+ ).toEqual({ type: "json", path: ["profile", "display name"] });
+ });
+
+ test.each([
+ ["../about.md", { type: "document" }],
+ ["../about.md#body", { type: "markdown-body" }],
+ ["../about.md#frontmatter", { type: "markdown-frontmatter" }],
+ ])("parses the representation in %s", (value, representation) => {
+ expect(parseSourceDocumentReference({ value, baseUrl })).toEqual({
+ documentUrl: "https://content.webstudio.test/about.md",
+ representation,
+ });
+ });
+
+ test("resolves a same-document reference without retaining the base fragment", () => {
+ expect(
+ parseSourceDocumentReference({
+ value: "#/author/name",
+ baseUrl: `${baseUrl}#body`,
+ })
+ ).toEqual({
+ documentUrl: baseUrl,
+ representation: { type: "json", path: ["author", "name"] },
+ });
+ });
+
+ test("serializes references canonically and round trips them", () => {
+ const reference = parseSourceDocumentReference({
+ value: "../authors/ada.json#/profile/display~1name",
+ baseUrl,
+ });
+ const serialized = serializeSourceDocumentReference(reference);
+
+ expect(serialized).toBe(
+ "https://content.webstudio.test/authors/ada.json#%2Fprofile%2Fdisplay~1name"
+ );
+ expect(
+ parseSourceDocumentReference({ value: serialized, baseUrl })
+ ).toEqual(reference);
+ expect(
+ serializeSourceDocumentReference({
+ documentUrl: "https://content.webstudio.test/about.md",
+ representation: { type: "markdown-body" },
+ })
+ ).toBe("https://content.webstudio.test/about.md#body");
+ });
+
+ test.each([
+ ["../about.md#unknown", "INVALID_FRAGMENT"],
+ ["../author.json#/invalid~2escape", "INVALID_JSON_POINTER"],
+ ["../author.json#%E0%A4%A", "INVALID_FRAGMENT_ENCODING"],
+ ])("rejects invalid reference %s", (value, code) => {
+ expect(() => parseSourceDocumentReference({ value, baseUrl })).toThrowError(
+ expect.objectContaining({ code })
+ );
+ });
+
+ test("rejects a relative base URL", () => {
+ expect(() =>
+ parseSourceDocumentReference({
+ value: "author.json",
+ baseUrl: "posts/hello.json",
+ })
+ ).toThrowError(expect.objectContaining({ code: "INVALID_BASE_URL" }));
+ });
+
+ test("rejects a non-string authored reference", () => {
+ expect(() =>
+ parseSourceDocumentReference({ value: 42, baseUrl })
+ ).toThrowError(
+ expect.objectContaining({ code: "INVALID_REFERENCE_URL", value: 42 })
+ );
+ });
+});
diff --git a/packages/content-engine/src/document-graph/reference-codec.ts b/packages/content-engine/src/document-graph/reference-codec.ts
new file mode 100644
index 0000000000..aff67c48b4
--- /dev/null
+++ b/packages/content-engine/src/document-graph/reference-codec.ts
@@ -0,0 +1,214 @@
+import {
+ append as appendJsonPointerSegment,
+ nil as emptyJsonPointer,
+ pointerSegments,
+} from "@hyperjump/json-pointer";
+import {
+ createDocumentRepresentation,
+ type DocumentRepresentation,
+} from "./reference";
+
+export type SourceDocumentReference = Readonly<{
+ documentUrl: string;
+ representation: DocumentRepresentation;
+}>;
+
+export type SourceReferenceOccurrence = Readonly<{
+ sourceDocumentId: string;
+ referenceId: string;
+ reference: SourceDocumentReference;
+}>;
+
+export type DocumentReferenceSyntaxErrorCode =
+ | "INVALID_BASE_URL"
+ | "INVALID_REFERENCE_URL"
+ | "INVALID_DOCUMENT_URL"
+ | "INVALID_FRAGMENT_ENCODING"
+ | "INVALID_FRAGMENT"
+ | "INVALID_JSON_POINTER"
+ | "INVALID_REPRESENTATION";
+
+export class DocumentReferenceSyntaxError extends Error {
+ readonly code: DocumentReferenceSyntaxErrorCode;
+ readonly value: unknown;
+
+ constructor({
+ code,
+ message,
+ value,
+ cause,
+ }: {
+ code: DocumentReferenceSyntaxErrorCode;
+ message: string;
+ value: unknown;
+ cause?: unknown;
+ }) {
+ super(message, { cause });
+ this.name = "DocumentReferenceSyntaxError";
+ this.code = code;
+ this.value = value;
+ }
+}
+
+const parseAbsoluteUrl = ({
+ value,
+ code,
+ label,
+}: {
+ value: unknown;
+ code: "INVALID_BASE_URL" | "INVALID_DOCUMENT_URL";
+ label: string;
+}) => {
+ if (typeof value !== "string" && value instanceof URL === false) {
+ throw new DocumentReferenceSyntaxError({
+ code,
+ message: `${label} must be an absolute URL`,
+ value,
+ });
+ }
+ try {
+ return new URL(value);
+ } catch (cause) {
+ throw new DocumentReferenceSyntaxError({
+ code,
+ message: `${label} must be an absolute URL`,
+ value,
+ cause,
+ });
+ }
+};
+
+const getRepresentation = (encodedFragment: string): DocumentRepresentation => {
+ if (encodedFragment === "") {
+ return createDocumentRepresentation({ type: "document" });
+ }
+ let fragment: string;
+ try {
+ fragment = decodeURIComponent(encodedFragment);
+ } catch (cause) {
+ throw new DocumentReferenceSyntaxError({
+ code: "INVALID_FRAGMENT_ENCODING",
+ message: "Document reference fragment is not valid URI encoding",
+ value: encodedFragment,
+ cause,
+ });
+ }
+ if (fragment === "body") {
+ return createDocumentRepresentation({ type: "markdown-body" });
+ }
+ if (fragment === "frontmatter") {
+ return createDocumentRepresentation({ type: "markdown-frontmatter" });
+ }
+ if (fragment.startsWith("/") === false) {
+ throw new DocumentReferenceSyntaxError({
+ code: "INVALID_FRAGMENT",
+ message:
+ "Document reference fragment must be a JSON Pointer, body, or frontmatter",
+ value: fragment,
+ });
+ }
+ try {
+ return createDocumentRepresentation({
+ type: "json",
+ path: [...pointerSegments(fragment)],
+ });
+ } catch (cause) {
+ throw new DocumentReferenceSyntaxError({
+ code: "INVALID_JSON_POINTER",
+ message: "Document reference fragment is not a valid JSON Pointer",
+ value: fragment,
+ cause,
+ });
+ }
+};
+
+/** Parses and resolves one authored URI reference without performing I/O. */
+export const parseSourceDocumentReference = ({
+ value,
+ baseUrl,
+}: {
+ value: unknown;
+ baseUrl: string | URL;
+}): SourceDocumentReference => {
+ const base = parseAbsoluteUrl({
+ value: baseUrl,
+ code: "INVALID_BASE_URL",
+ label: "Document reference base",
+ });
+ base.hash = "";
+ if (typeof value !== "string") {
+ throw new DocumentReferenceSyntaxError({
+ code: "INVALID_REFERENCE_URL",
+ message: "Document reference must be a string URI reference",
+ value,
+ });
+ }
+ let resolved: URL;
+ try {
+ resolved = new URL(value, base);
+ } catch (cause) {
+ throw new DocumentReferenceSyntaxError({
+ code: "INVALID_REFERENCE_URL",
+ message: "Document reference is not a valid URI reference",
+ value,
+ cause,
+ });
+ }
+ const representation = getRepresentation(resolved.hash.slice(1));
+ resolved.hash = "";
+ return Object.freeze({
+ documentUrl: resolved.href,
+ representation,
+ });
+};
+
+const serializeRepresentation = (representation: DocumentRepresentation) => {
+ if (representation.type === "document") {
+ return "";
+ }
+ if (representation.type === "markdown-body") {
+ return "body";
+ }
+ if (representation.type === "markdown-frontmatter") {
+ return "frontmatter";
+ }
+ let pointer: string = emptyJsonPointer;
+ for (const segment of representation.path) {
+ pointer = appendJsonPointerSegment(segment, pointer);
+ }
+ return encodeURIComponent(pointer);
+};
+
+/** Serializes a normalized source reference to one canonical absolute URI. */
+export const serializeSourceDocumentReference = (
+ input: SourceDocumentReference
+) => {
+ const documentUrl = parseAbsoluteUrl({
+ value: input.documentUrl,
+ code: "INVALID_DOCUMENT_URL",
+ label: "Referenced document",
+ });
+ if (documentUrl.hash !== "") {
+ throw new DocumentReferenceSyntaxError({
+ code: "INVALID_DOCUMENT_URL",
+ message: "Referenced document URL must not contain a fragment",
+ value: input.documentUrl,
+ });
+ }
+ let representation: DocumentRepresentation;
+ try {
+ representation = createDocumentRepresentation(input.representation);
+ } catch (cause) {
+ throw new DocumentReferenceSyntaxError({
+ code: "INVALID_REPRESENTATION",
+ message: "Document reference representation is invalid",
+ value: input.representation,
+ cause,
+ });
+ }
+ const fragment = serializeRepresentation(representation);
+ if (fragment !== "") {
+ documentUrl.hash = fragment;
+ }
+ return documentUrl.href;
+};
diff --git a/packages/content-engine/src/document-graph/reference.test.ts b/packages/content-engine/src/document-graph/reference.test.ts
new file mode 100644
index 0000000000..8a473b91db
--- /dev/null
+++ b/packages/content-engine/src/document-graph/reference.test.ts
@@ -0,0 +1,49 @@
+import { describe, expect, test } from "vitest";
+import { createDocumentReference } from "./reference";
+
+describe("document reference", () => {
+ test("creates an immutable normalized reference", () => {
+ const reference = createDocumentReference({
+ documentId: "author",
+ revision: "sha256:author",
+ representation: { type: "json", path: ["profile", "name"] },
+ });
+
+ expect(reference).toEqual({
+ documentId: "author",
+ revision: "sha256:author",
+ representation: { type: "json", path: ["profile", "name"] },
+ });
+ expect(Object.isFrozen(reference)).toBe(true);
+ expect(Object.isFrozen(reference.representation)).toBe(true);
+ expect(reference.representation.type).toBe("json");
+ if (reference.representation.type === "json") {
+ expect(Object.isFrozen(reference.representation.path)).toBe(true);
+ }
+ });
+
+ test.each([
+ {
+ documentId: "",
+ revision: "sha256:author",
+ representation: { type: "document" },
+ },
+ {
+ documentId: "author",
+ revision: "",
+ representation: { type: "document" },
+ },
+ {
+ documentId: "author",
+ revision: "sha256:author",
+ representation: { type: "json", path: ["profile", 0] },
+ },
+ {
+ documentId: "author",
+ revision: "sha256:author",
+ representation: { type: "json", path: [] },
+ },
+ ])("rejects an invalid normalized reference", (reference) => {
+ expect(() => createDocumentReference(reference)).toThrow();
+ });
+});
diff --git a/packages/content-engine/src/document-graph/reference.ts b/packages/content-engine/src/document-graph/reference.ts
new file mode 100644
index 0000000000..ae1779398a
--- /dev/null
+++ b/packages/content-engine/src/document-graph/reference.ts
@@ -0,0 +1,51 @@
+import { array, discriminatedUnion, literal, strictObject, string } from "zod";
+
+export const documentRepresentation = discriminatedUnion("type", [
+ strictObject({ type: literal("document") }),
+ strictObject({
+ type: literal("json"),
+ path: array(string()).min(1),
+ }),
+ strictObject({ type: literal("markdown-body") }),
+ strictObject({ type: literal("markdown-frontmatter") }),
+]);
+
+export type DocumentRepresentation =
+ | Readonly<{ type: "document" }>
+ | Readonly<{ type: "json"; path: readonly string[] }>
+ | Readonly<{ type: "markdown-body" }>
+ | Readonly<{ type: "markdown-frontmatter" }>;
+
+export const documentReference = strictObject({
+ documentId: string().min(1),
+ revision: string().min(1),
+ representation: documentRepresentation,
+});
+
+export type DocumentReference = Readonly<{
+ documentId: string;
+ revision: string;
+ representation: DocumentRepresentation;
+}>;
+
+export const createDocumentRepresentation = (
+ input: unknown
+): DocumentRepresentation => {
+ const representation = documentRepresentation.parse(input);
+ if (representation.type === "json") {
+ return Object.freeze({
+ ...representation,
+ path: Object.freeze([...representation.path]),
+ });
+ }
+ return Object.freeze(representation);
+};
+
+/** Validates and freezes the storage-independent form of a document reference. */
+export const createDocumentReference = (input: unknown): DocumentReference => {
+ const reference = documentReference.parse(input);
+ return Object.freeze({
+ ...reference,
+ representation: createDocumentRepresentation(reference.representation),
+ });
+};
diff --git a/packages/content-engine/src/document-graph/resolver.test.ts b/packages/content-engine/src/document-graph/resolver.test.ts
new file mode 100644
index 0000000000..933c10efa4
--- /dev/null
+++ b/packages/content-engine/src/document-graph/resolver.test.ts
@@ -0,0 +1,141 @@
+import { describe, expect, test } from "vitest";
+import { createDocumentGraph } from "./graph";
+import { DocumentGraphResolutionError, resolveDocumentGraph } from "./resolver";
+
+const graph = createDocumentGraph({
+ nodes: [
+ { id: "post", revision: "post-r1", contentRef: "content:post" },
+ { id: "author", revision: "author-r1", contentRef: "content:author" },
+ { id: "avatar", revision: "avatar-r1", contentRef: "content:avatar" },
+ { id: "unused", revision: "unused-r1", contentRef: "content:unused" },
+ ],
+ edges: [
+ {
+ sourceId: "post",
+ referenceId: "author",
+ reference: {
+ documentId: "author",
+ revision: "author-r1",
+ representation: { type: "json", path: ["name"] },
+ },
+ },
+ {
+ sourceId: "post",
+ referenceId: "avatar",
+ reference: {
+ documentId: "avatar",
+ revision: "avatar-r1",
+ representation: { type: "document" },
+ },
+ },
+ {
+ sourceId: "author",
+ referenceId: "avatar",
+ reference: {
+ documentId: "avatar",
+ revision: "avatar-r1",
+ representation: { type: "document" },
+ },
+ },
+ ],
+});
+
+describe("document graph resolver", () => {
+ test("loads the reachable closure once with bounded concurrency and assembles dependency-first", async () => {
+ type Source = { id: string };
+ type Value = { id: string; references: Record<string, unknown> };
+ let active = 0;
+ let maximumActive = 0;
+ const loaded: string[] = [];
+ const assembled: string[] = [];
+
+ const result = await resolveDocumentGraph<Source, Value>({
+ graph,
+ rootIds: ["post"],
+ concurrency: 2,
+ load: async (node) => {
+ active += 1;
+ maximumActive = Math.max(maximumActive, active);
+ loaded.push(node.id);
+ await Promise.resolve();
+ active -= 1;
+ return { id: node.id };
+ },
+ select: ({ reference, value }) =>
+ reference.representation.type === "json"
+ ? `${value.id}:${reference.representation.path.join(".")}`
+ : value.id,
+ assemble: ({ node, references }) => {
+ assembled.push(node.id);
+ return {
+ id: node.id,
+ references: Object.fromEntries(references),
+ };
+ },
+ });
+
+ expect(new Set(loaded)).toEqual(new Set(["post", "author", "avatar"]));
+ expect(loaded).toHaveLength(3);
+ expect(loaded).not.toContain("unused");
+ expect(maximumActive).toBe(2);
+ expect(assembled).toEqual(["avatar", "author", "post"]);
+ expect(result.roots).toEqual([
+ {
+ id: "post",
+ references: {
+ author: "author:name",
+ avatar: "avatar",
+ },
+ },
+ ]);
+ expect(result.values.get("author")).toEqual({
+ id: "author",
+ references: { avatar: "avatar" },
+ });
+ });
+
+ test("wraps a document load failure with document context", async () => {
+ await expect(
+ resolveDocumentGraph({
+ graph,
+ rootIds: ["post"],
+ concurrency: 2,
+ load: async (node) => {
+ if (node.id === "author") {
+ throw new Error("offline");
+ }
+ return node.id;
+ },
+ assemble: ({ source }) => source,
+ })
+ ).rejects.toMatchObject({
+ code: "DOCUMENT_LOAD_FAILED",
+ documentId: "author",
+ } satisfies Partial<DocumentGraphResolutionError>);
+ });
+
+ test("loads a shared content reference once for multiple document identities", async () => {
+ const aliasGraph = createDocumentGraph({
+ nodes: [
+ { id: "first", revision: "shared-r1", contentRef: "content:shared" },
+ { id: "second", revision: "shared-r1", contentRef: "content:shared" },
+ ],
+ edges: [],
+ });
+ let loadCount = 0;
+
+ const result = await resolveDocumentGraph({
+ graph: aliasGraph,
+ rootIds: ["first", "second"],
+ concurrency: 2,
+ load: async () => {
+ loadCount += 1;
+ return "shared";
+ },
+ assemble: ({ node, source }) => `${node.id}:${source}`,
+ });
+
+ expect(loadCount).toBe(1);
+ expect(result.roots).toEqual(["first:shared", "second:shared"]);
+ });
+});
diff --git a/packages/content-engine/src/document-graph/resolver.ts b/packages/content-engine/src/document-graph/resolver.ts
new file mode 100644
index 0000000000..28979636b7
--- /dev/null
+++ b/packages/content-engine/src/document-graph/resolver.ts
@@ -0,0 +1,202 @@
+import { mapBounded } from "../async-utils";
+import {
+ getDocumentGraphClosure,
+ type DocumentGraph,
+ type DocumentGraphNode,
+} from "./graph";
+import { getDocumentGraphEdgesBySourceId } from "./graph-utils";
+import type { DocumentReference } from "./reference";
+
+export type DocumentGraphResolutionErrorCode =
+ | "REQUEST_CANCELLED"
+ | "DOCUMENT_LOAD_FAILED"
+ | "REPRESENTATION_SELECTOR_REQUIRED"
+ | "DOCUMENT_SELECTION_FAILED"
+ | "DOCUMENT_ASSEMBLY_FAILED";
+
+export class DocumentGraphResolutionError extends Error {
+ readonly code: DocumentGraphResolutionErrorCode;
+ readonly documentId?: string;
+ readonly referenceId?: string;
+
+ constructor({
+ code,
+ message,
+ documentId,
+ referenceId,
+ cause,
+ }: {
+ code: DocumentGraphResolutionErrorCode;
+ message: string;
+ documentId?: string;
+ referenceId?: string;
+ cause?: unknown;
+ }) {
+ super(message, { cause });
+ this.name = "DocumentGraphResolutionError";
+ this.code = code;
+ this.documentId = documentId;
+ this.referenceId = referenceId;
+ }
+}
+
+export type ResolvedDocumentGraph<Value> = Readonly<{
+ roots: readonly Value[];
+ values: ReadonlyMap<string, Value>;
+}>;
+
+const assertActive = (signal: AbortSignal | undefined) => {
+ if (signal?.aborted) {
+ throw new DocumentGraphResolutionError({
+ code: "REQUEST_CANCELLED",
+ message: "Document graph resolution was cancelled",
+ cause: signal.reason,
+ });
+ }
+};
+
+/**
+ * Loads a reachable graph in parallel, then assembles it dependency-first.
+ * Parsing and representation semantics stay behind the injected callbacks.
+ */
+export const resolveDocumentGraph = async <Source, Value>({
+ graph,
+ rootIds,
+ concurrency,
+ signal,
+ load,
+ select,
+ assemble,
+}: {
+ graph: DocumentGraph;
+ rootIds: readonly string[];
+ concurrency: number;
+ signal?: AbortSignal;
+ load: (
+ node: DocumentGraphNode,
+ options: { signal?: AbortSignal }
+ ) => Promise<Source>;
+ select?: (input: {
+ reference: DocumentReference;
+ value: NoInfer<Value>;
+ sourceNode: DocumentGraphNode;
+ targetNode: DocumentGraphNode;
+ }) => unknown | Promise<unknown>;
+ assemble: (input: {
+ node: DocumentGraphNode;
+ source: Source;
+ references: ReadonlyMap<string, unknown>;
+ }) => Value | Promise<Value>;
+}): Promise<ResolvedDocumentGraph<Value>> => {
+ assertActive(signal);
+ const closure = getDocumentGraphClosure({ graph, rootIds });
+ const nodesById = new Map(closure.map((node) => [node.id, node]));
+ const sources = new Map<string, Source>();
+ const loadGroups = new Map<
+ string,
+ { representative: DocumentGraphNode; nodes: DocumentGraphNode[] }
+ >();
+ for (const node of closure) {
+ const group = loadGroups.get(node.contentRef);
+ if (group === undefined) {
+ loadGroups.set(node.contentRef, { representative: node, nodes: [node] });
+ } else {
+ group.nodes.push(node);
+ }
+ }
+ await mapBounded([...loadGroups.values()], concurrency, async (group) => {
+ assertActive(signal);
+ const node = group.representative;
+ try {
+ const source = await load(node, { signal });
+ for (const groupedNode of group.nodes) {
+ sources.set(groupedNode.id, source);
+ }
+ } catch (error) {
+ if (signal?.aborted) {
+ assertActive(signal);
+ }
+ throw new DocumentGraphResolutionError({
+ code: "DOCUMENT_LOAD_FAILED",
+ message: `Document ${node.id} could not be loaded`,
+ documentId: node.id,
+ cause: error,
+ });
+ }
+ });
+
+ const edgesBySourceId = getDocumentGraphEdgesBySourceId(graph.edges);
+ const values = new Map<string, Value>();
+ for (const node of closure) {
+ assertActive(signal);
+ const references = new Map<string, unknown>();
+ for (const edge of edgesBySourceId.get(node.id) ?? []) {
+ const targetNode = nodesById.get(edge.reference.documentId);
+ if (
+ targetNode === undefined ||
+ values.has(edge.reference.documentId) === false
+ ) {
+ throw new DocumentGraphResolutionError({
+ code: "DOCUMENT_ASSEMBLY_FAILED",
+ message: `Document ${node.id} dependency ${edge.reference.documentId} is unavailable`,
+ documentId: node.id,
+ referenceId: edge.referenceId,
+ });
+ }
+ const targetValue = values.get(edge.reference.documentId) as Value;
+ let selected: unknown;
+ if (select === undefined) {
+ if (edge.reference.representation.type !== "document") {
+ throw new DocumentGraphResolutionError({
+ code: "REPRESENTATION_SELECTOR_REQUIRED",
+ message: `Document ${node.id} reference ${edge.referenceId} requires a representation selector`,
+ documentId: node.id,
+ referenceId: edge.referenceId,
+ });
+ }
+ selected = targetValue;
+ } else {
+ try {
+ selected = await select({
+ reference: edge.reference,
+ value: targetValue,
+ sourceNode: node,
+ targetNode,
+ });
+ } catch (error) {
+ throw new DocumentGraphResolutionError({
+ code: "DOCUMENT_SELECTION_FAILED",
+ message: `Document ${node.id} reference ${edge.referenceId} could not be selected`,
+ documentId: node.id,
+ referenceId: edge.referenceId,
+ cause: error,
+ });
+ }
+ }
+ references.set(edge.referenceId, selected);
+ }
+ if (sources.has(node.id) === false) {
+ throw new DocumentGraphResolutionError({
+ code: "DOCUMENT_ASSEMBLY_FAILED",
+ message: `Document ${node.id} source is unavailable`,
+ documentId: node.id,
+ });
+ }
+ const source = sources.get(node.id) as Source;
+ try {
+ values.set(node.id, await assemble({ node, source, references }));
+ } catch (error) {
+ throw new DocumentGraphResolutionError({
+ code: "DOCUMENT_ASSEMBLY_FAILED",
+ message: `Document ${node.id} could not be assembled`,
+ documentId: node.id,
+ cause: error,
+ });
+ }
+ }
+
+ return Object.freeze({
+ roots: Object.freeze(rootIds.map((rootId) => values.get(rootId) as Value)),
+ values,
+ });
+};
diff --git a/packages/content-engine/src/document-graph/source-compiler.test.ts b/packages/content-engine/src/document-graph/source-compiler.test.ts
new file mode 100644
index 0000000000..2fa9a89517
--- /dev/null
+++ b/packages/content-engine/src/document-graph/source-compiler.test.ts
@@ -0,0 +1,129 @@
+import { describe, expect, test } from "vitest";
+import {
+ compileDocumentSourceGraph,
+ DocumentSourceCompilationError,
+} from "./source-compiler";
+
+const documents = [
+ {
+ id: "post",
+ documentUrl: "https://content.webstudio.test/posts/hello.json",
+ revision: "post-r1",
+ contentRef: "content:post",
+ format: "json" as const,
+ source:
+ '{"author":{"$ref":"../authors/ada.md#frontmatter"},"body":{"$ref":"../authors/ada.md#body"}}',
+ },
+ {
+ id: "author",
+ documentUrl: "https://content.webstudio.test/authors/ada.md",
+ revision: "author-r1",
+ contentRef: "content:author",
+ format: "markdown" as const,
+ source:
+ "---\nname: Ada\navatar:\n $ref: ../media/ada.json#/url\n---\nWriter.\n",
+ },
+ {
+ id: "avatar",
+ documentUrl: "https://content.webstudio.test/media/ada.json",
+ revision: "avatar-r1",
+ contentRef: "content:avatar",
+ format: "json" as const,
+ source: '{"url":"/ada.png"}',
+ },
+];
+
+describe("document source graph compiler", () => {
+ test("discovers mixed-format references and compiles a deterministic graph", async () => {
+ const graph = await compileDocumentSourceGraph({
+ documents: [...documents].reverse(),
+ concurrency: 2,
+ });
+
+ expect(graph.nodes.map(({ id }) => id)).toEqual([
+ "author",
+ "avatar",
+ "post",
+ ]);
+ expect(graph.nodes.map(({ id, format }) => [id, format])).toEqual([
+ ["author", "markdown"],
+ ["avatar", "json"],
+ ["post", "json"],
+ ]);
+ expect(graph.edges).toEqual([
+ {
+ sourceId: "author",
+ referenceId: "#frontmatter/avatar",
+ reference: {
+ documentId: "avatar",
+ revision: "avatar-r1",
+ representation: { type: "json", path: ["url"] },
+ },
+ },
+ {
+ sourceId: "post",
+ referenceId: "#/author",
+ reference: {
+ documentId: "author",
+ revision: "author-r1",
+ representation: { type: "markdown-frontmatter" },
+ },
+ },
+ {
+ sourceId: "post",
+ referenceId: "#/body",
+ reference: {
+ documentId: "author",
+ revision: "author-r1",
+ representation: { type: "markdown-body" },
+ },
+ },
+ ]);
+ });
+
+ test("reports analysis failures with their source document", async () => {
+ await expect(
+ compileDocumentSourceGraph({
+ documents: [
+ {
+ ...documents[0],
+ source: '{"author":{"$ref":42}}',
+ },
+ ],
+ concurrency: 1,
+ })
+ ).rejects.toMatchObject({
+ code: "DOCUMENT_ANALYSIS_FAILED",
+ documentId: "post",
+ cause: expect.objectContaining({
+ code: "INVALID_REFERENCE_MARKER",
+ referenceId: "#/author",
+ }),
+ } satisfies Partial<DocumentSourceCompilationError>);
+ });
+
+ test("rejects an already-cancelled compilation before reading sources", async () => {
+ const controller = new AbortController();
+ controller.abort("cancelled");
+ let read = false;
+
+ await expect(
+ compileDocumentSourceGraph({
+ documents: [
+ {
+ ...documents[0],
+ source: {
+ async *[Symbol.asyncIterator]() {
+ read = true;
+ yield new Uint8Array();
+ },
+ },
+ },
+ ],
+ concurrency: 1,
+ signal: controller.signal,
+ })
+ ).rejects.toMatchObject({ code: "REQUEST_CANCELLED" });
+ expect(read).toBe(false);
+ });
+});
diff --git a/packages/content-engine/src/document-graph/source-compiler.ts b/packages/content-engine/src/document-graph/source-compiler.ts
new file mode 100644
index 0000000000..4d7b115ddd
--- /dev/null
+++ b/packages/content-engine/src/document-graph/source-compiler.ts
@@ -0,0 +1,134 @@
+import { mapBounded } from "../async-utils";
+import type { ByteSource } from "../byte-stream";
+import { contentEngineLimits } from "../limits";
+import { compareStrings } from "../canonical-json";
+import { compileDocumentGraph, type DocumentDescriptor } from "./compiler";
+import { analyzeDocumentSource, type DocumentFormat } from "./document-adapter";
+import type { DocumentGraph } from "./graph";
+import type { SourceReferenceOccurrence } from "./reference-codec";
+
+export type DocumentSourceDescriptor = DocumentDescriptor &
+ Readonly<{
+ format: DocumentFormat;
+ source: ByteSource;
+ }>;
+
+export type DocumentSourceCompilationErrorCode =
+ | "REQUEST_CANCELLED"
+ | "ROOT_NOT_FOUND"
+ | "DOCUMENT_ANALYSIS_FAILED";
+
+export class DocumentSourceCompilationError extends Error {
+ readonly code: DocumentSourceCompilationErrorCode;
+ readonly documentId?: string;
+
+ constructor({
+ code,
+ message,
+ documentId,
+ cause,
+ }: {
+ code: DocumentSourceCompilationErrorCode;
+ message: string;
+ documentId?: string;
+ cause?: unknown;
+ }) {
+ super(message, { cause });
+ this.name = "DocumentSourceCompilationError";
+ this.code = code;
+ this.documentId = documentId;
+ }
+}
+
+const assertActive = (signal: AbortSignal | undefined) => {
+ if (signal?.aborted) {
+ throw new DocumentSourceCompilationError({
+ code: "REQUEST_CANCELLED",
+ message: "Document source graph compilation was cancelled",
+ cause: signal.reason,
+ });
+ }
+};
+
+/** Discovers references from bounded sources, then compiles graph metadata only. */
+export const compileDocumentSourceGraph = async ({
+ documents,
+ rootIds,
+ concurrency = contentEngineLimits.concurrentContentReads,
+ maximumBytes = contentEngineLimits.hydratedFileBytes,
+ signal,
+}: {
+ documents: readonly DocumentSourceDescriptor[];
+ rootIds?: readonly string[];
+ concurrency?: number;
+ maximumBytes?: number;
+ signal?: AbortSignal;
+}): Promise<DocumentGraph> => {
+ assertActive(signal);
+ // Validate the complete catalog without reading document payloads.
+ compileDocumentGraph({ documents, references: [] });
+ const documentsById = new Map(
+ documents.map((document) => [document.id, document])
+ );
+ const documentsByUrl = new Map(
+ documents.map((document) => [new URL(document.documentUrl).href, document])
+ );
+ const pendingIds = new Set(rootIds ?? documents.map(({ id }) => id));
+ const analyzedIds = new Set<string>();
+ const references: SourceReferenceOccurrence[] = [];
+
+ while (pendingIds.size > 0) {
+ const frontier = [...pendingIds].sort(compareStrings);
+ pendingIds.clear();
+ const analyzed = await mapBounded(
+ frontier,
+ concurrency,
+ async (documentId) => {
+ const document = documentsById.get(documentId);
+ if (document === undefined) {
+ throw new DocumentSourceCompilationError({
+ code: "ROOT_NOT_FOUND",
+ message: `Document source graph root ${documentId} does not exist`,
+ documentId,
+ });
+ }
+ assertActive(signal);
+ try {
+ const result = await analyzeDocumentSource({
+ format: document.format,
+ source: document.source,
+ sourceDocumentId: document.id,
+ documentUrl: document.documentUrl,
+ maximumBytes,
+ });
+ return { document, references: result.references };
+ } catch (cause) {
+ assertActive(signal);
+ throw new DocumentSourceCompilationError({
+ code: "DOCUMENT_ANALYSIS_FAILED",
+ message: `Document ${document.id} could not be analyzed`,
+ documentId: document.id,
+ cause,
+ });
+ }
+ }
+ );
+ for (const { document } of analyzed) {
+ analyzedIds.add(document.id);
+ }
+ for (const result of analyzed) {
+ references.push(...result.references);
+ for (const occurrence of result.references) {
+ const target = documentsByUrl.get(occurrence.reference.documentUrl);
+ if (target !== undefined && analyzedIds.has(target.id) === false) {
+ pendingIds.add(target.id);
+ }
+ }
+ }
+ }
+ assertActive(signal);
+ return compileDocumentGraph({
+ documents: documents.filter(({ id }) => analyzedIds.has(id)),
+ references,
+ });
+};
diff --git a/packages/content-engine/src/index.ts b/packages/content-engine/src/index.ts
index 3f9f3743d1..1d4c540632 100644
--- a/packages/content-engine/src/index.ts
+++ b/packages/content-engine/src/index.ts
@@ -5,7 +5,9 @@ export * from "./hydration";
export * from "./structured-query";
export * from "./projection";
export * from "./content-artifact";
+export * from "./content-runtime-artifact";
export * from "./content-database";
export * from "./request";
export * from "./query-source";
export * from "./query-error";
+export * from "./document-graph";
diff --git a/packages/content-engine/src/published-runtime.test.ts b/packages/content-engine/src/published-runtime.test.ts
index 31c7b70f21..9f3971f081 100644
--- a/packages/content-engine/src/published-runtime.test.ts
+++ b/packages/content-engine/src/published-runtime.test.ts
@@ -1,15 +1,18 @@
import { afterEach, describe, expect, test, vi } from "vitest";
import { assetQuery, type AssetFileDocument } from "./schema";
-import { createAssetIndex } from "./asset-index";
+import { compileContentArtifact, createAssetIndex } from "./asset-index";
import { createCanonicalAssetFileEntry } from "./canonical";
+import { createContentDatabase } from "./content-database";
+import { createContentRuntimeArtifact } from "./content-runtime-artifact";
import {
createContentCompilationPlan,
createLiteralContentCompilationQuery,
} from "./compilation-plan";
import {
- createGeneratedAssetResourceRuntime,
- createPublishedAssetResourceFetch,
+ createGeneratedAssetResourceRuntime as createGeneratedRuntime,
+ createPublishedAssetResourceFetch as createPublishedRuntime,
} from "./published-runtime";
+import { createDocumentGraph } from "./document-graph";
const revision = `sha256:${"a".repeat(64)}`;
const document: AssetFileDocument = {
@@ -27,6 +30,26 @@ const document: AssetFileDocument = {
};
const runtimeAssets = { "post-1": { url: "/assets/post.md" } };
+const createPublishedAssetResourceFetch = (
+ options: Omit<Parameters<typeof createPublishedRuntime>[0], "artifact"> & {
+ artifact: Parameters<typeof createContentRuntimeArtifact>[0];
+ }
+) =>
+ createPublishedRuntime({
+ ...options,
+ artifact: createContentRuntimeArtifact(options.artifact),
+ });
+
+const createGeneratedAssetResourceRuntime = (
+ options: Omit<Parameters<typeof createGeneratedRuntime>[0], "artifact"> & {
+ artifact: Parameters<typeof createContentRuntimeArtifact>[0];
+ }
+) =>
+ createGeneratedRuntime({
+ ...options,
+ artifact: createContentRuntimeArtifact(options.artifact),
+ });
+
const createRuntime = async () => {
const index = await createAssetIndex({
projectId: "project-1",
@@ -110,15 +133,18 @@ describe("published asset resource runtime", () => {
],
});
const networkFetch = vi.fn();
+ const fallback = vi.fn(async () => new Response("fallback"));
+ const onDocumentGraphEvent = vi.fn();
vi.stubGlobal("fetch", networkFetch);
const createGeneratedFetch = createGeneratedAssetResourceRuntime({
deploymentId: "build-same-origin",
artifact: index,
runtimeAssets,
+ onDocumentGraphEvent,
});
const generatedFetch = await createGeneratedFetch({
request: new Request("https://site.example/blog"),
- fallback: vi.fn(async () => new Response("fallback")),
+ fallback,
});
const overview = await generatedFetch(queryRequest());
@@ -127,7 +153,7 @@ describe("published asset resource runtime", () => {
expect(overview.status).toBe(200);
const overviewData = await overview.json();
expect(overviewData).toMatchObject({
- items: [{ id: "post-1" }],
+ items: [{ id: "post-1", properties: { title: "Post" } }],
});
expect(overviewData).not.toHaveProperty("database");
expect(overviewData).not.toHaveProperty("__diagnostics__");
@@ -135,6 +161,603 @@ describe("published asset resource runtime", () => {
items: [{ id: "post-1", content: { text: "Post" } }],
});
expect(networkFetch).not.toHaveBeenCalled();
+ expect(fallback).not.toHaveBeenCalled();
+ expect(onDocumentGraphEvent).not.toHaveBeenCalled();
+ });
+
+ test("assembles equivalent graph results in local, SSG, SSR, and published runtimes", async () => {
+ const post = {
+ ...document,
+ _id: "post",
+ name: "post.json",
+ path: "content/post.json",
+ key: "post",
+ extension: "json",
+ mimeType: "application/json",
+ revision: "post-r1",
+ contentRef: "storage:post",
+ properties: {
+ title: "Hello",
+ author: { $ref: "./author.md#frontmatter" },
+ },
+ };
+ const author = {
+ ...document,
+ _id: "author",
+ name: "author.md",
+ path: "content/author.md",
+ key: "author",
+ revision: "author-r1",
+ contentRef: "storage:author",
+ properties: { name: "Ada" },
+ };
+ const graph = createDocumentGraph({
+ nodes: [
+ {
+ id: "post",
+ revision: "post-r1",
+ contentRef: "storage:post",
+ format: "json",
+ },
+ {
+ id: "author",
+ revision: "author-r1",
+ contentRef: "storage:author",
+ format: "markdown",
+ },
+ ],
+ edges: [
+ {
+ sourceId: "post",
+ referenceId: "#/author",
+ reference: {
+ documentId: "author",
+ revision: "author-r1",
+ representation: { type: "markdown-frontmatter" },
+ },
+ },
+ ],
+ });
+ const { artifact } = await compileContentArtifact({
+ projectId: "project-1",
+ entries: [post, author].map((value) =>
+ createCanonicalAssetFileEntry({
+ projectId: "project-1",
+ document: value,
+ })
+ ),
+ documentGraph: graph,
+ });
+ const fetchDocument = vi.fn(async (input: RequestInfo | URL) => {
+ const pathname = new URL(String(input), "https://site.example").pathname;
+ return new Response(
+ pathname.endsWith("post.json")
+ ? '{"title":"Hello","author":{"$ref":"./author.md#frontmatter"}}'
+ : "---\nname: Ada\nrole: Writer\n---\nBio\n"
+ );
+ });
+ const graphQuery = assetQuery.parse({
+ where: { all: [{ field: ["id"], operator: "eq", value: "post" }] },
+ limit: 1,
+ output: {
+ mode: "fields",
+ includeMetadata: false,
+ fields: [
+ ["properties", "title"],
+ ["properties", "author"],
+ ],
+ },
+ });
+ const localResult = await createContentDatabase({
+ artifact,
+ }).queryWithDocumentGraph({
+ request: { query: graphQuery },
+ load: async (node) => ({
+ format: node.format as "json" | "markdown",
+ revision: node.revision,
+ source:
+ node.id === "post"
+ ? '{"title":"Hello","author":{"$ref":"./author.md#frontmatter"}}'
+ : "---\nname: Ada\nrole: Writer\n---\nBio\n",
+ }),
+ });
+ const events: unknown[] = [];
+ const runtimeFetch = createPublishedAssetResourceFetch({
+ baseUrl: "https://site.example",
+ deploymentId: "graph-build",
+ artifact,
+ runtimeAssets: {
+ post: { url: "/assets/post.json", contentRef: "storage:post" },
+ author: { url: "/assets/author.md", contentRef: "storage:author" },
+ },
+ fetchDocument,
+ onDocumentGraphEvent: (event) => events.push(event),
+ });
+
+ const requestInit = () => ({
+ method: "POST",
+ body: JSON.stringify({ query: graphQuery }),
+ });
+ const request = () => runtimeFetch("/$resources/assets", requestInit());
+
+ const response = await request();
+
+ expect(localResult).toMatchObject({
+ items: [
+ {
+ id: "post",
+ properties: {
+ title: "Hello",
+ author: { name: "Ada", role: "Writer" },
+ },
+ },
+ ],
+ });
+ await expect(response?.json()).resolves.toMatchObject({
+ items: [
+ {
+ id: "post",
+ properties: {
+ title: "Hello",
+ author: { name: "Ada", role: "Writer" },
+ },
+ },
+ ],
+ });
+ await expect((await request())?.json()).resolves.toMatchObject({
+ items: [{ id: "post" }],
+ });
+ expect(fetchDocument).toHaveBeenCalledTimes(1);
+ expect(fetchDocument).toHaveBeenCalledWith(
+ new URL("https://site.example/assets/author.md"),
+ expect.anything()
+ );
+ expect(events).toEqual(
+ expect.arrayContaining([
+ { type: "roots-selected", rootCount: 1 },
+ { type: "resolution-started", rootCount: 1, documentCount: 2 },
+ {
+ type: "document-fetch-completed",
+ documentId: "author",
+ revision: "author-r1",
+ },
+ { type: "resolution-completed", rootCount: 1, documentCount: 2 },
+ ])
+ );
+
+ const ssgFetch = createPublishedAssetResourceFetch({
+ baseUrl: "https://webstudio.local",
+ deploymentId: "graph-ssg-build",
+ artifact,
+ runtimeAssets: {
+ post: { url: "/assets/post.json", contentRef: "storage:post" },
+ author: { url: "/assets/author.md", contentRef: "storage:author" },
+ },
+ fetchDocument,
+ });
+ const ssgResponse = await ssgFetch("/$resources/assets", requestInit());
+ await expect(ssgResponse?.json()).resolves.toMatchObject(localResult);
+ expect(fetchDocument).toHaveBeenCalledTimes(2);
+
+ const createGeneratedFetch = createGeneratedAssetResourceRuntime({
+ deploymentId: "graph-build",
+ artifact,
+ runtimeAssets: {
+ post: { url: "/assets/post.json", contentRef: "storage:post" },
+ author: { url: "/assets/author.md", contentRef: "storage:author" },
+ },
+ onDocumentGraphEvent: (event) => events.push(event),
+ });
+ const generatedFetch = await createGeneratedFetch({
+ request: new Request("https://site.example/blog/post"),
+ fallback: fetchDocument,
+ });
+ const generatedResponse = await generatedFetch(
+ new Request("https://site.example/$resources/assets", requestInit())
+ );
+ await expect(generatedResponse.json()).resolves.toMatchObject({
+ items: [
+ {
+ id: "post",
+ properties: { author: { name: "Ada", role: "Writer" } },
+ },
+ ],
+ });
+ expect(fetchDocument).toHaveBeenCalledTimes(3);
+ expect(() =>
+ createPublishedAssetResourceFetch({
+ baseUrl: "https://site.example",
+ deploymentId: "incomplete-graph-build",
+ artifact,
+ runtimeAssets: { post: { url: "/assets/post.json" } },
+ fetchDocument,
+ })
+ ).toThrow("Published document URL is unavailable for author");
+ expect(() =>
+ createPublishedAssetResourceFetch({
+ baseUrl: "https://site.example",
+ deploymentId: "inline-graph-source-build",
+ artifact,
+ runtimeAssets: {
+ author: {
+ url: "/assets/author.md",
+ contentRef: "storage:author",
+ },
+ },
+ fetchDocument,
+ })
+ ).not.toThrow();
+ });
+
+ test("fetches a selected Markdown body from the CDN without bundling it", async () => {
+ const sources = {
+ first: "---\nslug: first\n---\nFirst stored body\n",
+ second: "---\nslug: second\n---\nSecond stored body\n",
+ };
+ const markdownDocuments = (["first", "second"] as const).map(
+ (id): AssetFileDocument => ({
+ ...document,
+ _id: id,
+ name: `${id}.md`,
+ path: `posts/${id}.md`,
+ key: id,
+ size: new TextEncoder().encode(sources[id]).byteLength,
+ revision: `${id}-r1`,
+ contentRef: `storage:${id}`,
+ properties: {
+ slug: id,
+ title: id === "first" ? "First" : "Second",
+ },
+ })
+ );
+ const plan = createContentCompilationPlan([
+ {
+ id: "post",
+ where: {
+ all: [
+ {
+ field: ["properties", "slug"],
+ operator: "eq",
+ value: { type: "dynamic" },
+ },
+ ],
+ },
+ sort: [],
+ limit: { type: "literal", value: 1 },
+ offset: { type: "literal", value: 0 },
+ output: {
+ mode: "fields",
+ includeMetadata: false,
+ fields: [["properties", "title"]],
+ },
+ content: { mode: "markdown-body" },
+ },
+ ]);
+ expect(plan).toBeDefined();
+ const { artifact } = await compileContentArtifact({
+ projectId: "project-1",
+ entries: markdownDocuments.map((value) => ({
+ ...createCanonicalAssetFileEntry({
+ projectId: "project-1",
+ document: value,
+ }),
+ content: sources[value._id as keyof typeof sources],
+ contentRequired: true,
+ })),
+ plan,
+ documentGraph: createDocumentGraph({
+ nodes: markdownDocuments.map((value) => ({
+ id: value._id,
+ revision: value.revision,
+ contentRef: value.contentRef,
+ format: "markdown" as const,
+ })),
+ edges: [],
+ }),
+ });
+ const runtimeArtifact = createContentRuntimeArtifact(artifact);
+ const fetchDocument = vi.fn(async (input: RequestInfo | URL) => {
+ const id = String(input).includes("second.md") ? "second" : "first";
+ return new Response(sources[id]);
+ });
+ const runtimeFetch = createPublishedRuntime({
+ baseUrl: "https://site.example",
+ deploymentId: "markdown-body-reference",
+ artifact: runtimeArtifact,
+ runtimeAssets: {
+ first: { url: "/assets/first.md", contentRef: "storage:first" },
+ second: { url: "/assets/second.md", contentRef: "storage:second" },
+ },
+ fetchDocument,
+ });
+
+ expect(runtimeArtifact.contents).toBeUndefined();
+ expect(JSON.stringify(runtimeArtifact)).not.toContain("stored body");
+ const response = await runtimeFetch("/$resources/assets", {
+ method: "POST",
+ body: JSON.stringify({
+ query: {
+ where: {
+ all: [
+ {
+ field: ["properties", "slug"],
+ operator: "eq",
+ value: "second",
+ },
+ ],
+ },
+ limit: 1,
+ output: {
+ mode: "fields",
+ includeMetadata: false,
+ fields: [["properties", "title"]],
+ },
+ content: { mode: "markdown-body" },
+ },
+ }),
+ });
+
+ await expect(response?.json()).resolves.toMatchObject({
+ items: [
+ {
+ id: "second",
+ properties: { title: "Second" },
+ content: { text: "Second stored body\n" },
+ },
+ ],
+ });
+ expect(fetchDocument).toHaveBeenCalledOnce();
+ expect(String(fetchDocument.mock.calls[0][0])).toContain("second.md");
+ });
+
+ test("hydrates parallel CDN roots with one cached shared dependency", async () => {
+ const createJsonDocument = (id: string): AssetFileDocument => ({
+ ...document,
+ _id: id,
+ name: `${id}.json`,
+ path: `content/${id}.json`,
+ key: id,
+ extension: "json",
+ mimeType: "application/json",
+ revision: `${id}-r1`,
+ contentRef: `storage:${id}`,
+ properties: {
+ title: id,
+ author: { $ref: "./author.json#/profile" },
+ },
+ });
+ const postA = createJsonDocument("post-a");
+ const postB = createJsonDocument("post-b");
+ const author: AssetFileDocument = {
+ ...createJsonDocument("author"),
+ properties: { profile: { name: "Ada" } },
+ };
+ const graph = createDocumentGraph({
+ nodes: [postA, postB, author].map((value) => ({
+ id: value._id,
+ revision: value.revision,
+ contentRef: value.contentRef,
+ format: "json" as const,
+ })),
+ edges: [postA, postB].map((value) => ({
+ sourceId: value._id,
+ referenceId: "#/author",
+ reference: {
+ documentId: "author",
+ revision: "author-r1",
+ representation: { type: "json" as const, path: ["profile"] },
+ },
+ })),
+ });
+ const { artifact } = await compileContentArtifact({
+ projectId: "project-1",
+ entries: [postA, postB, author].map((value) =>
+ createCanonicalAssetFileEntry({
+ projectId: "project-1",
+ document: value,
+ })
+ ),
+ documentGraph: graph,
+ });
+ const pending = new Map<string, (response: Response) => void>();
+ const fetchDocument = vi.fn(
+ (input: RequestInfo | URL) =>
+ new Promise<Response>((resolve) => {
+ pending.set(new URL(String(input)).pathname, resolve);
+ })
+ );
+ const runtimeFetch = createPublishedAssetResourceFetch({
+ baseUrl: "https://site.example",
+ deploymentId: "parallel-graph-build",
+ artifact,
+ runtimeAssets: {
+ "post-a": {
+ url: "/assets/post-a.json",
+ contentRef: "storage:post-a",
+ },
+ "post-b": {
+ url: "/assets/post-b.json",
+ contentRef: "storage:post-b",
+ },
+ author: {
+ url: "/assets/author.json",
+ contentRef: "storage:author",
+ },
+ },
+ fetchDocument,
+ });
+ const request = () =>
+ runtimeFetch("/$resources/assets", {
+ method: "POST",
+ body: JSON.stringify({
+ query: {
+ where: {
+ all: [{ field: ["id"], operator: "ne", value: "author" }],
+ },
+ sort: [{ field: ["id"], direction: "asc" }],
+ limit: 2,
+ output: {
+ mode: "fields",
+ includeMetadata: false,
+ fields: [
+ ["properties", "title"],
+ ["properties", "author"],
+ ],
+ },
+ },
+ }),
+ });
+
+ const responsePromise = request();
+ await vi.waitFor(() => expect(fetchDocument).toHaveBeenCalledOnce());
+ pending.get("/assets/author.json")?.(
+ new Response('{"profile":{"name":"Ada"}}')
+ );
+
+ await expect((await responsePromise)?.json()).resolves.toMatchObject({
+ items: [
+ { id: "post-a", properties: { author: { name: "Ada" } } },
+ { id: "post-b", properties: { author: { name: "Ada" } } },
+ ],
+ });
+ await expect((await request())?.json()).resolves.toMatchObject({
+ items: [{ id: "post-a" }, { id: "post-b" }],
+ });
+ expect(fetchDocument).toHaveBeenCalledTimes(1);
+ expect(
+ fetchDocument.mock.calls.filter(([input]) =>
+ String(input).includes("/assets/author.json")
+ )
+ ).toHaveLength(1);
+ });
+
+ test("maps CDN document limits and in-flight cancellation to query failures", async () => {
+ const graphDocument: AssetFileDocument = {
+ ...document,
+ _id: "graph-post",
+ name: "graph-post.json",
+ path: "content/graph-post.json",
+ key: "graph-post",
+ extension: "json",
+ mimeType: "application/json",
+ revision: "graph-post-r1",
+ contentRef: "storage:graph-post",
+ properties: { author: { $ref: "./author.json" } },
+ };
+ const { artifact } = await compileContentArtifact({
+ projectId: "project-1",
+ entries: [
+ createCanonicalAssetFileEntry({
+ projectId: "project-1",
+ document: graphDocument,
+ }),
+ ],
+ documentGraph: createDocumentGraph({
+ nodes: [
+ {
+ id: graphDocument._id,
+ revision: graphDocument.revision,
+ contentRef: graphDocument.contentRef,
+ format: "json",
+ },
+ {
+ id: "graph-author",
+ revision: "graph-author-r1",
+ contentRef: "storage:graph-author",
+ format: "json",
+ },
+ ],
+ edges: [
+ {
+ sourceId: graphDocument._id,
+ referenceId: "#/author",
+ reference: {
+ documentId: "graph-author",
+ revision: "graph-author-r1",
+ representation: { type: "document" },
+ },
+ },
+ ],
+ }),
+ });
+ const request = (signal?: AbortSignal) =>
+ new Request("https://site.example/$resources/assets", {
+ method: "POST",
+ signal,
+ body: JSON.stringify({
+ query: {
+ where: {
+ all: [{ field: ["id"], operator: "eq", value: "graph-post" }],
+ },
+ limit: 1,
+ output: {
+ mode: "fields",
+ includeMetadata: false,
+ fields: [["properties", "author"]],
+ },
+ },
+ }),
+ });
+ const runtimeAssets = {
+ "graph-post": {
+ url: "/assets/graph-post.json",
+ contentRef: "storage:graph-post",
+ },
+ "graph-author": {
+ url: "/assets/graph-author.json",
+ contentRef: "storage:graph-author",
+ },
+ };
+ const oversizedRuntime = createPublishedAssetResourceFetch({
+ baseUrl: "https://site.example",
+ deploymentId: "graph-limit-build",
+ artifact,
+ runtimeAssets,
+ fetchDocument: async (input) =>
+ new Response(
+ String(input).endsWith("graph-post.json")
+ ? '{"author":{"$ref":"./author.json"}}'
+ : `{"value":"${"a".repeat(1024 * 1024)}"}`
+ ),
+ });
+
+ const oversized = await oversizedRuntime(request());
+ expect(oversized?.status).toBe(400);
+ await expect(oversized?.json()).resolves.toMatchObject({
+ error: {
+ code: "CONTENT_LIMIT_EXCEEDED",
+ details: {
+ assetId: "graph-author",
+ contentByteLimit: 1024 * 1024,
+ },
+ },
+ });
+
+ const fetchDocument = vi.fn(
+ (_input: RequestInfo | URL, init?: RequestInit) =>
+ new Promise<Response>((_resolve, reject) => {
+ init?.signal?.addEventListener("abort", () =>
+ reject(init.signal?.reason)
+ );
+ })
+ );
+ const cancelledRuntime = createPublishedAssetResourceFetch({
+ baseUrl: "https://site.example",
+ deploymentId: "graph-cancel-build",
+ artifact,
+ runtimeAssets,
+ fetchDocument,
+ });
+ const controller = new AbortController();
+ const cancelledPromise = cancelledRuntime(request(controller.signal));
+ await vi.waitFor(() => expect(fetchDocument).toHaveBeenCalled());
+ controller.abort("test cancellation");
+
+ const cancelled = await cancelledPromise;
+ expect(cancelled?.status).toBe(499);
+ await expect(cancelled?.json()).resolves.toMatchObject({
+ error: { code: "REQUEST_CANCELLED" },
+ });
});
test("serves a materialized static query without candidate documents", async () => {
diff --git a/packages/content-engine/src/published-runtime.ts b/packages/content-engine/src/published-runtime.ts
index 6e0fc689ec..0b20912ecd 100644
--- a/packages/content-engine/src/published-runtime.ts
+++ b/packages/content-engine/src/published-runtime.ts
@@ -1,14 +1,21 @@
import {
createAssetResourceQueryFailure,
- type ContentArtifactV1,
type AssetResourceQueryFailure,
} from "./schema";
import { sha256Hex } from "./canonical-json";
-import { getContentArtifactReferencedAssetIds } from "./content-artifact";
-import { createContentDatabase } from "./content-database";
+import { createRuntimeContentDatabase } from "./content-database";
import { readAssetQueryRequest } from "./request";
import type { AssetRuntimeData } from "./structured-query";
import { getAssetResourceQueryError } from "./query-error";
+import { contentEngineLimits } from "./limits";
+import {
+ createCachedDocumentSourceLoader,
+ createHttpDocumentSourceLoader,
+ type CachedDocumentSource,
+ type DocumentSourceCache,
+ type DocumentGraphRuntimeObserver,
+} from "./document-graph";
+import type { ContentRuntimeArtifact } from "./content-runtime-artifact";
const assetsResourceUrl = "/$resources/assets";
@@ -51,18 +58,13 @@ const getCacheKey = async ({
request,
}: {
deploymentId: string;
- artifact: ContentArtifactV1;
+ artifact: ContentRuntimeArtifact;
request: Request;
}) => {
const body = await request.clone().text();
const cacheControl = request.headers.get("cache-control");
const hash = await sha256Hex(
- JSON.stringify([
- deploymentId,
- artifact.integrity.checksum,
- body,
- cacheControl,
- ])
+ JSON.stringify([deploymentId, artifact.revision, body, cacheControl])
);
const url = new URL(request.url);
url.searchParams.set("ws-asset-resource", hash);
@@ -75,39 +77,135 @@ export const createPublishedAssetResourceFetch = ({
runtimeAssets,
cache,
baseUrl,
+ fetchDocument = globalThis.fetch,
+ onDocumentGraphEvent,
}: {
deploymentId: string;
- artifact: ContentArtifactV1;
+ artifact: ContentRuntimeArtifact;
runtimeAssets: Readonly<Record<string, AssetRuntimeData>>;
cache?: Pick<Cache, "match" | "put">;
baseUrl: string | URL;
+ fetchDocument?: typeof fetch;
+ onDocumentGraphEvent?: DocumentGraphRuntimeObserver;
}) => {
validateRuntimeAssets({ artifact, runtimeAssets });
+ const documentCache = createMemoryDocumentSourceCache();
return createPublishedAssetResourceHandler({
deploymentId,
artifact,
runtimeAssets,
cache,
baseUrl,
- database: createContentDatabase({ artifact }),
+ database: createRuntimeContentDatabase({ artifact }),
+ fetchDocument,
+ documentCache,
+ onDocumentGraphEvent,
});
};
+const createMemoryDocumentSourceCache = (): DocumentSourceCache => {
+ const values = new Map<string, CachedDocumentSource>();
+ const maximumBytes = contentEngineLimits.hydratedTotalBytes * 4;
+ let usedBytes = 0;
+ return {
+ get: async (key) => {
+ const value = values.get(key);
+ if (value !== undefined) {
+ values.delete(key);
+ values.set(key, value);
+ }
+ return value;
+ },
+ set: async (key, source) => {
+ if (source.bytes.byteLength > maximumBytes) {
+ return;
+ }
+ const previous = values.get(key);
+ if (previous !== undefined) {
+ usedBytes -= previous.bytes.byteLength;
+ values.delete(key);
+ }
+ values.set(key, source);
+ usedBytes += source.bytes.byteLength;
+ while (usedBytes > maximumBytes) {
+ const oldest = values.entries().next().value;
+ if (oldest === undefined) {
+ break;
+ }
+ values.delete(oldest[0]);
+ usedBytes -= oldest[1].bytes.byteLength;
+ }
+ },
+ };
+};
+
+const createPublishedDocumentLoader = ({
+ baseUrl,
+ runtimeAssets,
+ fetchDocument,
+ cache,
+ onEvent,
+}: {
+ baseUrl: string | URL;
+ runtimeAssets: Readonly<Record<string, AssetRuntimeData>>;
+ fetchDocument: typeof fetch;
+ cache: DocumentSourceCache;
+ onEvent?: DocumentGraphRuntimeObserver;
+}) =>
+ createCachedDocumentSourceLoader({
+ cache,
+ onEvent,
+ load: createHttpDocumentSourceLoader({
+ fetch: fetchDocument,
+ getRequest: (node) => {
+ const asset = runtimeAssets[node.id];
+ if (asset === undefined) {
+ throw new Error(
+ `Published document URL is unavailable for ${node.id}`
+ );
+ }
+ return new URL(asset.url, baseUrl);
+ },
+ getMetadata: ({ node }) => ({
+ format: node.format,
+ revision: node.revision,
+ }),
+ onEvent,
+ }),
+ });
+
const validateRuntimeAssets = ({
artifact,
runtimeAssets,
}: {
- artifact: ContentArtifactV1;
+ artifact: ContentRuntimeArtifact;
runtimeAssets: Readonly<Record<string, AssetRuntimeData>>;
}) => {
- const missingReferencedAssetId = getContentArtifactReferencedAssetIds(
- artifact
- ).find((assetId) => runtimeAssets[assetId] === undefined);
+ const missingReferencedAssetId = Object.values(artifact.assetReferences ?? {})
+ .flat()
+ .map(({ assetId }) => assetId)
+ .find((assetId) => runtimeAssets[assetId] === undefined);
if (missingReferencedAssetId !== undefined) {
throw new Error(
`Published referenced asset URL is unavailable for ${missingReferencedAssetId}`
);
}
+ const missingDocumentId = artifact.documentGraph?.nodes.find(
+ ({ id }) => runtimeAssets[id] === undefined
+ )?.id;
+ if (missingDocumentId !== undefined) {
+ throw new Error(
+ `Published document URL is unavailable for ${missingDocumentId}`
+ );
+ }
+ const staleDocumentId = artifact.documentGraph?.nodes.find(
+ ({ id, contentRef }) => runtimeAssets[id]?.contentRef !== contentRef
+ )?.id;
+ if (staleDocumentId !== undefined) {
+ throw new Error(
+ `Published document identity does not match graph node ${staleDocumentId}`
+ );
+ }
};
const createPublishedAssetResourceHandler = ({
@@ -117,15 +215,28 @@ const createPublishedAssetResourceHandler = ({
cache,
baseUrl,
database,
+ fetchDocument,
+ documentCache,
+ onDocumentGraphEvent,
}: {
deploymentId: string;
- artifact: ContentArtifactV1;
+ artifact: ContentRuntimeArtifact;
runtimeAssets: Readonly<Record<string, AssetRuntimeData>>;
cache?: Pick<Cache, "match" | "put">;
baseUrl: string | URL;
- database: ReturnType<typeof createContentDatabase>;
+ database: ReturnType<typeof createRuntimeContentDatabase>;
+ fetchDocument: typeof fetch;
+ documentCache: DocumentSourceCache;
+ onDocumentGraphEvent?: DocumentGraphRuntimeObserver;
}) => {
const baseOrigin = new URL(baseUrl).origin;
+ const loadDocument = createPublishedDocumentLoader({
+ baseUrl,
+ runtimeAssets,
+ fetchDocument,
+ cache: documentCache,
+ onEvent: onDocumentGraphEvent,
+ });
return async (
input: RequestInfo | URL,
init?: RequestInit
@@ -168,7 +279,13 @@ const createPublishedAssetResourceHandler = ({
});
}
const response = jsonResponse(
- await database.query(parsedRequest, undefined, runtimeAssets)
+ await database.queryWithDocumentGraph({
+ request: parsedRequest,
+ load: loadDocument,
+ runtimeAssets,
+ signal: request.signal,
+ onEvent: onDocumentGraphEvent,
+ })
);
if (
cacheKey !== undefined &&
@@ -208,10 +325,13 @@ export const createGeneratedAssetResourceRuntime = ({
deploymentId,
artifact,
runtimeAssets,
+ // Generated projects infer this API from bundled JavaScript.
+ onDocumentGraphEvent = undefined,
}: {
deploymentId: string;
- artifact: ContentArtifactV1;
+ artifact: ContentRuntimeArtifact;
runtimeAssets: Readonly<Record<string, AssetRuntimeData>>;
+ onDocumentGraphEvent?: DocumentGraphRuntimeObserver;
}) => {
const cacheStorage = globalThis.caches;
let cachePromise: Promise<Cache> | undefined;
@@ -228,7 +348,8 @@ export const createGeneratedAssetResourceRuntime = ({
(await getCache()).put(key, response),
};
validateRuntimeAssets({ artifact, runtimeAssets });
- const database = createContentDatabase({ artifact });
+ const database = createRuntimeContentDatabase({ artifact });
+ const documentCache = createMemoryDocumentSourceCache();
return async ({
request,
fallback,
@@ -244,6 +365,9 @@ export const createGeneratedAssetResourceRuntime = ({
cache,
baseUrl: origin,
database,
+ fetchDocument: fallback,
+ documentCache,
+ onDocumentGraphEvent,
});
return async (input, init) =>
(await fetchResource(input, init)) ?? fallback(input, init);
diff --git a/packages/content-engine/src/query-error.test.ts b/packages/content-engine/src/query-error.test.ts
new file mode 100644
index 0000000000..fd1267cb6c
--- /dev/null
+++ b/packages/content-engine/src/query-error.test.ts
@@ -0,0 +1,35 @@
+import { describe, expect, test } from "vitest";
+import {
+ DocumentGraphResolutionError,
+ DocumentResolutionLimitError,
+} from "./document-graph";
+import { getAssetResourceQueryError } from "./query-error";
+
+describe("asset resource graph query errors", () => {
+ test("maps nested document graph limits to structured content errors", () => {
+ const error = new DocumentGraphResolutionError({
+ code: "DOCUMENT_LOAD_FAILED",
+ message: "Document post could not be loaded",
+ documentId: "post",
+ cause: new DocumentResolutionLimitError({
+ code: "TOTAL_BYTES_EXCEEDED",
+ message: "Document graph resolution exceeds the total byte limit",
+ documentId: "post",
+ totalBytes: 100,
+ totalByteLimit: 50,
+ }),
+ });
+
+ expect(getAssetResourceQueryError(error)).toEqual({
+ code: "CONTENT_LIMIT_EXCEEDED",
+ message: "Document graph resolution exceeds the total byte limit",
+ retryable: false,
+ status: 400,
+ details: {
+ assetId: "post",
+ totalBytes: 100,
+ totalByteLimit: 50,
+ },
+ });
+ });
+});
diff --git a/packages/content-engine/src/query-error.ts b/packages/content-engine/src/query-error.ts
index d1ea9e510d..27a38d400a 100644
--- a/packages/content-engine/src/query-error.ts
+++ b/packages/content-engine/src/query-error.ts
@@ -4,6 +4,8 @@ import {
AssetIndexRevisionError,
AssetQueryExecutionError,
} from "./structured-query";
+import { DocumentResolutionLimitError } from "./document-graph/document-resolution";
+import { CachedDocumentLoaderError } from "./document-graph/cached-document-loader";
export type AssetResourceQueryError = Omit<
AssetResourceQueryFailure["error"],
@@ -42,4 +44,44 @@ export const getAssetResourceQueryError = (
status: 400,
};
}
+ const visited = new Set<unknown>();
+ let cause = error;
+ while (cause !== undefined && visited.has(cause) === false) {
+ if (cause instanceof DocumentResolutionLimitError) {
+ const details: Record<string, string | number> = {};
+ for (const [key, value] of Object.entries({
+ assetId: cause.documentId,
+ documentCount: cause.documentCount,
+ documentLimit: cause.documentLimit,
+ contentByteLimit: cause.contentByteLimit,
+ totalBytes: cause.totalBytes,
+ totalByteLimit: cause.totalByteLimit,
+ })) {
+ if (value !== undefined) {
+ details[key] = value;
+ }
+ }
+ return {
+ code: "CONTENT_LIMIT_EXCEEDED",
+ message: cause.message,
+ retryable: false,
+ details,
+ status: 400,
+ };
+ }
+ if (cause instanceof CachedDocumentLoaderError) {
+ return {
+ code: "CONTENT_LIMIT_EXCEEDED",
+ message: cause.message,
+ retryable: false,
+ details: {
+ assetId: cause.documentId,
+ contentByteLimit: cause.contentByteLimit,
+ },
+ status: 400,
+ };
+ }
+ visited.add(cause);
+ cause = cause instanceof Error ? cause.cause : undefined;
+ }
};
diff --git a/packages/content-engine/src/schema.ts b/packages/content-engine/src/schema.ts
index e06b76d4a5..31951a7574 100644
--- a/packages/content-engine/src/schema.ts
+++ b/packages/content-engine/src/schema.ts
@@ -21,6 +21,7 @@ import {
type QueryWhereTree,
} from "@webstudio-is/query-builder/runtime";
import { contentEngineLimits } from "./limits";
+import { documentGraphArtifactV1 } from "./document-graph/graph-artifact";
const relativeAssetPath = string()
.min(1)
@@ -176,6 +177,7 @@ export const contentArtifactV1 = strictObject({
version: literal(1),
assetRevision: sha256Revision,
documents: array(contentDatabaseDocument),
+ documentGraph: documentGraphArtifactV1.optional(),
contents: record(string().min(1), string()).optional(),
assetReferences: record(
string().min(1),
@@ -617,24 +619,29 @@ const contentDatabaseCapacityStats = contentDatabaseStats.pick({
truncated: true,
});
+export const assetQueryResult = strictObject({
+ items: array(assetQueryItem),
+ totalCount: number().int().nonnegative(),
+ hasMore: boolean(),
+});
+
+export type AssetQueryResult = Infer<typeof assetQueryResult>;
+
export const assetQueryPreviewDiagnostics = strictObject({
scope: literal("query-preview"),
query: contentDatabaseCapacityStats,
database: contentDatabaseCapacityStats,
+ artifacts: strictObject({
+ query: contentArtifactV1,
+ database: contentArtifactV1,
+ }).optional(),
+ unresolved: assetQueryResult.optional(),
});
export type AssetQueryPreviewDiagnostics = Infer<
typeof assetQueryPreviewDiagnostics
>;
-export const assetQueryResult = strictObject({
- items: array(assetQueryItem),
- totalCount: number().int().nonnegative(),
- hasMore: boolean(),
-});
-
-export type AssetQueryResult = Infer<typeof assetQueryResult>;
-
export const assetQueryPreviewResult = strictObject({
data: assetQueryResult,
__diagnostics__: assetQueryPreviewDiagnostics,
diff --git a/packages/content-engine/src/structured-query.ts b/packages/content-engine/src/structured-query.ts
index 6c0348c1eb..f3f72090c2 100644
--- a/packages/content-engine/src/structured-query.ts
+++ b/packages/content-engine/src/structured-query.ts
@@ -35,6 +35,8 @@ import type { MarkdownAssetReferences } from "./markdown-references";
export type AssetRuntimeData = {
url: string;
+ /** Immutable storage identity for graph-backed document URLs. */
+ contentRef?: string;
width?: number;
height?: number;
};
@@ -72,15 +74,20 @@ const isFilterOperatorCompatible = ({
fieldTypes: readonly AssetObservedFieldType[];
}) => getAssetQueryOperatorsForFieldTypes(fieldTypes).includes(filter.operator);
-const getCatalogField = (catalog: BuilderAssetFieldCatalog, path: string) =>
- Object.hasOwn(catalog.fields, path) ? catalog.fields[path] : undefined;
+const getCatalogField = (
+ catalog: BuilderAssetFieldCatalog | undefined,
+ path: string
+) =>
+ catalog !== undefined && Object.hasOwn(catalog.fields, path)
+ ? catalog.fields[path]
+ : undefined;
export const validateAssetQueryAgainstCatalog = ({
query: input,
catalog,
}: {
query: AssetQueryInput;
- catalog: BuilderAssetFieldCatalog;
+ catalog?: BuilderAssetFieldCatalog;
}) => {
const query = assetQuery.parse(input);
const referencedFieldPaths = new Map<string, AssetQueryFieldPath>();
@@ -93,11 +100,12 @@ export const validateAssetQueryAgainstCatalog = ({
// Dynamic fields are schemaless. The catalog describes the currently
// observed documents for authoring assistance, but deleting the last
// matching file must not invalidate an otherwise valid saved query.
- if (field === undefined) {
+ if (catalog !== undefined && field === undefined) {
warnings.push(`Asset field ${catalogPath} is not currently observed`);
} else if (
+ field !== undefined &&
isFilterOperatorCompatible({ filter, fieldTypes: field.types }) ===
- false
+ false
) {
warnings.push(
`Operator ${filter.operator} is not compatible with the currently observed types of ${catalogPath}`
@@ -127,9 +135,10 @@ export const validateAssetQueryAgainstCatalog = ({
// previously valid schemaless query fail at runtime.
if (order.field[0] === "properties") {
const field = getCatalogField(catalog, catalogPath);
- if (field === undefined) {
+ if (catalog !== undefined && field === undefined) {
warnings.push(`Asset field ${catalogPath} is not currently observed`);
} else if (
+ field !== undefined &&
field.types.some((type) => type === "object" || type === "array")
) {
warnings.push(
@@ -393,7 +402,7 @@ const toQueryItem = (
};
};
-const assertResultSize = (result: AssetQueryResult) => {
+export const assertAssetQueryResultSize = (result: AssetQueryResult) => {
if (
getUtf8ByteLength(serializeJsonDeterministically(result)) >
contentEngineLimits.resultBytes
@@ -413,7 +422,7 @@ export const executeAssetQuery = async ({
assetReferences,
}: {
query: AssetQueryInput;
- catalog: BuilderAssetFieldCatalog;
+ catalog?: BuilderAssetFieldCatalog;
documents: readonly ContentDatabaseDocument[];
read?: AssetResourceContentReader;
runtimeAssets?: Readonly<Record<string, AssetRuntimeData>>;
@@ -494,6 +503,6 @@ export const executeAssetQuery = async ({
totalCount: matched.length,
hasMore: query.offset + selected.length < matched.length,
} satisfies AssetQueryResult;
- assertResultSize(result);
+ assertAssetQueryResultSize(result);
return result;
};
diff --git a/packages/project-build/src/mcp.test.ts b/packages/project-build/src/mcp.test.ts
index abfe08868e..4a2c44ead8 100644
--- a/packages/project-build/src/mcp.test.ts
+++ b/packages/project-build/src/mcp.test.ts
@@ -1174,9 +1174,16 @@ describe("project session mcp adapter", () => {
expect(tool.description).toContain("Webstudio JavaScript expression");
expect(tool.description).toContain("<dataSourceName>.data");
expect(tool.description).toContain("<dataSourceName>.meta");
- expect(tool.description).toContain(".properties");
- expect(tool.description).toContain(".excerpt");
- expect(tool.description).toContain(".content.text");
+ expect(tool.description).toContain("markdown-body");
+ expect(tool.description).toContain("document reference");
+ expect(tool.description).toContain("item.content.text");
+ expect(tool.description).toContain(
+ "one final resource per rendered query"
+ );
+ expect(tool.description).toContain(
+ "static filters, limits, and offsets literal"
+ );
+ expect(tool.description).toContain("remove obsolete duplicates");
expect(getSchemaProperties(tool.inputSchema)).not.toEqual({});
}
});
@@ -4511,17 +4518,61 @@ describe("project session mcp adapter", () => {
);
expect(markdownBlogGuide.structuredContent.data).toEqual(
expect.objectContaining({
+ recipe: expect.objectContaining({
+ overviewResource: expect.objectContaining({
+ dataSourceName: "posts",
+ query: expect.objectContaining({
+ limit: { type: "literal", value: 20 },
+ offset: { type: "literal", value: 0 },
+ }),
+ }),
+ detailResource: expect.objectContaining({
+ dataSourceName: "post",
+ query: expect.objectContaining({
+ limit: { type: "literal", value: 1 },
+ offset: { type: "literal", value: 0 },
+ content: { mode: "markdown-body" },
+ }),
+ }),
+ overviewCollection: expect.objectContaining({
+ itemFragment: expect.stringContaining(
+ "collectionItem.properties.author.name"
+ ),
+ }),
+ detailCollection: expect.objectContaining({
+ itemFragment: expect.stringContaining(
+ "collectionItem.content.text"
+ ),
+ }),
+ }),
workflow: expect.arrayContaining([
+ expect.stringContaining(
+ 'meta.get_more_tools with {"tools":["create-assets-resource"]}'
+ ),
+ expect.stringContaining(
+ "Upload all Markdown source files together in one upload-assets call"
+ ),
+ expect.stringContaining('"format":"md"'),
+ expect.stringContaining("Do not create companion JSON descriptors"),
expect.stringContaining("exactly two Builder pages"),
+ expect.stringContaining("do not dry-run it"),
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("exactly one final Assets resource"),
+ expect.stringContaining(
+ "bounded metadata-only result can be materialized"
+ ),
+ expect.stringContaining("only one materialized overview query"),
+ expect.stringContaining('content.mode:"markdown-body"'),
+ expect.stringContaining("Do not reshape or stringify any field"),
+ expect.stringContaining('"value":"posts.data"'),
+ expect.stringContaining("only the Markdown document reference"),
expect.stringContaining('field:["extension"]'),
- expect.stringContaining("system.params.slug"),
expect.stringContaining("both pages load their content from Assets"),
]),
tools: expect.arrayContaining([
+ expect.objectContaining({ name: "upload-assets" }),
expect.objectContaining({ name: "list-pages" }),
expect.objectContaining({ name: "list-assets" }),
expect.objectContaining({ name: "insert-collection" }),
diff --git a/packages/project-build/src/mcp.ts b/packages/project-build/src/mcp.ts
index a4bd7616da..0b41721b1f 100644
--- a/packages/project-build/src/mcp.ts
+++ b/packages/project-build/src/mcp.ts
@@ -824,7 +824,7 @@ const insertCollectionMcpInputSchema = getOperationInputSchema({
});
const assetsResourceResultDescription =
- "Pass query as structured tool input rather than a JSON-stringified expression or manually authored resource body. Dynamic query values use readable Webstudio JavaScript expression syntax. Assets expose an ID-keyed map at <dataSourceName>.data and collection information at <dataSourceName>.meta. Each value has selected file fields at the top level, frontmatter or JSON fields in .properties, a derived .excerpt at the top level, and requested file content in .content.text.";
+ "Pass query as structured tool input using Webstudio JavaScript expressions rather than a JSON-stringified expression or manually authored resource body. Every reachable Assets resource contributes to one shared published database, so create only one final resource per rendered query; update an existing resource instead of creating a replacement, and remove obsolete duplicates. Keep static filters, limits, and offsets literal so bounded overview queries can be materialized. Use output mode fields, select only rendered fields, keep includeMetadata false, and use content mode none when file content is not rendered. For a Markdown detail page, query the Markdown asset directly and use content mode markdown-body; compilation keeps only its document reference in the bundle and fetches the selected body from Asset storage at runtime. Bind the resolved body from item.content.text. Assets expose an ID-keyed map at <dataSourceName>.data and collection information at <dataSourceName>.meta.";
const mcpOperationOverrides = new Map<
string,
@@ -2086,7 +2086,12 @@ export const mcpArgumentExamples: Record<string, readonly unknown[]> = {
{
field: ["extension"],
operator: "eq",
- value: { type: "literal", value: "md" },
+ value: { type: "literal", value: "json" },
+ },
+ {
+ field: ["properties", "kind"],
+ operator: "eq",
+ value: { type: "literal", value: "post" },
},
{
field: ["properties", "draft"],
@@ -2112,7 +2117,12 @@ export const mcpArgumentExamples: Record<string, readonly unknown[]> = {
{
field: ["extension"],
operator: "eq",
- value: { type: "literal", value: "md" },
+ value: { type: "literal", value: "json" },
+ },
+ {
+ field: ["properties", "kind"],
+ operator: "eq",
+ value: { type: "literal", value: "post" },
},
{
any: [
@@ -2131,7 +2141,12 @@ export const mcpArgumentExamples: Record<string, readonly unknown[]> = {
],
},
limit: "1",
- content: { mode: "markdown-body", maxBytes: 1_048_576 },
+ output: {
+ mode: "fields",
+ includeMetadata: false,
+ fields: [["properties", "body"]],
+ },
+ content: { mode: "none" },
},
},
],
@@ -5487,6 +5502,8 @@ const metaGoalGuides = [
pattern:
/markdown(?:-|\s)*(?:based|backed)?\s*blog|blog.*markdown|assets?(?:-|\s)*backed\s*blog/i,
tools: [
+ "create-asset-folder",
+ "upload-assets",
"list-pages",
"list-assets",
"get-asset-field-catalog",
@@ -5499,13 +5516,112 @@ const metaGoalGuides = [
"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.",
+ 'Call meta.get_more_tools with {"tools":["create-assets-resource"]} once for the complete nested query contract. Use exact tool names, not brief search, and do not repeat discovery for this workflow.',
+ 'Create one Blog asset folder. Upload all Markdown source files together in one upload-assets call with assetsDir ".webstudio/assets". Put queryable metadata such as slug, title, author, publishedAt, excerpt, and draft in each file\'s frontmatter. Every file must use {"name":"<filename>.md","type":"file","format":"md","folderId":"<blog-folder-id>","meta":{}}. Do not create companion JSON descriptors, use a combined format value, or retry a failed mutation; report its actionable error instead.',
+ '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". Create each page once with a committed call; do not dry-run it. Both pages load their content from Assets resources. Do not create one page per post or copy Markdown content into page-specific static structures.',
+ "Every reachable Assets data source contributes its query to one shared published database. Keep exactly one final Assets resource for the overview and one for the detail page. Never create a placeholder, preview copy, or repair replacement; update the existing scoped resource when requirements change and remove obsolete duplicates.",
+ 'Field paths are arrays of segments, for example field:["extension"]. Literal query values use {"type":"literal","value":"..."}; raw strings are runtime expressions. Keep every overview filter value, limit, and offset literal so the bounded metadata-only result can be materialized instead of retaining its fields across every article. Use a deterministic secondary ID sort. Query Markdown posts with static extension and blog-folder constraints before any dynamic condition. Use output.mode:"fields", includeMetadata:false, and only fields rendered by that route.',
+ 'Keep content.mode:"none" on the overview and use content.mode:"markdown-body" only on the detail route. The detail query should have exactly one dynamic value, system.params.slug, a literal limit of 1, and only the title and author metadata rendered above Markdown Embed. The published database keeps only the Markdown document reference and fetches the selected body from Asset storage at runtime.',
+ "Call create-assets-resource exactly once with recipe.overviewResource after substituting the returned /blog root id and Blog folder id. Then call it exactly once with recipe.detailResource after substituting the returned /blog/:slug root id and the same Blog folder id.",
+ 'Call insert-collection exactly once with the entire recipe.overviewCollection object and exactly once with the entire recipe.detailCollection object, changing only parentInstanceId to the returned root id. Do not reshape or stringify any field: data must remain the recipe object {"type":"expression","value":"posts.data"} or {"type":"expression","value":"post.data"}. Do not improvise another fragment or call meta.get_more_tools again.',
+ "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. The merged database must contain every source document without truncation, no embedded Markdown contents, and only one materialized overview query.",
+ "Verify only after both Collections succeed and confirm that both pages load their content from Assets. Call verify-page-responsive once for /blog and once for one concrete detail route, including empty/not-found behavior, before finishing. If any call fails, stop and report it without retrying.",
],
+ recipe: {
+ overviewResource: {
+ name: "Published posts",
+ scopeInstanceId: "<overview-root-id>",
+ dataSourceName: "posts",
+ query: {
+ where: {
+ all: [
+ {
+ field: ["extension"],
+ operator: "eq",
+ value: { type: "literal", value: "md" },
+ },
+ {
+ field: ["folderId"],
+ operator: "eq",
+ value: { type: "literal", value: "<blog-folder-id>" },
+ },
+ {
+ field: ["properties", "draft"],
+ operator: "ne",
+ value: { type: "literal", value: true },
+ },
+ ],
+ },
+ sort: [
+ { field: ["properties", "publishedAt"], direction: "desc" },
+ { field: ["id"], direction: "asc" },
+ ],
+ limit: { type: "literal", value: 20 },
+ offset: { type: "literal", value: 0 },
+ output: {
+ mode: "fields",
+ includeMetadata: false,
+ fields: [
+ ["properties", "title"],
+ ["properties", "slug"],
+ ["properties", "publishedAt"],
+ ["properties", "author"],
+ ["properties", "excerpt"],
+ ],
+ },
+ content: { mode: "none" },
+ },
+ },
+ detailResource: {
+ name: "Post by slug",
+ scopeInstanceId: "<detail-root-id>",
+ dataSourceName: "post",
+ query: {
+ where: {
+ all: [
+ {
+ field: ["extension"],
+ operator: "eq",
+ value: { type: "literal", value: "md" },
+ },
+ {
+ field: ["folderId"],
+ operator: "eq",
+ value: { type: "literal", value: "<blog-folder-id>" },
+ },
+ {
+ field: ["properties", "slug"],
+ operator: "eq",
+ value: "system.params.slug",
+ },
+ ],
+ },
+ limit: { type: "literal", value: 1 },
+ offset: { type: "literal", value: 0 },
+ output: {
+ mode: "fields",
+ includeMetadata: false,
+ fields: [
+ ["properties", "title"],
+ ["properties", "author"],
+ ],
+ },
+ content: { mode: "markdown-body" },
+ },
+ },
+ overviewCollection: {
+ parentInstanceId: "<overview-root-id>",
+ data: { type: "expression", value: "posts.data" },
+ itemFragment:
+ '<ws.element ws:tag="article"><ws.element ws:tag="h2">{expression`collectionItem.properties.title ?? "Untitled"`}</ws.element><ws.element ws:tag="p">{expression`collectionItem.properties.excerpt ?? ""`}</ws.element><ws.element ws:tag="p">By {expression`collectionItem.properties.author.name`}</ws.element><ws.element ws:tag="time">{expression`collectionItem.properties.publishedAt ?? ""`}</ws.element><ws.element ws:tag="a" href={expression`"/blog/" + collectionItem.properties.slug`}>Read article</ws.element></ws.element>',
+ },
+ detailCollection: {
+ parentInstanceId: "<detail-root-id>",
+ data: { type: "expression", value: "post.data" },
+ itemFragment:
+ '<ws.element ws:tag="article"><ws.element ws:tag="h1">{expression`collectionItem.properties.title ?? "Untitled"`}</ws.element><ws.element ws:tag="p">By {expression`collectionItem.properties.author.name`}</ws.element><$.MarkdownEmbed code={expression`collectionItem.content.text`} /></ws.element>',
+ },
+ },
},
{
pattern: /json\s*-?\s*ld|structured\s+data/i,
@@ -5722,6 +5838,9 @@ const getMetaGuide = (
tools: matches.map((tool) =>
serializeMetaGuideTool(tool, goalGuide === undefined)
),
+ ...(goalGuide !== undefined && "recipe" in goalGuide
+ ? { recipe: goalGuide.recipe }
+ : {}),
more:
goalGuide === undefined
? "The MCP handshake provides top-level argument contracts and required fields, while this guide includes exact examples plus complete schemas for selected complex tools. Call meta.get_more_tools once with all needed tool names only when a nested input shape is not covered here or when you need server/local behavior that the guide does not cover."
diff --git a/packages/protocol/src/builder-api/operation-docs.test.ts b/packages/protocol/src/builder-api/operation-docs.test.ts
index d4b7c5ba00..d4373d1908 100644
--- a/packages/protocol/src/builder-api/operation-docs.test.ts
+++ b/packages/protocol/src/builder-api/operation-docs.test.ts
@@ -80,6 +80,11 @@ test("guides agents to keep Assets content databases small", () => {
expect(getDescription("update-assets-resource")).toContain(
"only rendered fields"
);
+ for (const command of ["create-assets-resource", "update-assets-resource"]) {
+ expect(getDescription(command)).toContain("$ref");
+ expect(getDescription(command)).toContain("#body");
+ expect(getDescription(command)).toContain("content mode none");
+ }
expect(getDescription("preview-asset-query")).toContain("usedBytes");
expect(getDescription("preview-asset-query")).toContain("truncated");
});
diff --git a/packages/protocol/src/builder-api/operation-docs.ts b/packages/protocol/src/builder-api/operation-docs.ts
index e47541e2f3..a2585281cf 100644
--- a/packages/protocol/src/builder-api/operation-docs.ts
+++ b/packages/protocol/src/builder-api/operation-docs.ts
@@ -612,7 +612,7 @@ const curatedPublicApiOperationDocumentation = [
{
command: "create-assets-resource",
description:
- "Create a scoped Assets resource. Omit query to use the minimal default query. For an explicit query, minimize the content database by selecting only fields the page renders, keeping includeMetadata false unless required, and using content mode none unless file content is rendered. Preview concrete queries and inspect size diagnostics before saving.",
+ 'Create a scoped Assets resource. Omit query to use the minimal default query. For an explicit query, minimize the content database by selecting only fields the page renders, keeping includeMetadata false, and using content mode none. Do not embed Markdown with markdown-body when a JSON document can reference it as { "$ref": "./article.md#body" }; select that reference field instead. Embed file content only when document references cannot represent the source. Preview concrete queries and inspect size diagnostics before saving.',
requiredOptions: ["input", "json"],
examples: [
"webstudio create-assets-resource --input assets-resource.json --json",
@@ -621,7 +621,7 @@ const curatedPublicApiOperationDocumentation = [
{
command: "update-assets-resource",
description:
- "Update an Assets resource. Set query to null to restore the minimal default query. Keep explicit queries storage-efficient by selecting only rendered fields, keeping includeMetadata false unless required, and loading only the necessary file content after narrow filtering.",
+ 'Update an Assets resource. Set query to null to restore the minimal default query. Keep explicit queries storage-efficient by selecting only rendered fields, keeping includeMetadata false, and using content mode none. Prefer a JSON document field such as { "$ref": "./article.md#body" } over embedding Markdown with markdown-body; embed file content only when references cannot represent the source.',
requiredOptions: ["input", "json"],
examples: [
"webstudio update-assets-resource --input assets-resource-update.json --json",
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 7e90eceda4..6dd40b9ba2 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -1406,6 +1406,9 @@ importers:
packages/content-engine:
dependencies:
+ '@hyperjump/json-pointer':
+ specifier: 1.1.2
+ version: 1.1.2
'@webstudio-is/expression':
specifier: workspace:*
version: link:../expression
@@ -4310,6 +4313,9 @@ packages:
peerDependencies:
hono: ^4
+ '@hyperjump/[email protected]':
+ resolution: {integrity: sha512-zPNgu1zdhtjQHFNLGzvEsLDsLOEvhRj6u6ktIQmlz7YPESv5uF8SnAe3Dq0oL6gZ6OGWSLq2n7pphRNF6Hpg6w==}
+
resolution: {integrity: sha512-trnsAYxU3xnS1gPHPyU961coFyLkh4gAD/0zQ5mymY4yOZ+CYvsPqUbOFSw0aDM4y0tV7tiFxL/1XfXPNC6IPg==}
@@ -12887,6 +12893,8 @@ snapshots:
dependencies:
hono: 4.12.27
+ '@hyperjump/[email protected]': {}
+
'@iarna/[email protected]': {}